org.bouncycastle.asn1.x509.X509Name Java Examples
The following examples show how to use
org.bouncycastle.asn1.x509.X509Name.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: X509CertUtils.java From MaxKey with Apache License 2.0 | 6 votes |
/** * Create a PKCS #10 certification request (CSR) using the supplied * certificate and private key. * * @param cert * The certificate * @param privateKey * The private key * @throws CryptoException * If there was a problem generating the CSR * @return The CSR */ public static PKCS10CertificationRequest generatePKCS10CSR( X509Certificate cert, PrivateKey privateKey) throws CryptoException { X509Name subject = new X509Name(cert.getSubjectDN().toString()); try { PKCS10CertificationRequest csr = new PKCS10CertificationRequest( cert.getSigAlgName(), subject, cert.getPublicKey(), null, privateKey); if (!csr.verify()) { throw new CryptoException( "Could not verify generated certification request."); } return csr; } catch (GeneralSecurityException ex) { throw new CryptoException( "Could not generate a certification request.", ex); } }
Example #2
Source File: GridCertRequest.java From swift-k with Apache License 2.0 | 6 votes |
private static X509Name makePTLSX509Name(String subject) throws Exception { Vector tdn = new Vector(); Vector elems = new Vector(); StringTokenizer st = new StringTokenizer(subject,","); for (; st.hasMoreTokens() ;) { String s = st.nextToken(); // [key=value] if ( s.indexOf("=") == -1 ) throw new Exception("Invalid subject format: " + subject + " Offending value: " + s); String key = s.substring(0, s.indexOf("=")).trim(); String val = s.substring(s.indexOf("=") + 1).trim(); if ( val == null || val.equals("")) throw new Exception("Invalid subject format: " + subject + " Offending value: " + s); //logger.debug(key + "=" + val); String[] temp = {key, val}; tdn.addElement(temp); } // COM.claymoresystems.cert (puretls.jar) return CertRequest.makeSimpleDN(tdn); }
Example #3
Source File: NameUtil.java From MaxKey with Apache License 2.0 | 5 votes |
/** * Gets the common name from the given X509Name. * * @param name * the X.509 name * @return the common name, null if not found */ public static String getCommonName(X509Name name) { if (name == null) { return null; } Vector<?> values = name.getValues(X509Name.CN); if (values == null || values.isEmpty()) { return null; } return values.get(0).toString(); }
Example #4
Source File: NameUtil.java From MaxKey with Apache License 2.0 | 5 votes |
/** * Gets the common name from the given X500Principal. * * @param name * the X.500 principal * @return the common name, null if not found */ public static String getCommonName(X500Principal name) { if (name == null) { return null; } return getCommonName(new X509Name(name.getName())); }
Example #5
Source File: GridCertRequest.java From swift-k with Apache License 2.0 | 5 votes |
/** * Generates a encrypted private key and certificate request. */ static public void genCertificateRequest( String dname, String emailAddressOfCA, String password, String privKeyLoc, String certLoc, String certReqLoc) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; CertUtil.init(); // Generate a new key pair. KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName); KeyPair keyPair = keygen.genKeyPair(); PrivateKey privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); // Generate the certificate request. X509Name name = new X509Name(dname); DERConstructedSet derSet = new DERConstructedSet(); PKCS10CertificationRequest request = new PKCS10CertificationRequest( sigAlgName, name, pubKey, derSet, privKey); // Save the certificate request to a .pem file. byte[] data = request.getEncoded(); PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc)); // build / delimited name. String certSubject = ""; StringTokenizer tokens = new StringTokenizer(dname, ","); while(tokens.hasMoreTokens()){ certSubject = certSubject + "/" + tokens.nextToken(); } ps.print( "\n\n" + "Please mail the following certificate request to " + emailAddressOfCA + "\n" + "\n" + "==================================================================\n" + "\n" + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n" + "The above string is known as your user certificate subject, and it \n" + "uniquely identifies this user.\n" + "\n" + "To install this user certificate, please save this e-mail message\n" + "into the following file.\n" + "\n" + "\n" + certLoc + "\n" + "\n" + "\n" + " You need not edit this message in any way. Simply \n" + " save this e-mail message to the file.\n" + "\n" + "\n" + "If you have any questions about the certificate contact\n" + "the Certificate Authority at " + emailAddressOfCA + "\n" + "\n"); ps.print(toPEM(data)); ps.close(); // Save private key to a .pem file. OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey); if (password.length() != 0) { key.encrypt(password); } key.writeTo(new File(privKeyLoc).getAbsolutePath()); // set read only permissions Util.setFilePermissions(privKeyLoc, 600); // Create an empty cert file. File f = new File(certLoc); f.createNewFile(); }
Example #6
Source File: CertificateUtil.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
public static X509Certificate generateCertificate(final PublicKey publicKey, final PrivateKey privateKey, final String algorithm, final int validDays, final String commonName, final String orgUnit, final String organization, final String locality, final String state, final String country) throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, CertificateEncodingException { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); Vector<ASN1ObjectIdentifier> order = new Vector<>(); Hashtable<ASN1ObjectIdentifier, String> attributeMap = new Hashtable<>(); if (commonName != null) { attributeMap.put(X509Name.CN, commonName); order.add(X509Name.CN); } if (orgUnit != null) { attributeMap.put(X509Name.OU, orgUnit); order.add(X509Name.OU); } if (organization != null) { attributeMap.put(X509Name.O, organization); order.add(X509Name.O); } if (locality != null) { attributeMap.put(X509Name.L, locality); order.add(X509Name.L); } if (state != null) { attributeMap.put(X509Name.ST, state); order.add(X509Name.ST); } if (country != null) { attributeMap.put(X509Name.C, country); order.add(X509Name.C); } X509Name issuerDN = new X509Name(order, attributeMap); // validity long now = System.currentTimeMillis(); long expire = now + (long) validDays * 24 * 60 * 60 * 1000; certificateGenerator.setNotBefore(new Date(now)); certificateGenerator.setNotAfter(new Date(expire)); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(issuerDN); certificateGenerator.setPublicKey(publicKey); certificateGenerator.setSignatureAlgorithm(algorithm); certificateGenerator.setSerialNumber(BigInteger.valueOf(now)); // make certificate return certificateGenerator.generate(privateKey); }
Example #7
Source File: SslUtil.java From DeviceConnect-Android with MIT License | 4 votes |
/** * Generates a new, self-signed X509 V3 certificate for a KeyPair. * * @param pair the {@link KeyPair} to be used * @param name X.500 distinguished name * @param notBefore not valid before this date * @param notAfter not valid after this date * @param serialNumber serial number * @return the new certificate * @throws GeneralSecurityException on error generating the certificate */ @SuppressWarnings("deprecation") public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore, Date notAfter, BigInteger serialNumber) throws GeneralSecurityException { java.security.Security.addProvider( new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name(name); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setNotBefore(notBefore); certGen.setNotAfter(notAfter); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // For self-signed certificates, OpenSSL 0.9.6 has specific requirements // about certificate and extension content. Quoting the `man verify`: // // In OpenSSL 0.9.6 and later all certificates whose subject name matches // the issuer name of the current certificate are subject to further // tests. The relevant authority key identifier components of the current // certificate (if present) must match the subject key identifier (if // present) and issuer and serial number of the candidate issuer, in // addition the keyUsage extension of the candidate issuer (if present) // must permit certificate signing. // // In the code that follows, // - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign); // - the Authority Key Identifier extension is added, matching the // subject key identifier, and using the issuer, and serial number. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage( KeyPurposeId.id_kp_serverAuth)); AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier( pair.getPublic(), dnName, serialNumber); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true, authIdentifier); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifierStructure(pair.getPublic())); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames( new GeneralName(GeneralName.rfc822Name, "[email protected]"))); // This method is deprecated, but Android Eclair does not provide the // generate() methods. X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), SecurityUtil.getSecurityProvider()); return cert; }
Example #8
Source File: GridCertRequest.java From swift-k with Apache License 2.0 | 4 votes |
/** * Certficate generation main function * @param dname Distinguished name (e.g John Doe) * @param password CSR password * @param outKey Out stream to the private key * @param outCertReq CSR out stream * @throws java.lang.Exception if error */ static public void makeCertificateRequest( String dname, String password, OutputStream outKey, OutputStream outCertReq) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; CertUtil.init(); // load CA certs and grab the DN for the request (every thing but the CN part) TrustedCertificates tcerts = TrustedCertificates.getDefaultTrustedCertificates(); String CADN = ""; if(tcerts != null){ X509Certificate[] caCerts = tcerts.getCertificates(); if(caCerts == null){ System.out.println("Warning: No trusted certificates found."); } else { CADN = (((caCerts.length == 0) || (caCerts[0] == null)) ? "" : (caCerts[0].getSubjectDN().toString())); } } else { System.out.println("Warning: No trusted certificates found."); } if(CADN == null){ CADN = ""; } // replace CA dn's CN elem with the user's CN if ( CADN.indexOf("CN") != -1 ) CADN = CADN.substring(0, CADN.indexOf("CN") ); if ( CADN.indexOf("cn") != -1 ) CADN = CADN.substring(0, CADN.indexOf("cn") ); dname = CADN + "CN=" + dname; logger.debug("Using DN=" + dname); KeyPair kp = null; byte[] data = null; // pure TLS can only create encrypted CSRs, OpenSSLKey gives an exception when encrypting if (password.length() != 0) { StringWriter sw = new StringWriter(); // will contain the priv key PEM BufferedWriter bw = new BufferedWriter(sw); kp = CertRequest.generateKey(keyAlgName, 1024, password, bw, true); // gen pub/priv keys data = CertRequest.makePKCS10Request(kp, makePTLSX509Name(dname)); // save encrypted private key outKey.write(sw.toString().getBytes()); } else { // OpenSSLKey gives an exception when encrypting, thus // use for unenc CSRs only...until fixed kp = KeyPairGenerator.getInstance(keyAlgName).generateKeyPair(); data = new PKCS10CertificationRequest( sigAlgName, new org.bouncycastle.asn1.x509.X509Name(dname), kp.getPublic(), new DERConstructedSet(), kp.getPrivate()).getEncoded(); // save unencrypted priv key OpenSSLKey key = new BouncyCastleOpenSSLKey(kp.getPrivate()); key.writeTo(outKey); } // Save the certificate request to a .pem file. PrintStream ps = new PrintStream(outCertReq); ps.println(makeRequestInfoHeader(dname)); ps.print(toPEM(data)); ps.close(); }