org.bouncycastle.asn1.ASN1GeneralizedTime Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1GeneralizedTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseCmpResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected PKIMessage buildErrorPkiMessage(ASN1OctetString tid,
    PKIHeader requestHeader, int failureCode, String statusText) {
  GeneralName respRecipient = requestHeader.getSender();

  PKIHeaderBuilder respHeader = new PKIHeaderBuilder(
      requestHeader.getPvno().getValue().intValue(), getSender(), respRecipient);
  respHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
  if (tid != null) {
    respHeader.setTransactionID(tid);
  }

  ASN1OctetString senderNonce = requestHeader.getSenderNonce();
  if (senderNonce != null) {
    respHeader.setRecipNonce(senderNonce);
  }

  PKIStatusInfo status = generateRejectionStatus(failureCode, statusText);
  ErrorMsgContent error = new ErrorMsgContent(status);
  PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, error);

  return new PKIMessage(respHeader.build(), body);
}
 
Example #2
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a formatted string value for the supplied generalized time object.
 *
 * @param time Generalized time
 * @return Formatted string
 * @throws ParseException If there is a problem formatting the generalized time
 */
private String formatGeneralizedTime(ASN1GeneralizedTime time)
    throws ParseException
{
	// Get generalized time as a string
	String sTime = time.getTime();

	// Setup date formatter with expected date format of string
	DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssz");

	// Create date object from string using formatter
	Date date = dateFormat.parse(sTime);

	// Re-format date - include time zone
	sTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(date);

	return escapeHtml(sTime);
}
 
Example #3
Source File: Time.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    if (derObject instanceof ASN1GeneralizedTime) {
        ASN1GeneralizedTime derGeneralizedTime = (ASN1GeneralizedTime) derObject;
        try {
            this.setTime(derGeneralizedTime.getDate());
        } catch (ParseException ex) {
            this.setTime(null);
        }
    } else if (derObject instanceof DERUTCTime) {
        DERUTCTime derUTCTime = (DERUTCTime) derObject;
        try {
            this.setTime(derUTCTime.getDate());
        } catch (ParseException exception) {
            this.setTime(null);
        }
    }
}
 
