private X509Certificate createSignedCertificate(X509Certificate cetrificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) throws Exception { Principal issuer = issuerCertificate.getSubjectDN(); String issuerSigAlg = issuerCertificate.getSigAlgName(); byte[] inCertBytes = cetrificate.getTBSCertificate(); X509CertInfo info = new X509CertInfo(inCertBytes); info.set(X509CertInfo.ISSUER, issuer); //No need to add the BasicContraint for leaf cert if (!cetrificate.getSubjectDN().getName().equals("CN=TOP")) { CertificateExtensions exts = new CertificateExtensions(); BasicConstraintsExtension bce = new BasicConstraintsExtension(true, -1); exts.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(false, bce.getExtensionValue())); info.set(X509CertInfo.EXTENSIONS, exts); } X509CertImpl outCert = new X509CertImpl(info); outCert.sign(issuerPrivateKey, issuerSigAlg); return outCert; }
private static void setKeyEntry(KeyStore ks, String dn, long expire) throws GeneralSecurityException, IOException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair keyPair = kpg.genKeyPair(); long now = System.currentTimeMillis(); X509CertInfo info = new X509CertInfo(); info.set("version", new CertificateVersion(2)); info.set("serialNumber", new CertificateSerialNumber(new BigInteger(128, random))); info.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA"))); X500Name x500Name = new X500Name(dn); info.set("subject", x500Name); info.set("key", new CertificateX509Key(keyPair.getPublic())); info.set("validity", new CertificateValidity(new Date(now), new Date(now + expire))); info.set("issuer", x500Name); X509CertImpl cert = new X509CertImpl(info); cert.sign(keyPair.getPrivate(), "SHA1withRSA"); ks.setKeyEntry(Bytes.toHexLower(Bytes.random(16)), keyPair.getPrivate(), new char[0], new X509Certificate[] {cert}); }
/** * Populate array of Issuer DNs from certificates and convert * each Principal to type X500Name if necessary. */ private void populateCertIssuerNames() { if (certificates == null) return; certIssuerNames = new Principal[certificates.length]; for (int i = 0; i < certificates.length; i++) { X509Certificate cert = certificates[i]; Principal certIssuerName = cert.getIssuerDN(); if (!(certIssuerName instanceof X500Name)) { // must extract the original encoded form of DN for // subsequent name comparison checks (converting to a // String and back to an encoded DN could cause the // types of String attribute values to be changed) try { X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate()); certIssuerName = (Principal) tbsCert.get(X509CertInfo.ISSUER + "." + X509CertInfo.DN_NAME); } catch (Exception e) { // error generating X500Name object from the cert's // issuer DN, leave name as is. } } certIssuerNames[i] = certIssuerName; } }
private String createEphemeralCert(Duration shiftIntoPast) throws GeneralSecurityException, IOException { Duration validFor = Duration.standardHours(1); DateTime notBefore = DateTime.now().minus(shiftIntoPast); DateTime notAfter = notBefore.plus(validFor); CertificateValidity interval = new CertificateValidity(notBefore.toDate(), notAfter.toDate()); X509CertInfo info = new X509CertInfo(); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(1)); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA"))); info.set( X509CertInfo.SUBJECT, new X500Name("C = US, O = Google\\, Inc, CN=temporary-subject")); info.set(X509CertInfo.KEY, new CertificateX509Key(clientKeyPair.getPublic())); info.set(X509CertInfo.VALIDITY, interval); info.set( X509CertInfo.ISSUER, new X500Name("C = US, O = Google\\, Inc, CN=Google Cloud SQL Signing CA foo:baz")); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary( TestKeys.SIGNING_CA_PRIVATE_KEY)); PrivateKey signingKey = keyFactory.generatePrivate(keySpec); X509CertImpl cert = new X509CertImpl(info); cert.sign(signingKey, "SHA1withRSA"); StringBuilder sb = new StringBuilder(); sb.append("-----BEGIN CERTIFICATE-----\n"); sb.append( DatatypeConverter.printBase64Binary(cert.getEncoded()) .replaceAll("(.{64})", "$1\n")); sb.append("\n"); sb.append("-----END CERTIFICATE-----\n"); return sb.toString(); }
/** * Create a self-signed X.509 Certificate. * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws IOException thrown if an IO error ocurred. * @throws GeneralSecurityException thrown if an Security error ocurred. */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws GeneralSecurityException, IOException { PrivateKey privkey = pair.getPrivate(); X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); CertificateValidity interval = new CertificateValidity(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); X500Name owner = new X500Name(dn); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); info .set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); // Sign the cert to identify the algorithm that's used. X509CertImpl cert = new X509CertImpl(info); cert.sign(privkey, algorithm); // Update the algorith, and resign. algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG); info .set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo); cert = new X509CertImpl(info); cert.sign(privkey, algorithm); return cert; }
/** * Populate array of Issuer DNs from certificates and convert * each Principal to type X500Name if necessary. */ private void populateCertIssuerNames() { if (certificates == null) return; certIssuerNames = new Principal[certificates.length]; for (int i = 0; i < certificates.length; i++) { X509Certificate cert = certificates[i]; Principal certIssuerName = cert.getIssuerDN(); if (!(certIssuerName instanceof X500Name)) { // must extract the original encoded form of DN for // subsequent name comparison checks (converting to a // String and back to an encoded DN could cause the // types of String attribute values to be changed) try { X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate()); certIssuerName = (Principal) tbsCert.get(CertificateIssuerName.NAME + "." + CertificateIssuerName.DN_NAME); } catch (Exception e) { // error generating X500Name object from the cert's // issuer DN, leave name as is. } } certIssuerNames[i] = certIssuerName; } }
private static X509Certificate generateCert( String hostname, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { X500Name issuer = new X500Name("CN=root" + issuerDirString); X500Name subject; if (hostname == null) { subject = issuer; } else { subject = new X500Name("CN=" + hostname + issuerDirString); } X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + 365 * 86400000l); CertificateValidity interval = new CertificateValidity(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(subject)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer)); info.set(X509CertInfo.KEY, new CertificateX509Key(kp.getPublic())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); // Sign the cert to identify the algorithm that's used. X509CertImpl cert = new X509CertImpl(info); cert.sign(signerPrivateKey, signingAlgorithm); // Update the algorithm, and resign. algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG); info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo); cert = new X509CertImpl(info); cert.sign(signerPrivateKey, signingAlgorithm); return cert; }
private static SSLContext getSSLContext(String dn, long expire) throws IOException, GeneralSecurityException { KeyManager[] kms; if (dn == null) { kms = SSLManagers.DEFAULT_KEY_MANAGERS; } else { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair keyPair = kpg.genKeyPair(); long now = System.currentTimeMillis(); X509CertInfo info = new X509CertInfo(); info.set("version", new CertificateVersion(2)); info.set("serialNumber", new CertificateSerialNumber(0)); info.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA"))); X500Name x500Name = new X500Name(dn); info.set("subject", x500Name); info.set("key", new CertificateX509Key(keyPair.getPublic())); info.set("validity", new CertificateValidity(new Date(now), new Date(now + expire))); info.set("issuer", x500Name); X509CertImpl cert = new X509CertImpl(info); cert.sign(keyPair.getPrivate(), "SHA1withRSA"); ks.setKeyEntry("", keyPair.getPrivate(), new char[0], new X509Certificate[] {cert}); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, new char[0]); kms = kmf.getKeyManagers(); } SSLContext sslc = SSLContext.getInstance("TLS"); sslc.init(kms, SSLManagers.DEFAULT_TRUST_MANAGERS, null); return sslc; }
static SSLContext get(String dn, long expire) throws IOException, GeneralSecurityException { KeyManager[] kms; if (dn == null) { kms = SSLManagers.DEFAULT_KEY_MANAGERS; } else { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair keyPair = kpg.genKeyPair(); long now = System.currentTimeMillis(); X509CertInfo info = new X509CertInfo(); info.set("version", new CertificateVersion(2)); info.set("serialNumber", new CertificateSerialNumber(new BigInteger(128, random))); info.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA"))); X500Name x500Name = new X500Name(dn); info.set("subject", x500Name); info.set("key", new CertificateX509Key(keyPair.getPublic())); info.set("validity", new CertificateValidity(new Date(now), new Date(now + expire))); info.set("issuer", x500Name); X509CertImpl cert = new X509CertImpl(info); cert.sign(keyPair.getPrivate(), "SHA1withRSA"); ks.setKeyEntry("", keyPair.getPrivate(), new char[0], new X509Certificate[] {cert}); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, new char[0]); kms = kmf.getKeyManagers(); } SSLContext sslc = SSLContext.getInstance("TLS"); sslc.init(kms, SSLManagers.DEFAULT_TRUST_MANAGERS, null); return sslc; }
public F() { // jdk internal API cert = new X509CertInfo(); }
/** * Create an X509 Certificate signed using SHA1withRSA with a 2048 bit key. * @param dname Domain Name to represent the certificate * @param notBefore The date by which the certificate starts being valid. Cannot be null. * @param validity The number of days the certificate is valid after notBefore. * @return An X509 certificate setup with properties using the specified parameters. * @throws Exception */ public static X509Certificate createCert(String dname, Date notBefore, int validity) throws Exception { int keysize = 2048; String keyAlgName = "RSA"; String sigAlgName = "SHA1withRSA"; if (dname == null) throw new Exception("Required DN is null. Please specify cert Domain Name via dname"); if (notBefore == null) throw new Exception("Required start date is null. Please specify the date at which the cert is valid via notBefore"); if (validity < 0) throw new Exception("Required validity is negative. Please specify the number of days for which the cert is valid after the start date."); // KeyTool#doGenKeyPair X500Name x500Name = new X500Name(dname); KeyPair keyPair = new KeyPair(keyAlgName, sigAlgName, keysize); PrivateKey privKey = keyPair.getPrivateKey(); X509Certificate oldCert = keyPair.getSelfCertificate(x500Name, notBefore, validity); // KeyTool#doSelfCert byte[] encoded = oldCert.getEncoded(); X509CertImpl certImpl = new X509CertImpl(encoded); X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO); Date notAfter = new Date(notBefore.getTime() + validity*1000L*24L*60L*60L); CertificateValidity interval = new CertificateValidity(notBefore, notAfter); certInfo.set(X509CertInfo.VALIDITY, interval); certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( new java.util.Random().nextInt() & 0x7fffffff)); certInfo.set(X509CertInfo.SUBJECT + "." + CertificateSubjectName.DN_NAME, x500Name); certInfo.set(X509CertInfo.ISSUER + "." + CertificateIssuerName.DN_NAME, x500Name); // The inner and outer signature algorithms have to match. // The way we achieve that is really ugly, but there seems to be no // other solution: We first sign the cert, then retrieve the // outer sigalg and use it to set the inner sigalg X509CertImpl newCert = new X509CertImpl(certInfo); newCert.sign(privKey, sigAlgName); AlgorithmId sigAlgid = (AlgorithmId)newCert.get(X509CertImpl.SIG_ALG); certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, sigAlgid); certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); // FIXME Figure out extensions // CertificateExtensions ext = createV3Extensions( // null, // (CertificateExtensions)certInfo.get(X509CertInfo.EXTENSIONS), // v3ext, // oldCert.getPublicKey(), // null); // certInfo.set(X509CertInfo.EXTENSIONS, ext); newCert = new X509CertImpl(certInfo); newCert.sign(privKey, sigAlgName); return newCert; }
/** * Create a self-signed X.509 Example * * @param dn * the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair * the KeyPair * @param days * how many days from now the Example is valid for * @param algorithm * the signing algorithm, eg "SHA1withRSA" */ public static CX509Certificate generateCertificate(final String aDn, final KeyPair aKeyPair, final int aNbDays, String aAlgorithm) throws IOException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { if (aAlgorithm == null) { aAlgorithm = "SHA1withRSA"; } PrivateKey privkey = aKeyPair.getPrivate(); X509CertInfo wInfo = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + aNbDays * 86400000l); CertificateValidity interval = new CertificateValidity(from, to); // compute // certificate // validatity BigInteger sn = new BigInteger(64, new SecureRandom()); X500Name owner = new X500Name(aDn); wInfo.set(X509CertInfo.VALIDITY, interval); wInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); wInfo.set(X509CertInfo.SUBJECT, owner); wInfo.set(X509CertInfo.ISSUER, owner); wInfo.set(X509CertInfo.KEY, new CertificateX509Key(aKeyPair.getPublic())); wInfo.set(X509CertInfo.VERSION, new CertificateVersion( CertificateVersion.V3)); AlgorithmId wAlgo = new AlgorithmId( AlgorithmId.md5WithRSAEncryption_oid); wInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(wAlgo)); // Sign the cert to identify the algorithm that's used. X509CertImpl wCert = new X509CertImpl(wInfo); wCert.sign(privkey, aAlgorithm); // Update the algorith, and resign. wAlgo = (AlgorithmId) wCert.get(X509CertImpl.SIG_ALG); wInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, wAlgo); wCert = new X509CertImpl(wInfo); wCert.sign(privkey, aAlgorithm); return new CX509Certificate(wCert); }