Java Code Examples for java.security.KeyStore.setKeyEntry()

The following are Jave code examples for showing how to use setKeyEntry() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: javaide   File: KeyStoreFileManager.java   View Source Code Vote up 7 votes
public static String renameKey( String keystorePath, String storePass, String oldKeyName, String newKeyName, String keyPass)
    throws Exception
{
    char[] keyPw = null;

    try {
        KeyStore ks = loadKeyStore(keystorePath, storePass);
        if (ks instanceof JksKeyStore) newKeyName = newKeyName.toLowerCase();

        if (ks.containsAlias(newKeyName)) throw new KeyNameConflictException();

        keyPw = PasswordObfuscator.getInstance().decodeAliasPassword( keystorePath, oldKeyName, keyPass);
        Key key = ks.getKey(oldKeyName, keyPw);
        Certificate cert = ks.getCertificate( oldKeyName);

        ks.setKeyEntry(newKeyName, key, keyPw, new Certificate[] { cert});
        ks.deleteEntry( oldKeyName);

        writeKeyStore(ks, keystorePath, storePass);
        return newKeyName;
    }
    finally {
        PasswordObfuscator.flush(keyPw);
    }
}
 
Example 2
Project: hadoop-oss   File: KeyStoreTestUtil.java   View Source Code Vote up 6 votes
public static void createKeyStore(String filename,
    String password, String alias,
    Key privateKey, Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setKeyEntry(alias, privateKey, password.toCharArray(),
      new Certificate[]{cert});
  saveKeyStore(ks, filename, password);
}
 
Example 3
Project: calcite-avatica   File: SslDriverTest.java   View Source Code Vote up 6 votes
private void createSelfSignedCert(File targetKeystore, String keyName,
    String keystorePassword) {
  if (targetKeystore.exists()) {
    throw new RuntimeException("Keystore already exists: " + targetKeystore);
  }

  try {
    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(),
        kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] {cert});
    try (FileOutputStream fos = new FileOutputStream(targetKeystore)) {
      keystore.store(fos, password);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Project: devops-cstack   File: KeyStoreUtils.java   View Source Code Vote up 5 votes
public static KeyStore createDockerKeyStore(String certPath) throws IOException, GeneralSecurityException {

		PrivateKey privKey = loadPrivateKey(certPath + "/key.pem");
		Certificate[] certs = loadCertificates(certPath + "/cert.pem");

		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		keyStore.load(null);

		keyStore.setKeyEntry("docker", privKey, "docker".toCharArray(), certs);
		addCA(keyStore, certPath + "/ca.pem");
		return keyStore;
	}
 
Example 5
Project: kafka-0.11.0.0-src-with-comment   File: TestSslUtils.java   View Source Code Vote up 5 votes
public static void createKeyStore(String filename,
                                  Password password, String alias,
                                  Key privateKey, Certificate cert) throws GeneralSecurityException, IOException {
    KeyStore ks = createEmptyKeyStore();
    ks.setKeyEntry(alias, privateKey, password.value().toCharArray(),
            new Certificate[]{cert});
    saveKeyStore(ks, filename, password);
}
 
Example 6
Project: jdk8u-jdk   File: CipherTestUtils.java   View Source Code Vote up 5 votes
private static KeyStore createServerKeyStore(String publicKeyStr,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKeyStr == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKeyStr or "
                + "keySpecStr cannot be null");
    }
    String strippedPrivateKey = keySpecStr.substring(
            keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));

    // generate the private key.
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(strippedPrivateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKey priKey
            = (RSAPrivateKey) kf.generatePrivate(priKeySpec);

    // generate certificate chain
    try (InputStream is =
            new ByteArrayInputStream(publicKeyStr.getBytes())) {
        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate keyCert = cf.generateCertificate(is);
        Certificate[] chain = {keyCert};
        ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);
    }

    return ks;
}
 