Example #4
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 *
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later.
 * The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1
 * type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 *
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/* this attribute is prohibited in PAdES B */
	if (padesUsage) {
		return;
	}

	final String contentIdentifierPrefix = parameters.getContentIdentifierPrefix();
	if (Utils.isStringNotBlank(contentIdentifierPrefix)) {
		if (Utils.isStringBlank(parameters.getContentIdentifierSuffix())) {
			StringBuilder suffixBuilder = new StringBuilder();
			suffixBuilder.append(new ASN1GeneralizedTime(new Date()).getTimeString());
			suffixBuilder.append(new SecureRandom().nextLong());
			parameters.setContentIdentifierSuffix(suffixBuilder.toString());
		}
		final String contentIdentifierString = contentIdentifierPrefix + parameters.getContentIdentifierSuffix();
		final ContentIdentifier contentIdentifier = new ContentIdentifier(contentIdentifierString.getBytes());
		final DERSet attrValues = new DERSet(contentIdentifier);
		final Attribute attribute = new Attribute(id_aa_contentIdentifier, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #5
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String dumpGeneralizedTime(ASN1GeneralizedTime asn1Time) {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));
	sb.append("GENERALIZED TIME=");

	Date date;
	try {
		date = asn1Time.getDate();
	} catch (ParseException e) {
		throw new RuntimeException("Cannot parse generalized time");
	}
	String formattedDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss.SSS z").format(date);

	sb.append(formattedDate);
	sb.append(" (");
	sb.append(asn1Time.getTime());
	sb.append(")");
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #6
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get Private Key Usage Period (2.5.29.16) extension value as a string.
 *
 * <pre>
 * PrivateKeyUsagePeriod ::= SEQUENCE {
 *       notBefore       [0]     GeneralizedTime OPTIONAL,
 *       notAfter        [1]     GeneralizedTime OPTIONAL }
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws ParseException If a date formatting problem occurs
 */
private String getPrivateKeyUsagePeriod(byte[] bValue)
    throws ParseException
{
	PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.getInstance(bValue);

	StringBuilder strBuff = new StringBuilder();
	ASN1GeneralizedTime dTime;

	if ((dTime = pkup.getNotBefore()) != null)
	{
		strBuff.append(
		    MessageFormat.format(RB.getString("PrivateKeyUsagePeriodNotBefore"), formatGeneralizedTime(dTime)));
	}

	if ((dTime = pkup.getNotAfter()) != null)
	{
		if (strBuff.length() != 0)
		{
			strBuff.append("<br><br>");
		}
		strBuff.append(
		    MessageFormat.format(RB.getString("PrivateKeyUsagePeriodNotAfter"), formatGeneralizedTime(dTime)));
	}

	return strBuff.toString();
}
 
Example #7
Source File: X509Ca.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Extension createInvalidityDateExtension(Date invalidityDate) {
  try {
    ASN1GeneralizedTime asnTime = new ASN1GeneralizedTime(invalidityDate);
    return new Extension(Extension.invalidityDate, false, asnTime.getEncoded());
  } catch (IOException ex) {
    throw new IllegalArgumentException("error encoding reason: " + ex.getMessage(), ex);
  }
}
 
Example #8
Source File: CaEnrollBenchmark.java    From xipki with Apache License 2.0 5 votes vote down vote up
public PKIMessage nextCertRequest() throws IOException, CertificateException {
  if (maxRequests > 0) {
    int num = processedRequests.getAndAdd(1);
    if (num >= maxRequests) {
      return null;
    }
  }

  CertReqMsg[] certReqMsgs = new CertReqMsg[num];

  for (int i = 0; i < num; i++) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();

    long thisIndex = index.getAndIncrement();
    certTempBuilder.setSubject(benchmarkEntry.getX500Name(thisIndex));

    SubjectPublicKeyInfo spki = benchmarkEntry.getSubjectPublicKeyInfo();
    certTempBuilder.setPublicKey(spki);
    CertTemplate certTemplate = certTempBuilder.build();
    CertRequest certRequest = new CertRequest(new ASN1Integer(i + 1), certTemplate, null);

    String utf8pairs = "certprofile?" + benchmarkEntry.getCertprofile() + "%";
    AttributeTypeAndValue certprofileInfo =
        new AttributeTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs,
            new DERUTF8String(utf8pairs));
    AttributeTypeAndValue[] atvs = new AttributeTypeAndValue[]{certprofileInfo};

    certReqMsgs[i] = new CertReqMsg(certRequest, RA_VERIFIED, atvs);
  }

  PKIHeaderBuilder builder = new PKIHeaderBuilder(
      PKIHeader.CMP_2000, conf.requestor(), conf.responder());
  builder.setMessageTime(new ASN1GeneralizedTime(new Date()));
  builder.setTransactionID(randomBytes(8));
  builder.setSenderNonce(randomBytes(8));
  builder.setGeneralInfo(IMPLICIT_CONFIRM);

  PKIBody body = new PKIBody(PKIBody.TYPE_CERT_REQ, new CertReqMessages(certReqMsgs));
  return new PKIMessage(builder.build(), body);
}
 
Example #9
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnPrivateKeyUsagePeriod(StringBuilder failureMsg,
    byte[] extensionValue, Date certNotBefore, Date certNotAfter) {
  ASN1GeneralizedTime notBefore = new ASN1GeneralizedTime(certNotBefore);
  Date dateNotAfter;
  Validity privateKeyUsagePeriod = certprofile.getPrivateKeyUsagePeriod();
  if (privateKeyUsagePeriod == null) {
    dateNotAfter = certNotAfter;
  } else {
    dateNotAfter = privateKeyUsagePeriod.add(certNotBefore);
    if (dateNotAfter.after(certNotAfter)) {
      dateNotAfter = certNotAfter;
    }
  }
  ASN1GeneralizedTime notAfter = new ASN1GeneralizedTime(dateNotAfter);

  org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod extValue =
      org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod.getInstance(extensionValue);

  ASN1GeneralizedTime time = extValue.getNotBefore();
  if (time == null) {
    failureMsg.append("notBefore is absent but expected present; ");
  } else if (!time.equals(notBefore)) {
    addViolation(failureMsg, "notBefore", time.getTimeString(), notBefore.getTimeString());
  }

  time = extValue.getNotAfter();
  if (time == null) {
    failureMsg.append("notAfter is absent but expected present; ");
  } else if (!time.equals(notAfter)) {
    addViolation(failureMsg, "notAfter", time.getTimeString(), notAfter.getTimeString());
  }
}
 
