List of usage examples for org.bouncycastle.asn1.x509 X509Name X509Name
public X509Name(boolean reverse, Hashtable lookUp, String dirName)
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception { PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile)); String subject = csr.getCertificationRequestInfo().getSubject().toString(); // Generate the app certificate X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset();/* ww w . j a v a 2 s.c o m*/ X509Certificate rootCert = (X509Certificate) store.getCertificate(alias); if (rootCert == null) { System.out .println("ERROR: Aborting application certificate creation." + " No root certificate to sign."); cleanup(); // removes the self signed certificate from the keystore System.exit(1); } cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter())); cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter())); cg.setNotBefore(rootCert.getNotBefore()); cg.setNotAfter(rootCert.getNotAfter()); cg.setPublicKey(csr.getPublicKey()); cg.setSerialNumber(appCertSerNo); // BD-J mandates using SHA1WithRSA as a signature Algorithm cg.setSignatureAlgorithm("SHA1WITHRSA"); cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature)); // FIXME: Ideally this should be pulled out from the original app cert's // extension. Email on X500Name is not encoded with UTF8String. cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName)); // Assuming that the root certificate was generated using our tool, // the certificate should have IssuerAlternativeNames as an extension. if (rootCert.getIssuerAlternativeNames() == null) { System.out.println("ERROR: the root certificate must have an alternate name"); System.exit(1); } List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next(); cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name((String) issuerName.get(1))); PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray()); X509Certificate cert = cg.generate(privateKey); // Now, write leaf certificate System.out.println("Writing cert to " + certfile + "."); FileOutputStream str = new FileOutputStream(certfile); str.write(cert.getEncoded()); str.close(); }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
/** * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID * (with order) are://from w ww .ja v a 2 s .c o m * <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU, * O, L, ST, DC, C </code> * To change order edit 'dnObjects' in this source file. Important NOT to mess * with the ordering within this class, since cert vierification on some * clients (IE :-() might depend on order. * * @param dn * String containing DN that will be transformed into X509Name, The * DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in * the string will be added to the end positions of OID array. * @param converter BC converter for DirectoryStrings, that determines which encoding is chosen * @param ldaporder true if LDAP ordering of DN should be used (default in EJBCA), false for X.500 order, ldap order is CN=A,OU=B,O=C,C=SE, x.500 order is the reverse * @return X509Name or null if input is null */ public static X509Name stringToBcX509Name(String dn, X509NameEntryConverter converter, boolean ldaporder) { if (dn == null) { return null; } Vector<DERObjectIdentifier> defaultOrdering = new Vector<DERObjectIdentifier>(); Vector<String> values = new Vector<String>(); X509NameTokenizer x509NameTokenizer = new X509NameTokenizer(dn); while (x509NameTokenizer.hasMoreTokens()) { // This is a pair key=val (CN=xx) String pair = x509NameTokenizer.nextToken(); // Will escape '+' and initial '#' chars int index = pair.indexOf('='); if (index != -1) { String key = pair.substring(0, index).toLowerCase().trim(); String val = pair.substring(index + 1); if (val != null) { // String whitespace from the beginning of the value, to handle the case // where someone type CN = Foo Bar val = StringUtils.stripStart(val, null); } // -- First search the OID by name in declared OID's DERObjectIdentifier oid = DnComponents.getOid(key); try { // -- If isn't declared, we try to create it if (oid == null) { oid = new DERObjectIdentifier(key); } defaultOrdering.add(oid); values.add(getUnescapedPlus(val)); } catch (IllegalArgumentException e) { // If it is not an OID we will ignore it log.warn("Unknown DN component ignored and silently dropped: " + key); } } else { log.warn("No 'key=value' pair encountered in token '" + pair + "' while converting subject DN '" + dn + "' into X509Name."); } } X509Name x509Name = new X509Name(defaultOrdering, values, converter); //-- Reorder fields X509Name orderedX509Name = getOrderedX509Name(x509Name, ldaporder, converter); //log.trace("<stringToBcX509Name"); return orderedX509Name; }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
/** * Obtain a X509Name reordered, if some fields from original X509Name * doesn't appear in "ordering" parameter, they will be added at end * in the original order./*w w w . j a va 2 s .c om*/ * * @param x509Name the X509Name that is unordered * @param ldaporder true if LDAP ordering of DN should be used (default in EJBCA), false for X.500 order, ldap order is CN=A,OU=B,O=C,C=SE, x.500 order is the reverse * @return X509Name with ordered conmponents according to the orcering vector */ private static X509Name getOrderedX509Name(final X509Name x509Name, final boolean ldaporder, final X509NameEntryConverter converter) { //-- Null prevent // Guess order of the input name final boolean isLdapOrder = !isDNReversed(x509Name.toString()); //-- New order for the X509 Fields final List<DERObjectIdentifier> newOrdering = new ArrayList<DERObjectIdentifier>(); final List<Object> newValues = new ArrayList<Object>(); //-- Add ordered fields @SuppressWarnings("unchecked") final Vector<DERObjectIdentifier> allOids = x509Name.getOIDs(); // If we think the DN is in LDAP order, first order it as a LDAP DN, if we don't think it's LDAP order // order it as a X.500 DN final List<DERObjectIdentifier> ordering = getX509FieldOrder(isLdapOrder); final HashSet<DERObjectIdentifier> hs = new HashSet<DERObjectIdentifier>(allOids.size() + ordering.size()); for (final DERObjectIdentifier oid : ordering) { if (!hs.contains(oid)) { hs.add(oid); @SuppressWarnings("unchecked") final Vector<Object> valueList = x509Name.getValues(oid); //-- Only add the OID if has not null value for (final Object value : valueList) { newOrdering.add(oid); newValues.add(value); } } } //-- Add unexpected fields to the end for (final DERObjectIdentifier oid : allOids) { if (!hs.contains(oid)) { hs.add(oid); @SuppressWarnings("unchecked") final Vector<Object> valueList = x509Name.getValues(oid); //-- Only add the OID if has not null value for (final Object value : valueList) { newOrdering.add(oid); newValues.add(value); if (log.isDebugEnabled()) { log.debug("added --> " + oid + " val: " + value); } } } } // If the requested ordering was the reverse of the ordering the input string was in (by our guess in the beginning) // we have to reverse the vectors if (ldaporder != isLdapOrder) { if (log.isDebugEnabled()) { log.debug("Reversing order of DN, ldaporder=" + ldaporder + ", isLdapOrder=" + isLdapOrder); } Collections.reverse(newOrdering); Collections.reverse(newValues); } //-- Return X509Name with the ordered fields return new X509Name(new Vector<DERObjectIdentifier>(newOrdering), new Vector<Object>(newValues), converter); }
From source file:org.mailster.core.crypto.CertificateUtilities.java
License:Open Source License
public static X509V3CertificateGenerator initCertificateGenerator(KeyPair pair, String issuerDN, String subjectDN, boolean isCA, long validityPeriod, String signatureAlgorithm) throws Exception { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); setSerialNumberAndValidityPeriod(v3CertGen, isCA, validityPeriod); v3CertGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, issuerDN)); v3CertGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, subjectDN)); v3CertGen.setPublicKey(pair.getPublic()); if (signatureAlgorithm != null) v3CertGen.setSignatureAlgorithm(signatureAlgorithm); else/*from ww w .jav a 2 s . co m*/ v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); return v3CertGen; }
From source file:org.mailster.core.crypto.CertificateUtilities.java
License:Open Source License
/** * Generate a CA Root certificate./* w w w . jav a2s . c om*/ */ private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN)); certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN)); setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier( new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pair.getPublic())); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation)); certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType( NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning)); return certGen.generate(pair.getPrivate(), "BC"); }
From source file:org.mailster.core.crypto.CertificateUtilities.java
License:Open Source License
/** * Generate a sample V3 certificate to use as an intermediate or end entity * certificate depending on the <code>isEndEntity</code> argument. *///from ww w. j av a 2 s.c o m private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN)); setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded(), new GeneralNames(new GeneralName( new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))), caCert.getSerialNumber())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); if (isEndEntity) { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); } else { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); } return certGen.generate(caKey, "BC"); }