List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest
ASN1ObjectIdentifier pkcs_9_at_extensionRequest
To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest.
Click Source Link
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);/*ww w. ja va 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:chapter6.PKCS10ExtensionExample.java
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { // Create a SubjectAlternativeName extension value GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")); // Create the extensions object and add it as an attribute Vector oids = new Vector(); Vector values = new Vector(); oids.add(X509Extensions.SubjectAlternativeName); values.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(oids, values); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), new DERSet(attribute), pair.getPrivate()); }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static String extractX509CSREmail(PKCS10CertificationRequest certReq) { String rfc822 = null;/*from w ww .j a v a 2 s. c o m*/ Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); for (Attribute attribute : attributes) { for (ASN1Encodable value : attribute.getAttributeValues()) { Extensions extensions = Extensions.getInstance(value); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); for (GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.rfc822Name) { rfc822 = (((DERIA5String) name.getName()).getString()); break; } } } } return rfc822; }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static List<String> extractX509CSRDnsNames(PKCS10CertificationRequest certReq) { List<String> dnsNames = new ArrayList<>(); Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); for (Attribute attribute : attributes) { for (ASN1Encodable value : attribute.getAttributeValues()) { Extensions extensions = Extensions.getInstance(value); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); for (GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.dNSName) { dnsNames.add(((DERIA5String) name.getName()).getString()); }/*from w ww . j av a 2s.c o m*/ } } } return dnsNames; }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) { List<String> ipAddresses = new ArrayList<>(); Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); for (Attribute attribute : attributes) { for (ASN1Encodable value : attribute.getAttributeValues()) { Extensions extensions = Extensions.getInstance(value); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); for (GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.iPAddress) { try { InetAddress addr = InetAddress .getByAddress(((DEROctetString) name.getName()).getOctets()); ipAddresses.add(addr.getHostAddress()); } catch (UnknownHostException e) { }/*from w ww. j av a 2s . c om*/ } } } } return ipAddresses; }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey, String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException { // Create Distinguished Name X500Principal subject = new X500Principal(x500Principal); // Create ContentSigner JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256); ContentSigner signer = csBuilder.build(privateKey); // Create the CSR PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey); // Add SubjectAlternativeNames (SAN) if specified if (sanArray != null) { ExtensionsGenerator extGen = new ExtensionsGenerator(); GeneralNames subjectAltNames = new GeneralNames(sanArray); extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); }/*www . j av a 2s . co m*/ PKCS10CertificationRequest csr = p10Builder.build(signer); // write to openssl PEM format PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded()); StringWriter strWriter; try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) { pemWriter.writeObject(pemObject); } return strWriter.toString(); }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) { // set validity for the given number of minutes from now Date notBefore = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(notBefore);//from w ww.ja v a2s. com cal.add(Calendar.MINUTE, validityTimeout); Date notAfter = cal.getTime(); // Generate self-signed certificate X509Certificate cert = null; try { JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest( certReq); PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey(); X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey) .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)) .addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // see if we have the dns/rfc822/ip address extensions specified in the csr ArrayList<GeneralName> altNames = new ArrayList<>(); Attribute[] certAttributes = jcaPKCS10CertificationRequest .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (certAttributes != null && certAttributes.length > 0) { for (Attribute attribute : certAttributes) { Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); if (gns == null) { continue; } GeneralName[] names = gns.getNames(); for (int i = 0; i < names.length; i++) { switch (names[i].getTagNo()) { case GeneralName.dNSName: case GeneralName.iPAddress: case GeneralName.rfc822Name: altNames.add(names[i]); break; } } } if (!altNames.isEmpty()) { caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]))); } } String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256); ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER) .build(caPrivateKey); JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER); cert = converter.getCertificate(caBuilder.build(caSigner)); } catch (CertificateException ex) { LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage()); throw new CryptoException(ex); } catch (OperatorCreationException ex) { LOG.error( "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage()); throw new CryptoException(ex); } catch (InvalidKeyException ex) { LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage()); throw new CryptoException(ex); } catch (NoSuchAlgorithmException ex) { LOG.error( "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage()); throw new CryptoException(ex); } catch (Exception ex) { LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage()); throw new CryptoException("Unable to generate X509 Certificate"); } return cert; }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastlePKCS10Object.java
License:Open Source License
@Override public Set<String> getExtensionOIDs() throws IOException { HashSet<String> oids = new HashSet<>(); Attribute[] attributes = this.pkcs10Object.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attributes != null) { for (Attribute attribute : attributes) { ASN1Encodable[] values = attribute.getAttributeValues(); if (values != null) { for (ASN1Encodable value : values) { ASN1Decoder decoder = new BouncyCastleASN1Decoder(value.toASN1Primitive()); ASN1Decoder[] entries = decoder.asn1DecodeSequence(-1, -1); for (ASN1Decoder entry : entries) { ASN1Decoder[] extensionEntries = entry.asn1DecodeSequence(2, 3); String extensionOID = extensionEntries[0].asn1DecodeOID(); oids.add(extensionOID); }/* ww w .j a v a 2s. c o m*/ } } } } return oids; }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastlePKCS10Object.java
License:Open Source License
@Override public byte[] getExtensionValue(String oid) throws IOException { byte[] extensionValue = null; Attribute[] attributes = this.pkcs10Object.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attributes != null) { for (Attribute attribute : attributes) { if (extensionValue != null) { break; }/*from ww w. jav a2s . c o m*/ ASN1Encodable[] values = attribute.getAttributeValues(); if (values != null) { for (ASN1Encodable value : values) { if (extensionValue != null) { break; } ASN1Decoder decoder = new BouncyCastleASN1Decoder(value.toASN1Primitive()); ASN1Decoder[] entries = decoder.asn1DecodeSequence(-1, -1); for (ASN1Decoder entry : entries) { ASN1Decoder[] extensionEntries = entry.asn1DecodeSequence(2, 3); String extensionOID = extensionEntries[0].asn1DecodeOID(); if (oid.equals(extensionOID)) { extensionValue = extensionEntries[extensionEntries.length - 1].getEncoded(); break; } } } } } } return extensionValue; }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java
License:Open Source License
private void addCustomExtensions(PKCS10CertificationRequestBuilder csrBuilder, X509CertificateParams certificateParams) throws IOException { ExtensionsGenerator extensionGenerator = new ExtensionsGenerator(); for (X509Extension extension : certificateParams.getExtensions()) { ASN1ObjectIdentifier extensionOID = new ASN1ObjectIdentifier(extension.getOID()); extensionGenerator.addExtension(extensionOID, extension.isCritical(), new BouncyCastleASN1Encoder(extension)); }//from w w w .j av a2 s . c o m csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionGenerator.generate()); }