Example #10
Source File: SubjectChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getRdnTextValueOfRequest(RDN requestedRdn)
    throws BadCertTemplateException {
  ASN1ObjectIdentifier type = requestedRdn.getFirst().getType();
  ASN1Encodable vec = requestedRdn.getFirst().getValue();
  if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
    if (!(vec instanceof ASN1GeneralizedTime)) {
      throw new BadCertTemplateException("requested RDN is not of GeneralizedTime");
    }
    return ((ASN1GeneralizedTime) vec).getTimeString();
  } else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
    if (!(vec instanceof ASN1Sequence)) {
      throw new BadCertTemplateException("requested RDN is not of Sequence");
    }

    ASN1Sequence seq = (ASN1Sequence) vec;
    final int n = seq.size();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
      ASN1Encodable obj = seq.getObjectAt(i);
      String textValue = X509Util.rdnValueToString(obj);
      sb.append("[").append(i).append("]=").append(textValue).append(",");
    }

    return sb.toString();
  } else {
    return X509Util.rdnValueToString(vec);
  }
}
 
Example #11
Source File: CertprofileQa.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void checkTime(Time time, ValidationIssue issue) {
  ASN1Primitive asn1Time = time.toASN1Primitive();
  if (time.getDate().getTime() / 1000 < EPOCHTIME_2050010100) {
    if (!(asn1Time instanceof ASN1UTCTime)) {
      issue.setFailureMessage("not encoded as UTCTime");
    }
  } else {
    if (!(asn1Time instanceof ASN1GeneralizedTime)) {
      issue.setFailureMessage("not encoded as GeneralizedTime");
    }
  }
}
 
Example #12
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void extractArchiveCutOff(SingleResp bestSingleResp) {
	Extension extension = bestSingleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
	if (extension != null) {
		ASN1GeneralizedTime archiveCutOffAsn1 = (ASN1GeneralizedTime) extension.getParsedValue();
		try {
			archiveCutOff = archiveCutOffAsn1.getDate();
		} catch (ParseException e) {
			LOG.warn("Unable to extract id_pkix_ocsp_archive_cutoff : {}", e.getMessage());
		}
	}
}
 
Example #13
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Date toDate(final ASN1GeneralizedTime asn1Date) {
	try {
		return asn1Date.getDate();
	} catch (ParseException e) {
		throw new DSSException(e);
	}
}
 
Example #14
Source File: AbstractCRLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void extractExpiredCertsOnCRL(CRLValidity validity, byte[] expiredCertsOnCRLBinaries) {
	if (expiredCertsOnCRLBinaries != null) {
		try {
			ASN1OctetString octetString = (ASN1OctetString) ASN1Primitive.fromByteArray(expiredCertsOnCRLBinaries);
			Time time = Time.getInstance(ASN1Primitive.fromByteArray(octetString.getOctets()));
			if (time != null && time.toASN1Primitive() instanceof ASN1GeneralizedTime) {
				validity.setExpiredCertsOnCRL(time.getDate());
			} else {
				LOG.warn("Attribute 'expiredCertsOnCRL' found but ignored (should be encoded as ASN.1 GeneralizedTime)");
			}
		} catch (Exception e) {
			LOG.error("Unable to parse expiredCertsOnCRL on CRL : {}", e.getMessage(), e);
		}
	}
}
 
