List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName
public GeneralName(int tag, String name)
From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java
License:Apache License
public void setIssuer(String issuerDN) throws Exception { try {/* w w w . jav a2 s . c o m*/ DERSequence issuer_name_sequence = DNtoDERSequence(issuerDN); V2Form v2form = new V2Form(new GeneralNames(new GeneralName(4, issuer_name_sequence))); this.issuer = new AttCertIssuer(v2form); } catch (Exception e) { throw e; } }
From source file:org.apache.cloudstack.utils.security.CertUtils.java
License:Apache License
public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair, final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm, final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException { final DateTime now = DateTime.now(DateTimeZone.UTC); final BigInteger serial = generateRandomBigInt(); final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); final X509v3CertificateBuilder certBuilder; if (caCert == null) { // Generate CA certificate certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject), clientPublicKey);//w w w .j a va2 s . co m certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); } else { // Generate client certificate certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)); } certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(clientPublicKey)); final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>(); if (publicIPAddresses != null) { for (final String publicIPAddress : publicIPAddresses) { if (Strings.isNullOrEmpty(publicIPAddress)) { continue; } subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress)); } } if (dnsNames != null) { for (final String dnsName : dnsNames) { if (Strings.isNullOrEmpty(dnsName)) { continue; } subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName)); } } if (subjectAlternativeNames.size() > 0) { final GeneralNames subjectAltNames = GeneralNames .getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {}))); certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC") .build(caKeyPair.getPrivate()); final X509CertificateHolder certHolder = certBuilder.build(signer); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); if (caCert != null) { cert.verify(caCert.getPublicKey()); } else { cert.verify(caKeyPair.getPublic()); } return cert; }
From source file:org.apache.kerby.pkix.EndEntityGenerator.java
License:Apache License
/** * Generate certificate./* www . j a v a 2 s . com*/ * * @param issuerCert * @param issuerPrivateKey * @param publicKey * @param dn * @param validityDays * @param friendlyName * @return The certificate. * @throws InvalidKeyException * @throws SecurityException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws DataLengthException * @throws CertificateException */ public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey, PublicKey publicKey, String dn, int validityDays, String friendlyName) throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CertificateException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Set certificate attributes. certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert)); certGen.setSubjectDN(new X509Principal(dn)); certGen.setNotBefore(new Date()); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); certGen.setNotAfter(expiry.getTime()); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); // MAY set BasicConstraints=false or not at all. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector(); keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon); //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth ); DERSequence keyPurposeOids = new DERSequence(keyPurposeVector); // If critical, will throw unsupported EKU. certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids); ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector(); pkinitSanVector.add(ID_PKINIT_SAN); pkinitSanVector.add(new DERTaggedObject(0, new DERSequence())); DERSequence pkinitSan = new DERSequence(pkinitSanVector); String dnsName = "localhost"; GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan); GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName); GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder(); genNamesBuilder.addName(name1); genNamesBuilder.addName(name2); GeneralNames sanGeneralNames = genNamesBuilder.build(); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames); /* * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's * X.509 certificate. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the client's X.509 certificate is restricted with * the id-pkinit-KPClientAuth EKU. */ /* * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as * there are a large number of X.509 client certificates deployed for use * with PKINIT that have this EKU. */ // KDC /* * In addition, unless the client can otherwise verify that the public key * used to verify the KDC's signature is bound to the KDC of the target realm, * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]). */ /* * Unless the client knows by some other means that the KDC certificate is * intended for a Kerberos KDC, the client MUST require that the KDC certificate * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the KDC's X.509 certificate is restricted with the * id-pkinit-KPKdc EKU. */ /* * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san * SAN, this certificate is certified by the issuing CA as a KDC certificate, * therefore the id-pkinit-KPKdc EKU is not required. */ /* * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth * EKU [RFC3280]. */ /* * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth * EKU, and the id-ms-kp-sc-logon EKU. */ /* * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC. * * MS: dNSName SAN containing the domain name of the KDC * id-pkinit-KPKdc EKU * id-kp-serverAuth EKU. */ /* * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and * the id-ms-kp-sc-logon EKU. The id-ms-san-sc-logon-upn SAN contains a * UTF8-encoded string whose value is that of the Directory Service attribute * UserPrincipalName of the client account object, and the purpose of including * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate * the client mapping (in other words, the client's public key is bound to * the account that has this UserPrincipalName value). */ X509Certificate cert = certGen.generate(issuerPrivateKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); return cert; }
From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java
License:Apache License
public static Extensions createDomainAlternativeNamesExtensions(String domainAlternativeNames, String requestedDn) throws IOException { List<GeneralName> namesList = new ArrayList<>(); try {/*from w w w . ja v a 2 s.com*/ final String cn = IETFUtils .valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue()); namesList.add(new GeneralName(GeneralName.dNSName, cn)); } catch (Exception e) { throw new IOException("Failed to extract CN from request DN: " + requestedDn, e); } if (StringUtils.isNotBlank(domainAlternativeNames)) { for (String alternativeName : domainAlternativeNames.split(",")) { namesList.add(new GeneralName(GeneralName.dNSName, alternativeName)); } } GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[] {})); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); return extGen.generate(); }
From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java
License:Apache License
static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException { String signatureAlgorithm = "SHA1withRSA"; X500Name issuerName;//w w w . j a v a 2s . c o m if (issuerCertificate != null) { issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer(); } else { issuerName = new X500Name(subjectDn); } RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey; RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec); DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build() .get(CertificateID.HASH_SHA1); X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo); X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc); SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo); AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo); certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId); certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId); if (caFlag) { BasicConstraints bc; if (-1 == pathLength) { bc = new BasicConstraints(true); } else { bc = new BasicConstraints(pathLength); } certificateGenerator.addExtension(Extension.basicConstraints, false, bc); } if (null != crlUri) { int uri = GeneralName.uniformResourceIdentifier; DERIA5String crlUriDer = new DERIA5String(crlUri); GeneralName gn = new GeneralName(uri, crlUriDer); DERSequence gnDer = new DERSequence(gn); GeneralNames gns = GeneralNames.getInstance(gnDer); DistributionPointName dpn = new DistributionPointName(0, gns); DistributionPoint distp = new DistributionPoint(dpn, null, null); DERSequence distpDer = new DERSequence(distp); certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer); } if (null != ocspUri) { int uri = GeneralName.uniformResourceIdentifier; GeneralName ocspName = new GeneralName(uri, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } if (null != keyUsage) { certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage); } JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); signerBuilder.setProvider("BC"); X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey)); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ // CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // certificate = (X509Certificate) certificateFactory // .generateCertificate(new ByteArrayInputStream(certificate // .getEncoded())); return new JcaX509CertificateConverter().getCertificate(certHolder); }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * Returns subject alternative names for "localhost". * @return the subject alternative names for "localhost". *//*from ww w . java 2s . c om*/ private static GeneralNames getLocalhostSubjectAltNames() throws UnknownHostException { InetAddress[] localAddresses = InetAddress.getAllByName("localhost"); GeneralName[] generalNames = new GeneralName[localAddresses.length + 1]; for (int i = 0; i < localAddresses.length; i++) { generalNames[i] = new GeneralName(GeneralName.iPAddress, new DEROctetString(localAddresses[i].getAddress())); } generalNames[generalNames.length - 1] = new GeneralName(GeneralName.dNSName, new DERIA5String("localhost")); return new GeneralNames(generalNames); }
From source file:org.apache.zookeeper.common.ZKTrustManagerTest.java
License:Apache License
private X509Certificate[] createSelfSignedCertifcateChain(String ipAddress, String hostname) throws Exception { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, "NOT_LOCALHOST"); Date notBefore = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(notBefore);//from w ww .ja v a 2 s . c o m cal.add(Calendar.YEAR, 1); Date notAfter = cal.getTime(); BigInteger serialNumber = new BigInteger(128, new Random()); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); List<GeneralName> generalNames = new ArrayList<>(); if (ipAddress != null) { generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress)); } if (hostname != null) { generalNames.add(new GeneralName(GeneralName.dNSName, hostname)); } if (!generalNames.isEmpty()) { certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); } ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); return new X509Certificate[] { new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner)) }; }
From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java
License:Apache License
public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception { X509CertificateHolder holder = new JcaX509CertificateHolder(caCert); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey); List<GeneralName> generalNames = new ArrayList<>(); if (hostname != null) { generalNames.add(new GeneralName(GeneralName.dNSName, hostname)); }/*w w w . j av a 2 s. c om*/ if (ipAddress != null) { generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress)); } SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded())); X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils(); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic()) .addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); if (!generalNames.isEmpty()) { certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); } if (crlPath != null) { DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath))); certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) })); } if (ocspPort != null) { certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort))); } return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer)); }
From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java
License:Open Source License
@Override public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Certificate caCert = reader.getCACert(); // set cert fields certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(startDate);/*from w w w .j av a2 s. co m*/ certGen.setNotAfter(endDate); X500Principal subjectPrincipal = new X500Principal(dn); certGen.setSubjectDN(subjectPrincipal); certGen.setPublicKey(clientKeyPair.getPublic()); certGen.setSignatureAlgorithm(SIGNATURE_ALGO); // set key usage - required for proper x509 function KeyUsage keyUsage = new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment); // add SSL extensions - required for proper x509 function NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime); certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType); certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); // Add an alternate name if provided if (alternateName != null) { GeneralName name = new GeneralName(GeneralName.uniformResourceIdentifier, "CN=" + alternateName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(name)); } if (extensions != null) { for (X509ExtensionWrapper wrapper : extensions) { // Bouncycastle hates null values. So, set them to blank // if they are null String value = wrapper.getValue() == null ? "" : wrapper.getValue(); certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value)); } } if (byteExtensions != null) { for (X509ByteExtensionWrapper wrapper : byteExtensions) { // Bouncycastle hates null values. So, set them to blank // if they are null byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue(); certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value)); } } // Generate the certificate return certGen.generate(reader.getCaKey()); }
From source file:org.candlepin.resource.test.cert.test.CertTest.java
License:Open Source License
@Test public void testCertExample() throws Exception { Security.addProvider(new BouncyCastleProvider()); ////from ww w.j av a2s . co m // set up the keys // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); PublicKey caPubKey = fact.generatePublic(caPubKeySpec); //PrivateKey privKey = fact.generatePrivate(privKeySpec); PublicKey pubKey = fact.generatePublic(pubKeySpec); // // note in this case we are using the CA certificate for both the client // cetificate // and the attribute certificate. This is to make the vcode simpler to // read, in practice // the CA for the attribute certificate should be different to that of // the client certificate // X509Certificate caCert = AttrCertExample.createAcIssuerCert(caPubKey, caPrivKey); X509Certificate clientCert = AttrCertExample.createClientCert(pubKey, caPrivKey, caPubKey); // Instantiate a new AC generator X509V2AttributeCertificateGenerator acGen = new X509V2AttributeCertificateGenerator(); acGen.reset(); // // Holder: here we use the IssuerSerial form // acGen.setHolder(new AttributeCertificateHolder(clientCert)); // set the Issuer acGen.setIssuer(new AttributeCertificateIssuer(caCert.getSubjectX500Principal())); // // serial number (as it's an example we don't have to keep track of the // serials anyway // acGen.setSerialNumber(BigInteger.ONE); // not Before acGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); // not After acGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); // signature Algorithmus acGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.rfc822Name, "DAU123456789"); ASN1EncodableVector roleSyntax = new ASN1EncodableVector(); roleSyntax.add(roleName); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DERSequence(roleSyntax)); acGen.addAttribute(attributes); // finally create the AC X509V2AttributeCertificate att = (X509V2AttributeCertificate) acGen.generate(caPrivKey, "BC"); //String encoded = new String(att.getEncoded()); //System.out.println("CERT CERT: " + encoded); //KeyStore store = KeyStore.getInstance("PKCS12"); //String pass = "redhat"; /*FileOutputStream fout = new FileOutputStream("/tmp/foo.file"); store.load(null, null); store.store(fout, pass.toCharArray()); X509CertificateObject ccert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(att)));*/ // // starting here, we parse the newly generated AC // // Holder AttributeCertificateHolder h = att.getHolder(); if (h.match(clientCert)) { if (h.getEntityNames() != null) { // System.out.println(h.getEntityNames().length + // " entity names found"); } if (h.getIssuer() != null) { // System.out.println(h.getIssuer().length + // " issuer names found, serial number " + // h.getSerialNumber()); } // System.out.println("Matches original client x509 cert"); } // Issuer AttributeCertificateIssuer issuer = att.getIssuer(); if (issuer.match(caCert)) { if (issuer.getPrincipals() != null) { // System.out.println(issuer.getPrincipals().length + // " entity names found"); } // System.out.println("Matches original ca x509 cert"); } // Dates // System.out.println("valid not before: " + att.getNotBefore()); // System.out.println("valid not before: " + att.getNotAfter()); // check the dates, an exception is thrown in checkValidity()... try { att.checkValidity(); att.checkValidity(new Date()); } catch (Exception e) { System.out.println(e); } // verify try { att.verify(caPubKey, "BC"); } catch (Exception e) { System.out.println(e); } // Attribute X509Attribute[] attribs = att.getAttributes(); // System.out.println("cert has " + attribs.length + " attributes:"); for (int i = 0; i < attribs.length; i++) { X509Attribute a = attribs[i]; // System.out.println("OID: " + a.getOID()); // currently we only check for the presence of a 'RoleSyntax' // attribute if (a.getOID().equals("2.5.24.72")) { // System.out.println("rolesyntax read from cert!"); } } }