使用PrivateKey,PublicKey和Certificate对象来设置SSLContext

时间:2016-07-17 17:15:40

标签: java android ssl x509certificate truststore

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

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;
    }

1 个答案:

答案 0 :(得分:1)

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

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应用程序中使用自签名客户端证书(具有匹配的自签名服务器证书)的完整示例,您可以查看我几年前所做的博客文章:{{3 }}