List of usage examples for org.bouncycastle.asn1.x509 GeneralName otherName
int otherName
To view the source code for org.bouncycastle.asn1.x509 GeneralName otherName.
Click Source Link
From source file:net.sf.portecle.crypto.X509Ext.java
License:Open Source License
/** * Get the supplied general name as a string ([general name type]=[general name]). * /*from w w w.j av a2s . c o m*/ * <pre> * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, x * dNSName [2] IA5String, x * x400Address [3] ORAddress, * directoryName [4] Name, x * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, x * iPAddress [7] OCTET STRING, x * registeredID [8] OBJECT IDENTIFIER x } * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * EDIPartyName ::= SEQUENCE { * nameAssigner [0] DirectoryString OPTIONAL, * partyName [1] DirectoryString } * DirectoryString ::= CHOICE { * teletexString TeletexString (SIZE (1..maxSize), * printableString PrintableString (SIZE (1..maxSize)), * universalString UniversalString (SIZE (1..maxSize)), * utf8String UTF8String (SIZE (1.. MAX)), * bmpString BMPString (SIZE(1..maxSIZE)) } * </pre> * * @param generalName The general name * @return General name string * @throws IOException */ private String getGeneralNameString(GeneralName generalName, LinkClass linkClass) throws IOException { StringBuilder strBuff = new StringBuilder(); int tagNo = generalName.getTagNo(); switch (tagNo) { case GeneralName.otherName: ASN1Sequence other = (ASN1Sequence) generalName.getName(); String sOid = ((ASN1ObjectIdentifier) other.getObjectAt(0)).getId(); String sVal = stringify(other.getObjectAt(1)); try { strBuff.append(RB.getString(sOid)); } catch (MissingResourceException e) { strBuff.append(MessageFormat.format(RB.getString("GeneralName." + tagNo), sOid)); } strBuff.append(": "); strBuff.append(sVal); break; case GeneralName.rfc822Name: String sRfc822 = generalName.getName().toString(); String urlEnc = URLEncoder.encode(sRfc822, "UTF-8"); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(getLink("mailto:" + urlEnc, escapeHtml(sRfc822), null)); break; case GeneralName.dNSName: case GeneralName.registeredID: case GeneralName.x400Address: // TODO: verify formatting case GeneralName.ediPartyName: // TODO: verify formatting strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(escapeHtml(generalName.getName())); break; case GeneralName.directoryName: ASN1Encodable name = generalName.getName(); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); // TODO: make E=foo@bar.com mail links strBuff.append(escapeHtml(name)); break; case GeneralName.uniformResourceIdentifier: String sUri = generalName.getName().toString(); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(getLink(sUri, escapeHtml(sUri), linkClass)); break; case GeneralName.iPAddress: ASN1OctetString ipAddress = (ASN1OctetString) generalName.getName(); byte[] bIpAddress = ipAddress.getOctets(); // Output the IP Address components one at a time separated by dots StringBuilder sbIpAddress = new StringBuilder(); for (int iCnt = 0, bl = bIpAddress.length; iCnt < bl; iCnt++) { // Convert from (possibly negative) byte to positive int sbIpAddress.append(bIpAddress[iCnt] & 0xFF); if ((iCnt + 1) < bIpAddress.length) { sbIpAddress.append('.'); } } strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(escapeHtml(sbIpAddress)); break; default: // Unsupported general name type strBuff.append( MessageFormat.format(RB.getString("UnrecognizedGeneralNameType"), generalName.getTagNo())); strBuff.append(": "); strBuff.append(escapeHtml(generalName.getName())); break; } return strBuff.toString(); }
From source file:org.apache.kerby.pkix.EndEntityGenerator.java
License:Apache License
/** * Generate certificate.//from ww w .jav a2 s .c om * * @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.TlsHelperTest.java
License:Apache License
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) { List<String> sans = new ArrayList<>(); Attribute[] certAttributes = csr.getAttributes(); for (Attribute attribute : certAttributes) { if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); GeneralName[] names = gns.getNames(); for (GeneralName name : names) { logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName()); String title = ""; if (name.getTagNo() == GeneralName.dNSName) { title = "DNS"; } else if (name.getTagNo() == GeneralName.iPAddress) { title = "IP Address"; // name.toASN1Primitive(); } else if (name.getTagNo() == GeneralName.otherName) { title = "Other Name"; }//from ww w. j a v a 2 s. co m sans.add(title + ": " + name.getName()); } } } return sans; }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Creates an X.509 {@link GeneralName} for use as a <em>Common Name</em> in the certificate's <em>Subject Alternative Names</em> * extension. A <em>common name</em> is a name with a tag of {@link GeneralName#otherName OTHER}, with an object-id that references * the {@link #CN_OID cn} attribute, an explicit tag of '0', and a DER encoded UTF8 string for the name. * This usage of using the {@code cn} OID as a <em>Subject Alternative Name</em> is <strong>non-standard</strong> and will not be * recognised by other X.509/TLS implementations. *///ww w . ja v a 2 s . c o m public static GeneralName createCommonName(String cn) { final ASN1Encodable[] sequence = { new ASN1ObjectIdentifier(CN_OID), new DERTaggedObject(true, 0, new DERUTF8String(cn)) }; return new GeneralName(GeneralName.otherName, new DERSequence(sequence)); }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java
License:Open Source License
private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception { final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); assertEquals(expectedCount, subjAltNames.getNames().length); Collections.sort(certInfo.dnsNames); Collections.sort(certInfo.ipAddresses); for (GeneralName generalName : subjAltNames.getNames()) { if (generalName.getTagNo() == GeneralName.dNSName) { String dns = ((ASN1String) generalName.getName()).getString(); assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals)); } else if (generalName.getTagNo() == GeneralName.iPAddress) { byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets(); String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes)); assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals)); } else if (generalName.getTagNo() == GeneralName.otherName) { ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName()); assertThat(seq.size(), equalTo(2)); assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class)); assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID)); assertThat(seq.getObjectAt(1), instanceOf(DERTaggedObject.class)); DERTaggedObject taggedName = (DERTaggedObject) seq.getObjectAt(1); assertThat(taggedName.getTagNo(), equalTo(0)); assertThat(taggedName.getObject(), instanceOf(ASN1String.class)); assertThat(taggedName.getObject().toString(), Matchers.isIn(certInfo.commonNames)); } else {//from w w w . j a v a 2s . c o m fail("unknown general name with tag " + generalName.getTagNo()); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java
License:Open Source License
private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception { final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); assertEquals(expectedCount, subjAltNames.getNames().length); Collections.sort(certInfo.dnsNames); Collections.sort(certInfo.ipAddresses); for (GeneralName generalName : subjAltNames.getNames()) { if (generalName.getTagNo() == GeneralName.dNSName) { String dns = ((ASN1String) generalName.getName()).getString(); assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals)); } else if (generalName.getTagNo() == GeneralName.iPAddress) { byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets(); String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes)); assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals)); } else if (generalName.getTagNo() == GeneralName.otherName) { ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName()); assertThat(seq.size(), equalTo(2)); assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class)); assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID)); assertThat(seq.getObjectAt(1), instanceOf(ASN1TaggedObject.class)); ASN1TaggedObject tagged = (ASN1TaggedObject) seq.getObjectAt(1); assertThat(tagged.getObject(), instanceOf(ASN1String.class)); assertThat(tagged.getObject().toString(), Matchers.isIn(certInfo.commonNames)); } else {//w w w . jav a2 s .c om fail("unknown general name with tag " + generalName.getTagNo()); } } }
From source file:org.jivesoftware.util.CertificateManager.java
License:Open Source License
/** * Creates an X509 version3 certificate. * * @param kp KeyPair that keeps the public and private keys for the new certificate. * @param months time to live//w w w .j a v a 2 s.c o m * @param issuerDN Issuer string e.g "O=Grid,OU=OGSA,CN=ACME" * @param subjectDN Subject string e.g "O=Grid,OU=OGSA,CN=John Doe" * @param domain Domain of the server. * @param signAlgoritm Signature algorithm. This can be either a name or an OID. * @return X509 V3 Certificate * @throws GeneralSecurityException * @throws IOException */ private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN, String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException { PublicKey pubKey = kp.getPublic(); PrivateKey privKey = kp.getPrivate(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger serial = (new java.math.BigInteger(serno)).abs(); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); certGenerator.setSerialNumber(serial); certGenerator.setIssuerDN(new X509Name(issuerDN)); certGenerator.setNotBefore(new Date(System.currentTimeMillis())); certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30))); certGenerator.setSubjectDN(new X509Name(subjectDN)); certGenerator.setPublicKey(pubKey); certGenerator.setSignatureAlgorithm(signAlgoritm); // Generate the subject alternative name boolean critical = subjectDN == null || "".equals(subjectDN.trim()); ASN1Sequence othernameSequence = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence); GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN }); // Add subject alternative name extension certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames); X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; }
From source file:org.jruby.ext.openssl.X509Extension.java
License:LGPL
@SuppressWarnings("unchecked") private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) { final ASN1Encodable obj = name.getName(); String val; boolean tagged = false; switch (name.getTagNo()) { case GeneralName.rfc822Name: if (!tagged) out.append('e').append('m').append('a').append('i').append('l').append(':'); tagged = true;// ww w . j ava2 s . c om case GeneralName.dNSName: if (!tagged) out.append('D').append('N').append('S').append(':'); tagged = true; case GeneralName.uniformResourceIdentifier: if (!tagged) out.append('U').append('R').append('I').append(':'); val = DERIA5String.getInstance(obj).getString(); out.append(ByteList.plain(val)); break; case GeneralName.directoryName: out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':'); final X500Name dirName = X500Name.getInstance(obj); if (slashed) { final RDN[] rdns = dirName.getRDNs(); final Hashtable defaultSymbols = getDefaultSymbols(); for (int i = 0; i < rdns.length; i++) { appendRDN(out.append('/'), rdns[i], defaultSymbols); } } else { out.append(ByteList.plain(dirName.toString())); } break; case GeneralName.iPAddress: out.append('I').append('P').append(':'); final byte[] ip = ((ASN1OctetString) name.getName()).getOctets(); int len = ip.length; boolean ip4 = len == 4; for (int i = 0; i < ip.length; i++) { out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff)); if (i != len - 1) { if (ip4) out.append('.'); else out.append(':').append(':'); } } break; case GeneralName.otherName: out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m') .append('e').append(':'); out.append(ByteList.plain(obj.toString())); return true; //tagged = true; case GeneralName.registeredID: out.append('R').append('I').append('D').append(':'); //tagged = true; default: out.append(ByteList.plain(obj.toString())); } return false; }
From source file:org.jruby.ext.openssl.X509ExtensionFactory.java
License:LGPL
private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException { if (valuex.startsWith(DNS_)) { final String dns = valuex.substring(DNS_.length()); return new GeneralName(GeneralName.dNSName, dns); }//from ww w. ja va 2 s . com if (valuex.startsWith(DNS_Name_)) { final String dns = valuex.substring(DNS_Name_.length()); return new GeneralName(GeneralName.dNSName, dns); } if (valuex.startsWith(URI_)) { final String uri = valuex.substring(URI_.length()); return new GeneralName(GeneralName.uniformResourceIdentifier, uri); } if (valuex.startsWith(RID_)) { final String rid = valuex.substring(RID_.length()); return new GeneralName(GeneralName.registeredID, rid); } if (valuex.startsWith(email_)) { final String mail = valuex.substring(email_.length()); return new GeneralName(GeneralName.rfc822Name, mail); } if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) { final int idx = valuex.charAt(2) == ':' ? 3 : 11; String[] vals = valuex.substring(idx).split("\\.|::"); final byte[] ip = new byte[vals.length]; for (int i = 0; i < vals.length; i++) { ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff); } return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip)); } if (valuex.startsWith("other")) { // otherName || othername final String other = valuex.substring(otherName_.length()); return new GeneralName(GeneralName.otherName, other); } if (valuex.startsWith("dir")) { // dirName || dirname final String dir = valuex.substring(dirName_.length()); return new GeneralName(GeneralName.directoryName, dir); } throw new IOException("could not parse SubjectAltName: " + valuex); }
From source file:org.kontalk.certgen.X509Bridge.java
License:Open Source License
/** * Creates a self-signed certificate from a public and private key. The * (critical) key-usage extension is set up with: digital signature, * non-repudiation, key-encipherment, key-agreement and certificate-signing. * The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. * * @param pubKey/*from www . j av a 2 s . c o m*/ * public key * @param privKey * private key * @param subject * subject (and issuer) DN for this certificate, RFC 2253 format * preferred. * @param startDate * date from which the certificate will be valid * (defaults to current date and time if null) * @param endDate * date until which the certificate will be valid * (defaults to start date and time if null) * @param subjectAltName * URI to be placed in subjectAltName * @return self-signed certificate */ private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject, Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, IOException, OperatorCreationException { /* * Sets the signature algorithm. */ BcContentSignerBuilder signerBuilder; String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId); } else if (pubKeyAlgorithm.equals("RSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA1WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); } /* else if (pubKeyAlgorithm.equals("ECDSA")) { // TODO is this even legal? certGenerator.setSignatureAlgorithm("SHA1WithECDSA"); } */ else { throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); } AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded()); ContentSigner signer = signerBuilder.build(keyp); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } if (endDate == null) { endDate = startDate; } X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( /* * Sets up the subject distinguished name. * Since it's a self-signed certificate, issuer and subject are the * same. */ subject, /* * The serial-number of this certificate is 1. It makes sense * because it's self-signed. */ BigInteger.ONE, startDate, endDate, subject, /* * Sets the public-key to embed in this certificate. */ SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject())); /* * Adds the Basic Constraint (CA: true) extension. */ certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); /* * Adds the Key Usage extension. */ certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.keyAgreement | KeyUsage.keyCertSign)); /* * Adds the Netscape certificate type extension. */ certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime)); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjectAltName != null) { GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName)); certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } /* * Adds the PGP public key block extension. */ SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData); certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension); /* * Creates and sign this certificate with the private key * corresponding to the public key of the certificate * (hence the name "self-signed certificate"). */ X509CertificateHolder holder = certBuilder.build(signer); /* * Checks that this certificate has indeed been correctly signed. */ X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder); cert.verify(pubKey); return cert; }