Example #15
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get dump of the supplied ASN.1 object.
 *
 * @param asn1Object
 *            ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(ASN1Primitive asn1Object) throws Asn1Exception, IOException {
	// Get dump of the supplied ASN.1 object incrementing the indent level of the output
	try {
		indentLevel++;

		if (asn1Object instanceof DERBitString) { // special case of ASN1String
			return dumpBitString((DERBitString) asn1Object);
		} else if (asn1Object instanceof ASN1String) {
			return dumpString((ASN1String) asn1Object);
		} else if (asn1Object instanceof ASN1UTCTime) {
			return dumpUTCTime((ASN1UTCTime) asn1Object);
		} else if (asn1Object instanceof ASN1GeneralizedTime) {
			return dumpGeneralizedTime((ASN1GeneralizedTime) asn1Object);
		} else if (asn1Object instanceof ASN1Sequence ||
				asn1Object instanceof ASN1Set ) {
			return dumpSetOrSequence(asn1Object);
		} else if (asn1Object instanceof ASN1TaggedObject) {
			return dumpTaggedObject((ASN1TaggedObject) asn1Object);
		} else if (asn1Object instanceof ASN1Boolean) {
			return dumpBoolean((ASN1Boolean) asn1Object);
		} else if (asn1Object instanceof ASN1Enumerated) {
			return dumpEnumerated((ASN1Enumerated) asn1Object);
		} else if (asn1Object instanceof ASN1Integer) {
			return dumpInteger((ASN1Integer) asn1Object);
		} else if (asn1Object instanceof ASN1Null) {
			return dumpNull();
		} else if (asn1Object instanceof ASN1ObjectIdentifier) {
			return dumpObjectIdentifier((ASN1ObjectIdentifier) asn1Object);
		} else if (asn1Object instanceof ASN1OctetString) {
			return dumpOctetString((ASN1OctetString) asn1Object);
		} else {
			throw new Asn1Exception("Unknown ASN.1 object: " + asn1Object.toString());
		}
	} finally {
		indentLevel--;
	}
}
 
Example #16
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getGeneralizedTimeString(ASN1GeneralizedTime notBefore) {
	// Get generalized time as a date
	Date date;
	try {
		date = notBefore.getDate();
	} catch (ParseException e) {
		throw new IllegalArgumentException("Cannot parse date");
	}

	return StringUtils.formatDate(date);
}
 
Example #17
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getAttributeValueString(ASN1ObjectIdentifier attributeType, ASN1Encodable attributeValue)
		throws IOException {

	/* AttributeValue ::= ANY  */

	// Get value string for recognized attribute types
	AttributeTypeType attributeTypeType = AttributeTypeType.resolveOid(attributeType.getId());

	switch (attributeTypeType) {
	case DATE_OF_BIRTH:
		return getGeneralizedTimeString(ASN1GeneralizedTime.getInstance(attributeValue));
	case SERIAL_NUMBER:
	case UNSTRUCTURED_ADDRESS:
	case COUNTRY_NAME:
	case GENDER:
	case COUNTRY_OF_CITIZENSHIP:
	case COUNTRY_OF_RESIDENCE:
		return DERPrintableString.getInstance(attributeValue).getString();
	case COMMON_NAME:
	case LOCALITY_NAME:
	case STATE_NAME:
	case STREET_ADDRESS:
	case ORGANIZATION_NAME:
	case ORGANIZATIONAL_UNIT:
	case TITLE:
	case USER_ID:
	case PLACE_OF_BIRTH:
		return DirectoryString.getInstance(attributeValue).getString();
	case MAIL:
	case EMAIL_ADDRESS:
	case UNSTRUCTURED_NAME:
	case DOMAIN_COMPONENT:
		return DERIA5String.getInstance(attributeValue).getString();
	default:
		// Attribute type not recognized - return hex string for value
		return HexUtil.getHexString(attributeValue.toASN1Primitive().getEncoded());
	}
}
 