Example 7
Project: jdk8u-jdk   File: BasicConstraints.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(boolean isServer) throws Exception {

        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        // create a key store
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(null, null);

        // import the trused cert
        ByteArrayInputStream is =
            new ByteArrayInputStream(trusedCertStr.getBytes());
        Certificate trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("SunJSSE Test Serivce", trusedCert);

        // import the certificate chain and key
        Certificate[] chain = new Certificate[3];

        is = new ByteArrayInputStream(caSignerStr.getBytes());
        Certificate caSignerCert = cf.generateCertificate(is);
        is.close();
        chain[2] = caSignerCert;

        is = new ByteArrayInputStream(certIssuerStr.getBytes());
        Certificate certIssuerCert = cf.generateCertificate(is);
        is.close();
        chain[1] = certIssuerCert;

        PKCS8EncodedKeySpec priKeySpec = null;
        if (isServer) {
            priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(serverPrivateKey));
            is = new ByteArrayInputStream(serverCertStr.getBytes());
        } else {
            priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(clientPrivateKey));
            is = new ByteArrayInputStream(clientCertStr.getBytes());
        }
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);
        Certificate keyCert = cf.generateCertificate(is);
        is.close();
        chain[0] = keyCert;

        ks.setKeyEntry("End Entity", priKey, passphrase, chain);

        // check the certification path
        PKIXParameters paras = new PKIXParameters(ks);
        paras.setRevocationEnabled(false);
        CertPath path = cf.generateCertPath(Arrays.asList(chain));
        CertPathValidator cv = CertPathValidator.getInstance("PKIX");
        cv.validate(path, paras);

        // create SSL context
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
        tmf.init(ks);

        SSLContext ctx = SSLContext.getInstance("TLS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;

        return ctx;
    }
 
Example 8
Project: jdk8u-jdk   File: IPIdentities.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 9
Project: openjdk-jdk10   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void test(Certificate certs[], String inKeyStorePath,
        String userAlias, String outStorePass, String outKeyPass)
        throws KeyStoreException, NoSuchProviderException, IOException,
        CertificateException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    // init output key store
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    outputKeyStore.load(null, null);
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
                inKeyStorePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        // input key store
        KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
                IN_KEYSTORE_PRV);
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        Key key = inputKeyStore
                .getKey(userAlias, IN_KEY_PASS.toCharArray());
        out.println("Input Key Algorithm " + key.getAlgorithm());
        out.println("====Input Certs=====");
        if (certs == null) {
            certs = new Certificate[] { inputKeyStore
                    .getCertificate(userAlias) };
        }
        for (Certificate cert : certs) {
            out.println(((X509Certificate) cert).getSubjectDN());
        }
        outputKeyStore.setKeyEntry(userAlias, key,
                outKeyPass.toCharArray(), certs);
        Certificate retCerts[] = outputKeyStore
                .getCertificateChain(userAlias);
        out.println("====Output Certs=====");
        for (Certificate retCert : retCerts) {
            out.println(((X509Certificate) retCert).getSubjectDN());
        }
        out.println("====Output Key Algorithm=====");
        Key outKey = outputKeyStore.getKey(userAlias,
                outKeyPass.toCharArray());
        out.println(outKey.getAlgorithm());

        if (!key.equals(outKey)) {
            throw new RuntimeException("key don't match");
        }
        if (!Arrays.equals(certs, retCerts)) {
            throw new RuntimeException("certs don't match");
        }
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
 
Example 10
Project: openjdk-jdk10   File: SunX509ExtendedTM.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf =
            TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    TrustManager tms[] = tmf.getTrustManagers();
    if (tms == null || tms.length == 0) {
        throw new Exception("unexpected trust manager implementation");
    } else {
       if (!(tms[0] instanceof X509ExtendedTrustManager)) {
        throw new Exception("unexpected trust manager implementation: "
                            + tms[0].getClass().getCanonicalName());
       }
    }


    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 11
