使用 PrivateKey、PublicKey 和 Certificate 对象设置 SSLContext

Using a PrivateKey, PublicKey and Certificate objects to setup an SSLContext

我创建了有效的 PrivateKey、PublicKey 和 Certificate 对象,我需要使用它们来创建用于 HttpsURLConnection 的 SSLContext。我需要这样做的原因是因为要求将私钥、public 密钥和证书作为文本存储在字符串变量中。我已经包含了我正在使用的代码的一小段摘录。

PrivateKey privKey = loadPrivateKey("REDACTED");
PublicKey publicKey = loadPublicKey("REDACTED");
X509Certificate cert = convertToX509Certificate("REDACTED");

sslContext = ???

     URL obj = new URL("https://www.example.com/WS");
     HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();


     connection.setSSLSocketFactory(sslContext.getSocketFactory());


 public static PublicKey loadPublicKey(String stored) throws GeneralSecurityException {
        byte[] data = Base64.decode(stored, 0).toString().getBytes();;
        X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
        KeyFactory fact = KeyFactory.getInstance("DSA");
        return fact.generatePublic(spec);
    }


    public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
        byte[] clear = Base64.decode(key64, 0).toString().getBytes();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
        KeyFactory fact = KeyFactory.getInstance("DSA");
        PrivateKey priv = fact.generatePrivate(keySpec);
        Arrays.fill(clear, (byte) 0);
        return priv;
    }

    public X509Certificate convertToX509Certificate(String pem) throws CertificateException, IOException {
        X509Certificate cert = null;
        StringReader reader = new StringReader(pem);
        PEMReader pr = new PEMReader(reader);
        cert = (X509Certificate)pr.readObject();
        return cert;
    }

最简单的方法是仍然使用密钥库,但不是从磁盘读取一个,而是动态创建一个:

ByteArrayInputStream is = new FileInputStream(certificateString);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(is, clientCertPassword.toCharArray());

KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, clientCertPassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, null, null);

有关在 Android 应用程序(具有匹配的自签名服务器证书)中使用自签名客户端证书的完整示例,您可以查看博客 post我几年前做过:http://chariotsolutions.com/blog/post/https-with-client-certificates-on