Example #18
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getPrivateKeyUsagePeriodStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * PrivateKeyUsagePeriod ::= ASN1Sequence { notBefore [0]
	 * ASN1GeneralizedTime OPTIONAL, notAfter [1] ASN1GeneralizedTime OPTIONAL }
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	PrivateKeyUsagePeriod privateKeyUsagePeriod = PrivateKeyUsagePeriod.getInstance(value);

	ASN1GeneralizedTime notBefore = privateKeyUsagePeriod.getNotBefore();
	ASN1GeneralizedTime notAfter = privateKeyUsagePeriod.getNotAfter();

	if (notBefore != null) {
		sb.append(MessageFormat.format(res.getString("NotBeforePrivateKeyUsagePeriod"),
				getGeneralizedTimeString(notBefore)));
	} else {
		sb.append(MessageFormat.format(res.getString("NotBeforePrivateKeyUsagePeriod"),
				res.getString("NoValue")));
	}
	sb.append(NEWLINE);

	if (notAfter != null) {
		sb.append(MessageFormat.format(res.getString("NotAfterPrivateKeyUsagePeriod"),
				getGeneralizedTimeString(notAfter)));
	} else {
		sb.append(MessageFormat.format(res.getString("NotAfterPrivateKeyUsagePeriod"),
				res.getString("NoValue")));
	}
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #19
Source File: GeneralizedTime.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    if (derObject instanceof ASN1GeneralizedTime) {
        ASN1GeneralizedTime derGeneralizedTime = (ASN1GeneralizedTime) derObject;
        try {
            this.setDate(derGeneralizedTime.getDate());
        } catch (ParseException error) {
            throw new RuntimeException(error);
        }
    }
}
 
Example #20
Source File: SES_SignatureTest.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
@Test
void build() throws IOException, GeneralSecurityException {
    Path userSealPath = Paths.get("src/test/resources", "UserV4.esl");
    Path userP12 = Paths.get("src/test/resources", "USER.p12");


    SESeal seal = SESeal.getInstance(Files.readAllBytes(userSealPath));
    TBS_Sign toSign = new TBS_Sign()
            .setVersion(SES_Header.V4)
            .setEseal(seal)
            .setTimeInfo(new ASN1GeneralizedTime(new Date()))
            .setDataHash(new byte[32])
            .setPropertyInfo("/Doc_0/Signs/Sign_0/Signature.xml");

    Certificate useCert = PKCS12Tools.ReadUserCert(userP12, "private", "777777");
    PrivateKey prvKey = PKCS12Tools.ReadPrvKey(userP12, "private", "777777");

    Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
    sg.initSign(prvKey);
    sg.update(toSign.getEncoded("DER"));
    final byte[] sigVal = sg.sign();
    SES_Signature signature = new SES_Signature()
            .setToSign(toSign)
            .setCert(useCert)
            .setSignatureAlgID(GMObjectIdentifiers.sm2sign_with_sm3)
            .setSignature(sigVal);

    Path out = Paths.get("target/SignedValueV4.dat");
    Files.write(out, signature.getEncoded("DER"));
    System.out.println(">> V4版本电子签章存储于: " + out.toAbsolutePath().toAbsolutePath());
}
 
Example #21
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getDeclarationOfMajorityStringValue(byte[] octets) {

		// @formatter:off

		/*
			DeclarationOfMajoritySyntax ::= CHOICE
			{
				notYoungerThan [0] IMPLICIT INTEGER,
				fullAgeAtCountry [1] IMPLICIT SEQUENCE {
					fullAge BOOLEAN DEFAULT TRUE,
					country PrintableString (SIZE(2))
				},
				dateOfBirth [2] IMPLICIT GeneralizedTime
			}
		 */

		// @formatter:on

		StringBuilder sb = new StringBuilder();

		DeclarationOfMajority declarationOfMajority = DeclarationOfMajority.getInstance(octets);
		int notYoungerThan = declarationOfMajority.notYoungerThan();
		ASN1Sequence fullAgeAtCountry = declarationOfMajority.fullAgeAtCountry();
		ASN1GeneralizedTime dateOfBirth = declarationOfMajority.getDateOfBirth();

		if (notYoungerThan != -1) {
			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.notYoungerThan"), notYoungerThan));
			sb.append(NEWLINE);
		}

		if (fullAgeAtCountry != null) {
			ASN1Boolean fullAge = ASN1Boolean.getInstance(fullAgeAtCountry.getObjectAt(0));
			DERPrintableString country = DERPrintableString.getInstance(fullAgeAtCountry.getObjectAt(1));

			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.fullAgeAtCountry"), country.toString(),
					fullAge.toString()));
			sb.append(NEWLINE);
		}

		if (dateOfBirth != null) {
			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.dateOfBirth"), dateOfBirth));
			sb.append(NEWLINE);
		}

		return sb.toString();
	}
 