Project: openjdk-jdk10   File: DisabledShortRSAKeys.java   View Source Code Vote up 4 votes
private static SSLContext generateSSLContext(String trustedCertStr,
            String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                        Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
            (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 12
Project: jdk8u-jdk   File: WriteP12Test.java   View Source Code Vote up 4 votes
private void test(Certificate certs[], String inKeyStorePath,
        String userAlias, String outStorePass, String outKeyPass)
        throws KeyStoreException, NoSuchProviderException, IOException,
        CertificateException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    // init output key store
    KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
    outputKeyStore.load(null, null);
    try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need
        // decode first.
        byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
                inKeyStorePath));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        // input key store
        KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
                IN_KEYSTORE_PRV);
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        // add key/certificate to output key store
        Key key = inputKeyStore
                .getKey(userAlias, IN_KEY_PASS.toCharArray());
        out.println("Input Key Algorithm " + key.getAlgorithm());
        out.println("====Input Certs=====");
        if (certs == null) {
            certs = new Certificate[] { inputKeyStore
                    .getCertificate(userAlias) };
        }
        for (Certificate cert : certs) {
            out.println(((X509Certificate) cert).getSubjectDN());
        }
        outputKeyStore.setKeyEntry(userAlias, key,
                outKeyPass.toCharArray(), certs);
        Certificate retCerts[] = outputKeyStore
                .getCertificateChain(userAlias);
        out.println("====Output Certs=====");
        for (Certificate retCert : retCerts) {
            out.println(((X509Certificate) retCert).getSubjectDN());
        }
        out.println("====Output Key Algorithm=====");
        Key outKey = outputKeyStore.getKey(userAlias,
                outKeyPass.toCharArray());
        out.println(outKey.getAlgorithm());

        if (!key.equals(outKey)) {
            throw new RuntimeException("key don't match");
        }
        if (!Arrays.equals(certs, retCerts)) {
            throw new RuntimeException("certs don't match");
        }
        // save output
        outputKeyStore.store(fout, outStorePass.toCharArray());
        // test output
        testKeyStore(outputKeyStore, outKeyPass.toCharArray());
    }
}
 
Example 13
Project: jdk8u-jdk   File: PKIXExtendedTM.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    TrustManager tms[] = tmf.getTrustManagers();
    if (tms == null || tms.length == 0) {
        throw new Exception("unexpected trust manager implementation");
    } else {
       if (!(tms[0] instanceof X509ExtendedTrustManager)) {
           throw new Exception("unexpected trust manager implementation: "
                            + tms[0].getClass().getCanonicalName());
       }
    }


    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 14
Project: openjdk-jdk10   File: Identities.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 15
Project: jdk8u-jdk   File: DNSIdentities.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 16
Project: jdk8u-jdk   File: TestKeyStoreEntry.java   View Source Code Vote up 4 votes
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 17
Project: jdk8u-jdk   File: DisabledShortDSAKeys.java   View Source Code Vote up 4 votes
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("DSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("DSA");
        DSAPrivateKey priKey =
                (DSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 18
Project: openjdk-jdk10   File: SelfIssuedCert.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trusedCertStr != null) {
        is = new ByteArrayInputStream(trusedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 19
Project: jdk8u-jdk   File: SmallPrimeExponentP.java   View Source Code Vote up 4 votes
public static void main(String argv[]) throws Exception {

        String osName = System.getProperty("os.name");
        if (!osName.startsWith("Windows")) {
            System.out.println("Not windows");
            return;
        }
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        CertAndKeyGen ckg = new CertAndKeyGen("RSA", "SHA1withRSA");
        ckg.setRandom(new SecureRandom());
        boolean see63 = false, see65 = false;
        while (!see63 || !see65) {
            ckg.generate(1024);
            RSAPrivateCrtKey k = (RSAPrivateCrtKey) ckg.getPrivateKey();
            int len = k.getPrimeExponentP().toByteArray().length;
            if (len == 63 || len == 65) {
                if (len == 63) {
                    if (see63) continue;
                    else see63 = true;
                }
                if (len == 65) {
                    if (see65) continue;
                    else see65 = true;
                }
                System.err.print(len);
                ks.setKeyEntry("anything", k, null, new X509Certificate[]{
                        ckg.getSelfCertificate(new X500Name("CN=Me"), 1000)
                });
            }
            System.err.print('.');
        }
        ks.store(null, null);
    }
 
Example 20
Project: hadoop   File: KeyStoreTestUtil.java   View Source Code Vote up 3 votes
/**
 * Creates a keystore with a single key and saves it to a file.
 *
 * @param filename String file to save
 * @param password String store password to set on keystore
 * @param keyPassword String key password to set on key
 * @param alias String alias to use for the key
 * @param privateKey Key to save in keystore
 * @param cert Certificate to use as certificate chain associated to key
 * @throws GeneralSecurityException for any error with the security APIs
 * @throws IOException if there is an I/O error saving the file
 */
public static void createKeyStore(String filename,
    String password, String keyPassword, String alias,
    Key privateKey, Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setKeyEntry(alias, privateKey, keyPassword.toCharArray(),
      new Certificate[]{cert});
  saveKeyStore(ks, filename, password);
}