List of usage examples for org.bouncycastle.asn1.x509 X509Extensions getInstance
public static X509Extensions getInstance(Object obj)
From source file:chapter6.PKCS10CertCreateExample.java
public static X509Certificate[] buildChain() throws Exception { // Create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // Create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // Validate the certification request if (request.verify("BC") == false) { System.out.println("Request failed to verify!!"); System.exit(1);//from ww w. j a v a 2s. c o m } // Create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // Extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i < attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // Process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:com.novosec.pkix.asn1.cmp.RevAnnContent.java
License:Open Source License
public RevAnnContent(ASN1Sequence seq) { this.status = DERInteger.getInstance(seq.getObjectAt(0)); this.certId = CertId.getInstance(seq.getObjectAt(1)); this.willBeRevokedAt = DERGeneralizedTime.getInstance(seq.getObjectAt(2)); this.badSinceDate = DERGeneralizedTime.getInstance(seq.getObjectAt(3)); if (seq.size() > 4) { this.crlDetails = X509Extensions.getInstance(seq.getObjectAt(4)); }/*from w ww. j a v a2 s . c o m*/ }
From source file:com.novosec.pkix.asn1.cmp.RevDetails.java
License:Open Source License
public RevDetails(ASN1Sequence seq) { this.certDetails = CertTemplate.getInstance(seq.getObjectAt(0)); int idx = 1;/*from w ww . j a v a 2 s . co m*/ Object obj = null; if (idx < seq.size()) { obj = seq.getObjectAt(idx++); } if (obj instanceof DERBitString) { this.revocationReason = DERBitString.getInstance(obj); if (idx < seq.size()) { obj = seq.getObjectAt(idx++); } else { obj = null; } } if (obj instanceof DERGeneralizedTime) { this.badSinceDate = DERGeneralizedTime.getInstance(obj); if (idx < seq.size()) { obj = seq.getObjectAt(idx++); } else { obj = null; } } if (obj instanceof ASN1Sequence) { this.crlEntryDetails = X509Extensions.getInstance(obj); if (idx < seq.size()) { obj = seq.getObjectAt(idx++); } else { obj = null; } } if (obj != null) { throw new IllegalArgumentException("unknown object in factory"); } }
From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java
License:Apache License
/** * Test behavior when CPS is set.//from w w w . j a v a 2 s . co m * * @throws IOException */ @Test @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION") public void testCpsPolicy() throws IOException { SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(CPS_URI, null, null, null); // get policy extensions byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER); assertNotNull(policyBytes); X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); CertificatePolicies policies = CertificatePolicies.getInstance(asn1); assertNotNull(policies, "unable to find CertificatePolicies extension"); for (PolicyInformation info : policies.getPolicyInformation()) { if (id_qt_cps.equals(info.getPolicyIdentifier())) { DLSequence dls = (DLSequence) info.getPolicyQualifiers(); for (int i = 0; i < dls.size(); i++) { DLSequence dls1 = (DLSequence) dls.getObjectAt(i); PolicyQualifierInfo pqInfo = new PolicyQualifierInfo((ASN1ObjectIdentifier) dls1.getObjectAt(0), dls1.getObjectAt(1)); // DLSequence dls1 = (DLSequence) dls.getObjectAt(i); if (id_qt_cps.equals(pqInfo.getPolicyQualifierId())) { assertEquals(pqInfo.getQualifier().toString(), CPS_URI); } else { fail("unknown policy qualifier id: " + pqInfo.getPolicyQualifierId()); } } } else { fail("unknown policy identifier: " + info.getPolicyIdentifier()); } } }
From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java
License:Apache License
/** * Test behavior when user notice is set. * //from ww w . ja v a 2 s . com * @throws IOException */ @Test @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION") public void testUserNoticePolicy() throws IOException { SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(null, ORGANIZATION, USER_NOTICE, Integer.valueOf(1)); // get policy extensions byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER); assertNotNull(policyBytes); X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); CertificatePolicies policies = CertificatePolicies.getInstance(asn1); assertNotNull(policies, "unable to find CertificatePolicies extension"); for (PolicyInformation info : policies.getPolicyInformation()) { if (id_qt_unotice.equals(info.getPolicyIdentifier())) { DLSequence dls = (DLSequence) info.getPolicyQualifiers(); for (int i = 0; i < dls.size(); i++) { UserNotice userNotice = UserNotice.getInstance((DLSequence) dls.getObjectAt(i)); assertEquals(userNotice.getNoticeRef().getOrganization().getString(), ORGANIZATION); assertEquals(userNotice.getNoticeRef().getNoticeNumbers()[0].getValue(), BigInteger.ONE); assertEquals(userNotice.getExplicitText().getString(), USER_NOTICE); } } else { fail("unknown policy identifier: " + info.getPolicyIdentifier()); } } }
From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java
License:Apache License
/** * @see com.otterca.repository.util.X509CertificateBuilder#build(java.security * .PrivateKey)/*from w w w . j av a 2s . c o m*/ */ @Override public X509Certificate build(PrivateKey pkey) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateEncodingException, CertificateParsingException, KeyStoreException { // validate everything going into the certificate. Standard validations // are quick, issuer validations may require significant resources. validator.validate(); generator = new X509V3CertificateGenerator(); // set the mandatory properties generator.setSerialNumber(serialNumber); generator.setIssuerDN((issuer == null) ? issuerDN : new X509Principal(issuer.getIssuerDN().getName())); generator.setSubjectDN(subjectDN); generator.setNotBefore(notBefore); generator.setNotAfter(notAfter); generator.setPublicKey(pubkey); generator.setSignatureAlgorithm(SIGNATURE_ALGORITHM); // can this certificate be used to sign more certificates? // make sure pathLengthConstraint is always lower than issuer's. setBasicConstraint(); setSKID(); setAKID(); setSubjectAlternativeName(); setIssuerAlternativeName(); setExtendedKeyUsage(); setInhibitAnyPolicy(); setPrivateKeyUsagePeriod(); setNameConstraints(); setAuthorityInfoAccess(); setSubjectInfoAccess(); // set/clear key usage flag. if (keyUsage != null) { if (basicConstraint) { keyUsage = new KeyUsage(keyUsage.intValue() | KeyUsage.keyCertSign); } else { keyUsage = new KeyUsage(keyUsage.intValue() & (Integer.MAX_VALUE ^ KeyUsage.keyCertSign)); } } else if (basicConstraint) { keyUsage = new KeyUsage(KeyUsage.keyCertSign); } // add mandatory key usage constraints. if (keyUsage != null) { generator.addExtension(X509Extensions.KeyUsage, true, keyUsage); } // establish any extensions. for (X509ExtensionGenerator extGenerator : extensionGenerators) { try { byte[] extensionBytes = extGenerator.getExtension(new X500Principal(subjectDN.getEncoded()), issuer); if (extensionBytes != null) { X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(extensionBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); DERObjectIdentifier objectIdentifier = new DERObjectIdentifier( extGenerator.getObjectIdentifier()); generator.addExtension(objectIdentifier, extGenerator.isCritical(), asn1); } } catch (IOException e) { log.info("X509Extension extraction threw IOException! " + e.getMessage()); // throw an exception if this is an error in a critical // extension. Otherwise // will continue to build the certificate and count on the // caller's verification // process. if (extGenerator.isCritical()) { X509CertificateBuilderException ex = new X509CertificateBuilderException(); ex.addError(ErrorType.OTHER_ERROR, e.getMessage()); throw ex; } } } X509Certificate cert = generator.generate(pkey); return cert; }
From source file:edu.washington.iam.tools.IamCertificateHelper.java
License:Apache License
public static int parseCsr(IamCertificate cert) throws IamCertificateException { try {//from ww w . j a v a 2 s . co m PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest)); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); if (request == null) throw new IamCertificateException("invalid CSR (request)"); CertificationRequestInfo info = request.getCertificationRequestInfo(); if (info == null) throw new IamCertificateException("invalid CSR (info)"); X509Name dn = info.getSubject(); if (dn == null) throw new IamCertificateException("invalid CSR (dn)"); log.debug("dn=" + dn.toString()); cert.dn = dn.toString(); try { List cns = dn.getValues(X509Name.CN); cert.cn = (String) (cns.get(0)); log.debug("cn=" + cert.cn); cert.names.add(cert.cn); // first entry for names is always cn cns = dn.getValues(X509Name.C); cert.dnC = (String) (cns.get(0)); cns = dn.getValues(X509Name.ST); cert.dnST = (String) (cns.get(0)); } catch (Exception e) { log.debug("get cn error: " + e); throw new IamCertificateException("invalid CSR"); } // see if we've got alt names (in extensions) ASN1Set attrs = info.getAttributes(); if (attrs != null) { for (int a = 0; a < attrs.size(); a++) { Attribute attr = Attribute.getInstance(attrs.getObjectAt(a)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // is the extension X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); // get the subAltName extension DERObjectIdentifier sanoid = new DERObjectIdentifier( X509Extensions.SubjectAlternativeName.getId()); X509Extension xext = extensions.getExtension(sanoid); if (xext != null) { log.debug("processing altname extensions"); ASN1Object asn1 = X509Extension.convertValueToObject(xext); Enumeration dit = DERSequence.getInstance(asn1).getObjects(); while (dit.hasMoreElements()) { GeneralName gn = GeneralName.getInstance(dit.nextElement()); log.debug("altname tag=" + gn.getTagNo()); log.debug("altname name=" + gn.getName().toString()); if (gn.getTagNo() == GeneralName.dNSName) cert.names.add(gn.getName().toString()); } } } } } // check key size PublicKey pk = request.getPublicKey(); log.debug("key alg = " + pk.getAlgorithm()); log.debug("key fmt = " + pk.getFormat()); if (pk.getAlgorithm().equals("RSA")) { RSAPublicKey rpk = (RSAPublicKey) pk; cert.keySize = rpk.getModulus().bitLength(); log.debug("key size = " + cert.keySize); } } catch (IOException e) { log.debug("ioerror: " + e); throw new IamCertificateException("invalid CSR " + e.getMessage()); } catch (Exception e) { log.debug("excp: " + e); throw new IamCertificateException("invalid CSR"); } return 1; }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);//from www. ja va2s .co m } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java
License:Open Source License
/** * Returns the challenge password from the certificattion request. * * @return challenge password from certification request or null if none exist in the request. *//*from w w w . j a v a 2 s. c o m*/ public String getPassword() { if (password != null) { return password; } try { if (pkcs10 == null) { init(); } } catch (IllegalArgumentException e) { log.error("PKCS10 not inited!"); return null; } String ret = null; // Get attributes // The password attribute can be either a pkcs_9_at_challengePassword directly // or // a pkcs_9_at_extensionRequest containing a pkcs_9_at_challengePassword as a // X509Extension. AttributeTable attributes = null; CertificationRequestInfo info = pkcs10.getCertificationRequestInfo(); if (info != null) { ASN1Set attrs = info.getAttributes(); if (attrs != null) { attributes = new AttributeTable(attrs); } } if (attributes == null) { return null; } Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); DEREncodable obj = null; if (attr == null) { // See if we have it embedded in an extension request instead attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attr == null) { return null; } if (log.isDebugEnabled()) { log.debug("got extension request"); } ASN1Set values = attr.getAttrValues(); if (values.size() == 0) { return null; } X509Extensions exts = X509Extensions.getInstance(values.getObjectAt(0)); X509Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); if (ext == null) { if (log.isDebugEnabled()) { log.debug("no challenge password extension"); } return null; } obj = ext.getValue(); } else { // If it is a challengePassword directly, it's just to grab the value ASN1Set values = attr.getAttrValues(); obj = values.getObjectAt(0); } if (obj != null) { DERString str = null; try { str = DERPrintableString.getInstance((obj)); } catch (IllegalArgumentException ie) { // This was not printable string, should be utf8string then according to pkcs#9 v2.0 str = DERUTF8String.getInstance((obj)); } if (str != null) { ret = str.getString(); } } return ret; }
From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java
License:Open Source License
/** * @see org.ejbca.core.protocol.IRequestMessage *//*from w ww . j a v a2 s .c om*/ public X509Extensions getRequestExtensions() { try { if (pkcs10 == null) { init(); } } catch (IllegalArgumentException e) { log.error("PKCS10 not inited!"); return null; } X509Extensions ret = null; // Get attributes // The X509 extension is in a a pkcs_9_at_extensionRequest AttributeTable attributes = null; CertificationRequestInfo info = pkcs10.getCertificationRequestInfo(); if (info != null) { ASN1Set attrs = info.getAttributes(); if (attrs != null) { attributes = new AttributeTable(attrs); } } if (attributes != null) { // See if we have it embedded in an extension request instead Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attr != null) { if (log.isDebugEnabled()) { log.debug("got request extension"); } ASN1Set values = attr.getAttrValues(); if (values.size() > 0) { try { ret = X509Extensions.getInstance(values.getObjectAt(0)); } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug( "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request."); } } } } } return ret; }