org.bouncycastle.asn1.x509.Time Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.Time. 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: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addSigningTimeAttribute(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/*
	 * In PAdES, we don't include the signing time : ETSI TS 102 778-3 V1.2.1
	 * (2010-07): 4.5.3 signing-time Attribute
	 */
	if (padesUsage) {
		return;
	}

	final Date signingDate = parameters.bLevel().getSigningDate();
	if (signingDate != null) {
		final DERSet attrValues = new DERSet(new Time(signingDate));
		final Attribute attribute = new Attribute(pkcs_9_at_signingTime, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #2
Source File: ScepUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static Date getTime(Object obj) {
  if (obj instanceof byte[]) {
    byte[] encoded = (byte[]) obj;
    int tag = encoded[0] & 0xFF;;
    try {
      if (tag == BERTags.UTC_TIME) {
        return DERUTCTime.getInstance(encoded).getDate();
      } else if (tag == BERTags.GENERALIZED_TIME) {
        return DERGeneralizedTime.getInstance(encoded).getDate();
      } else {
        throw new IllegalArgumentException("invalid tag " + tag);
      }
    } catch (ParseException ex) {
      throw new IllegalArgumentException("error parsing time", ex);
    }
  } else if (obj instanceof Time) {
    return ((Time) obj).getDate();
  } else if (obj instanceof org.bouncycastle.asn1.cms.Time) {
    return ((org.bouncycastle.asn1.cms.Time) obj).getDate();
  } else {
    return Time.getInstance(obj).getDate();
  }
}
 
Example #3
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 #4
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Date getDate(ASN1Encodable encodable) {
	try {
		return Time.getInstance(encodable).getDate();
	} catch (Exception e) {
		LOG.warn("Unable to retrieve the date {}", encodable, e);
		return null;
	}
}
 
Example #5
Source File: BaseSyncopeWASAML2ClientTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #6
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #7
Source File: LocalRepoKeyStore.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname)
        throws CertificateException, OperatorCreationException, IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);

    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(pubKey.getEncoded()));

    Date now = new Date(); // now

    /* force it to use a English/Gregorian dates for the cert, hardly anyone
       ever looks at the cert metadata anyway, and its very likely that they
       understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(now);
    c.add(Calendar.YEAR, 1);
    Time startTime = new Time(now, Locale.ENGLISH);
    Time endTime = new Time(c.getTime(), Locale.ENGLISH);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            subject,
            BigInteger.valueOf(rand.nextLong()),
            startTime,
            endTime,
            subject,
            subPubKeyInfo);

    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(
                new GeneralName(GeneralName.iPAddress, hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example #8
Source File: Asn1StreamParser.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static Date readTime(ASN1Encodable  obj) {
  if (obj instanceof Time) {
    return ((Time) obj).getDate();
  } else if (obj instanceof org.bouncycastle.asn1.cms.Time) {
    return ((org.bouncycastle.asn1.cms.Time) obj).getDate();
  } else {
    return Time.getInstance(obj).getDate();
  }
}
 
Example #9
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 #10
Source File: CRLParser.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Time rebuildASN1Time(int tagNo, byte[] array) throws IOException {
	// Tag UTC or GeneralizedTime
	return Time.getInstance(rebuildASN1Primitive(tagNo, array));
}
 
Example #11
Source File: Actions.java    From xipki with Apache License 2.0 4 votes vote down vote up
protected EnrollCertResult enroll() throws Exception {
  Set<String> caNames = client.getCaNames();
  if (caName != null) {
    caName = caName.toLowerCase();
    if (!caNames.contains(caName)) {
      throw new IllegalCmdParamException("unknown CA " + caName);
    }
  } else {
    if (caNames.size() != 1) {
      throw new IllegalCmdParamException("please specify the CA");
    } else {
      caName = caNames.iterator().next();
    }
  }

  if (needExtensionTypes != null) {
    needExtensionTypes = EnrollAction.resolveExtensionTypes(needExtensionTypes);
  } else {
    needExtensionTypes = new LinkedList<>();
  }

  if (wantExtensionTypes != null) {
    wantExtensionTypes = EnrollAction.resolveExtensionTypes(wantExtensionTypes);
  } else {
    wantExtensionTypes = new LinkedList<>();
  }

  CertTemplateBuilder certTemplateBuilder = new CertTemplateBuilder();

  if (subject != null && !subject.isEmpty()) {
    certTemplateBuilder.setSubject(new X500Name(subject));
  }

  SubjectPublicKeyInfo publicKey = getPublicKey();
  if (publicKey != null) {
    certTemplateBuilder.setPublicKey(getPublicKey());
  }

  if (StringUtil.isNotBlank(notBeforeS) || StringUtil.isNotBlank(notAfterS)) {
    Time notBefore = StringUtil.isNotBlank(notBeforeS)
        ? new Time(DateUtil.parseUtcTimeyyyyMMddhhmmss(notBeforeS)) : null;
    Time notAfter = StringUtil.isNotBlank(notAfterS)
        ? new Time(DateUtil.parseUtcTimeyyyyMMddhhmmss(notAfterS)) : null;
    OptionalValidity validity = new OptionalValidity(notBefore, notAfter);
    certTemplateBuilder.setValidity(validity);
  }

  List<Extension> extensions = new LinkedList<>();

  if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
    ExtensionExistence ee = new ExtensionExistence(
        EnrollAction.textToAsn1ObjectIdentifers(needExtensionTypes),
        EnrollAction.textToAsn1ObjectIdentifers(wantExtensionTypes));
    extensions.add(new Extension(ObjectIdentifiers.Xipki.id_xipki_ext_cmpRequestExtensions,
                      false, ee.toASN1Primitive().getEncoded()));
  }

  if (isNotEmpty(extensions)) {
    Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
    certTemplateBuilder.setExtensions(asn1Extensions);
  }

  if (!(oldCertFile == null ^ oldCSerialNumber == null)) {
    throw new IllegalCmdParamException(
        "exactly one of oldcert and oldcert-serial must be specified");
  }

  CertId oldCertId;
  if (oldCertFile != null) {
    X509Cert oldCert = X509Util.parseCert(new File(oldCertFile));
    oldCertId = new CertId(new GeneralName(oldCert.getIssuer()), oldCert.getSerialNumber());
  } else {
    X500Name issuer = client.getCaCertSubject(caName);
    oldCertId = new CertId(new GeneralName(issuer), toBigInt(oldCSerialNumber));
  }

  Controls controls = new Controls(
      new AttributeTypeAndValue(CMPObjectIdentifiers.regCtrl_oldCertID, oldCertId));

  CertRequest certReq = new CertRequest(1, certTemplateBuilder.build(), controls);

  EnrollCertRequest.Entry reqEntry = buildEnrollCertRequestEntry("id-1", null, certReq);
  EnrollCertRequest request = new EnrollCertRequest(EnrollCertRequest.EnrollType.KEY_UPDATE);
  request.addRequestEntry(reqEntry);

  ReqRespDebug debug = getReqRespDebug();
  EnrollCertResult result;
  try {
    result = client.enrollCerts(caName, request, debug);
  } finally {
    saveRequestResponse(debug);
  }

  return result;
}