Example #22
Source File: ProfileConfCreatorDemo.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static List<ExtensionType> createConstantExtensions(
    ASN1ObjectIdentifier oidPrefix, Tag tag) throws IOException {
  List<ExtensionType> list = new LinkedList<>();

  // Custom Constant Extension Value
  list.add(createConstantExtension(oidPrefix.branch("1"), true, false, tag,
      FieldType.BIT_STRING, Base64.encodeToString(new byte[] {1, 2})));
  list.add(createConstantExtension(oidPrefix.branch("2"), true, false, tag,
      FieldType.BMPString, "A BMP string"));
  list.add(createConstantExtension(oidPrefix.branch("3"), true, false, tag,
      FieldType.BOOLEAN, Boolean.TRUE.toString()));
  list.add(createConstantExtension(oidPrefix.branch("4"), true, false, tag,
      FieldType.IA5String, "An IA5 string"));
  list.add(createConstantExtension(oidPrefix.branch("5"), true, false, tag,
      FieldType.INTEGER, "10"));
  list.add(createConstantExtension(oidPrefix.branch("6"), true, false, tag,
      FieldType.NULL, null));
  list.add(createConstantExtension(oidPrefix.branch("7"), true, false, tag,
      FieldType.OCTET_STRING, Base64.encodeToString(new byte[] {3, 4})));
  list.add(createConstantExtension(oidPrefix.branch("8"), true, false, tag,
      FieldType.OID, "2.3.4.5"));
  list.add(createConstantExtension(oidPrefix.branch("9"), true, false, tag,
      FieldType.PrintableString, "A printable string"));
  list.add(createConstantExtension(oidPrefix.branch("10"), true, false, tag,
      FieldType.RAW, Base64.encodeToString(DERNull.INSTANCE.getEncoded())));
  last(list).getConstant().setDescription("DER NULL");

  list.add(createConstantExtension(oidPrefix.branch("11"), true, false, tag,
      FieldType.TeletexString, "A teletax string"));
  list.add(createConstantExtension(oidPrefix.branch("12"), true, false, tag,
      FieldType.UTF8String, "A UTF8 string"));
  list.add(createConstantExtension(oidPrefix.branch("13"), true, false, tag,
      FieldType.ENUMERATED, "2"));
  list.add(createConstantExtension(oidPrefix.branch("14"), true, false, tag,
      FieldType.GeneralizedTime, new ASN1GeneralizedTime("20180314130102Z").getTimeString()));
  list.add(createConstantExtension(oidPrefix.branch("15"), true, false, tag,
      FieldType.UTCTime, "190314130102Z"));
  list.add(createConstantExtension(oidPrefix.branch("16"), true, false, tag,
      FieldType.Name, "CN=abc,C=DE"));

  list.add(createConstantExtension(oidPrefix.branch("17"), true, false, tag,
      FieldType.SEQUENCE, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("18"), true, false, tag,
      FieldType.SEQUENCE_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  list.add(createConstantExtension(oidPrefix.branch("19"), true, false, tag,
      FieldType.SET, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("20"), true, false, tag,
      FieldType.SET_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  return list;
}
 
Example #23
Source File: ExtensionsConfCreatorDemo.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static List<X509ExtensionType> createConstantExtensions(ASN1ObjectIdentifier oidPrefix,
    Tag tag) {
  List<X509ExtensionType> list = new LinkedList<>();

  // Custom Constant Extension Value
  list.add(createConstantExtension(oidPrefix.branch("1"), tag, FieldType.BIT_STRING,
      Base64.encodeToString(new byte[] {1, 2})));
  list.add(createConstantExtension(oidPrefix.branch("2"), tag, FieldType.BMPString,
      "A BMP string"));
  list.add(createConstantExtension(oidPrefix.branch("3"), tag, FieldType.BOOLEAN,
      Boolean.TRUE.toString()));
  list.add(createConstantExtension(oidPrefix.branch("4"), tag, FieldType.IA5String,
      "An IA5 string"));
  list.add(createConstantExtension(oidPrefix.branch("5"), tag, FieldType.INTEGER,
      "10"));
  list.add(createConstantExtension(oidPrefix.branch("6"), tag, FieldType.NULL,
      null));
  list.add(createConstantExtension(oidPrefix.branch("7"), tag, FieldType.OCTET_STRING,
      Base64.encodeToString(new byte[] {3, 4})));
  list.add(createConstantExtension(oidPrefix.branch("8"), tag, FieldType.OID,
      "2.3.4.5"));
  list.add(createConstantExtension(oidPrefix.branch("9"), tag, FieldType.PrintableString,
      "A printable string"));

  list.add(createConstantExtension(oidPrefix.branch("10"), tag, FieldType.NULL,
      null));

  list.add(createConstantExtension(oidPrefix.branch("11"), tag, FieldType.TeletexString,
      "A teletax string"));
  list.add(createConstantExtension(oidPrefix.branch("12"), tag, FieldType.UTF8String,
      "A UTF8 string"));
  list.add(createConstantExtension(oidPrefix.branch("13"), tag, FieldType.ENUMERATED,
      "2"));
  list.add(createConstantExtension(oidPrefix.branch("14"), tag, FieldType.GeneralizedTime,
      new ASN1GeneralizedTime("20180314130102Z").getTimeString()));
  list.add(createConstantExtension(oidPrefix.branch("15"), tag, FieldType.UTCTime,
      "190314130102Z"));
  list.add(createConstantExtension(oidPrefix.branch("16"), tag, FieldType.Name,
      "CN=abc,C=DE"));

  list.add(createConstantExtension(oidPrefix.branch("17"), tag, FieldType.SEQUENCE, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("18"), tag, FieldType.SEQUENCE_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  list.add(createConstantExtension(oidPrefix.branch("19"), tag, FieldType.SET, null));
  last(list).getConstant().setListValue(createConstantSequenceOrSet());

  list.add(createConstantExtension(oidPrefix.branch("20"), tag, FieldType.SET_OF, null));
  last(list).getConstant().setListValue(createConstantSequenceOfOrSetOf());

  return list;
}
 
Example #24
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getInvalidityDateStringValue(byte[] value) throws IOException {
	// @formatter:off

	/* InvalidityDate ::= ASN1GeneralizedTime */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	ASN1GeneralizedTime invalidityDate = ASN1GeneralizedTime.getInstance(value);

	sb.append(getGeneralizedTimeString(invalidityDate));
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #25
Source File: SubjectChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static String getAtvValueString(String name, AttributeTypeAndValue atv,
    StringType stringType, StringBuilder failureMsg) {
  ASN1ObjectIdentifier type = atv.getType();
  ASN1Encodable atvValue = atv.getValue();

  if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
    if (!(atvValue instanceof ASN1GeneralizedTime)) {
      failureMsg.append(name).append(" is not of type GeneralizedTime; ");
      return null;
    }
    return ((ASN1GeneralizedTime) atvValue).getTimeString();
  } else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
    if (!(atvValue instanceof ASN1Sequence)) {
      failureMsg.append(name).append(" is not of type Sequence; ");
      return null;
    }

    ASN1Sequence seq = (ASN1Sequence) atvValue;
    final int n = seq.size();

    StringBuilder sb = new StringBuilder();
    boolean validEncoding = true;
    for (int i = 0; i < n; i++) {
      ASN1Encodable obj = seq.getObjectAt(i);
      if (!matchStringType(obj, stringType)) {
        failureMsg.append(name).append(".[").append(i).append("] is not of type ")
          .append(stringType.name()).append("; ");
        validEncoding = false;
        break;
      }

      String textValue = X509Util.rdnValueToString(obj);
      sb.append("[").append(i).append("]=").append(textValue).append(",");
    }

    if (!validEncoding) {
      return null;
    }

    return sb.toString();
  } else {
    if (!matchStringType(atvValue, stringType)) {
      failureMsg.append(name).append(" is not of type " + stringType.name()).append("; ");
      return null;
    }

    return X509Util.rdnValueToString(atvValue);
  }
}
 
Example #26
Source File: CmpResponder.java    From xipki with Apache License 2.0 4 votes vote down vote up
private PKIBody cmpEnrollCert(String dfltCertprofileName, Boolean dfltCaGenKeypair,
    PKIMessage request, PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader,
    PKIBody reqBody, CmpRequestorInfo requestor, ASN1OctetString tid, String msgId,
    AuditEvent event) throws InsuffientPermissionException {
  long confirmWaitTime = cmpControl.getConfirmWaitTime();
  if (confirmWaitTime < 0) {
    confirmWaitTime *= -1;
  }
  confirmWaitTime *= 1000; // second to millisecond

  PKIBody respBody;

  int type = reqBody.getType();
  switch (type) {
    case PKIBody.TYPE_INIT_REQ:
      checkPermission(requestor, PermissionConstants.ENROLL_CERT);
      respBody = processIr(dfltCertprofileName, dfltCaGenKeypair, request, requestor, tid,
          reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
      break;
    case PKIBody.TYPE_CERT_REQ:
      checkPermission(requestor, PermissionConstants.ENROLL_CERT);
      respBody = processCr(dfltCertprofileName, dfltCaGenKeypair, request, requestor, tid,
          reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
      break;
    case PKIBody.TYPE_KEY_UPDATE_REQ:
      checkPermission(requestor, PermissionConstants.KEY_UPDATE);
      respBody = processKur(dfltCertprofileName, dfltCaGenKeypair, request, requestor, tid,
          reqHeader, CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
      break;
    case PKIBody.TYPE_P10_CERT_REQ:
      checkPermission(requestor, PermissionConstants.ENROLL_CERT);
      respBody = processP10cr(dfltCertprofileName, request, requestor, tid, reqHeader,
          CertificationRequest.getInstance(reqBody.getContent()), cmpControl, msgId, event);
      break;
    case PKIBody.TYPE_CROSS_CERT_REQ:
      checkPermission(requestor, PermissionConstants.ENROLL_CROSS);
      respBody = processCcp(dfltCertprofileName, request, requestor, tid, reqHeader,
          CertReqMessages.getInstance(reqBody.getContent()), cmpControl, msgId, event);
      break;
    default:
      throw new IllegalStateException("should not reach here");
  } // switch type

  InfoTypeAndValue tv = null;
  if (!cmpControl.isConfirmCert() && CmpUtil.isImplictConfirm(reqHeader)) {
    pendingCertPool.removeCertificates(tid.getOctets());
    tv = CmpUtil.getImplictConfirmGeneralInfo();
  } else {
    Date now = new Date();
    respHeader.setMessageTime(new ASN1GeneralizedTime(now));
    tv = new InfoTypeAndValue(CMPObjectIdentifiers.it_confirmWaitTime,
        new ASN1GeneralizedTime(new Date(System.currentTimeMillis() + confirmWaitTime)));
  }

  respHeader.setGeneralInfo(tv);
  return respBody;
}
 
Example #27
Source File: CmpAgent.java    From xipki with Apache License 2.0 4 votes vote down vote up
private PKIMessage buildRevokeCertRequest(RevokeCertRequest request)
    throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<RevokeCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (RevokeCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Date invalidityDate = requestEntry.getInvalidityDate();
    int idx = (invalidityDate == null) ? 1 : 2;
    Extension[] extensions = new Extension[idx];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
      extensions[0] = new Extension(Extension.reasonCode, true,
          new DEROctetString(reason.getEncoded()));

      if (invalidityDate != null) {
        ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
        extensions[1] = new Extension(Extension.invalidityDate, true,
                new DEROctetString(time.getEncoded()));
      }
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }

    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}
 
Example #28
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 3 votes vote down vote up
private String getDateOfCertGenStringValue(byte[] octets) {

		/*	DateOfCertGenSyntax ::= GeneralizedTime */

		ASN1GeneralizedTime dateOfCertGenSyntax = ASN1GeneralizedTime.getInstance(octets);
		return getGeneralizedTimeString(dateOfCertGenSyntax);
	}
 
Example #29
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Get Invalidity Date (2.5.29.24) extension value as a string.
 *
 * <pre>
 * InvalidityDate ::=  GeneralizedTime
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 * @throws ParseException If a date formatting problem occurs
 */
private String getInvalidityDateStringValue(byte[] bValue)
    throws IOException, ParseException
{
	// Get invalidity date
	ASN1GeneralizedTime invalidityDate = (ASN1GeneralizedTime) ASN1Primitive.fromByteArray(bValue);

	// Format invalidity date for display
	return formatGeneralizedTime(invalidityDate);
}