将私钥导入Java时出错

时间:2015-06-24 15:35:58

标签: java ssl openssl certificate java-security

更新 This suggestion解决了我的问题

我使用OpenSSL创建了一个私钥,并获得了相应的公共证书。我使用以下命令创建了私钥:

openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key

私钥和公共证书都是Base64编码的。

PEM编码私钥的格式如下:

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----

公共证书的格式为:

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

现在,我将它们导入我的Java应用程序以创建SSLContext。我想避免两件事:

  • 使用Java密钥库(或.jks)
  • 使用BouncyCastle

到目前为止,我有以下Java代码:

第1步:阅读私钥和公共证书:

byte[] certBytes = convertFileToBytes(new File("public.cer"));
byte[] keyBytes = convertFileToBytes(new File("private.key"));

步骤2:从二进制编码字节生成公共证书:

private static X509Certificate generatePublicCert(byte[] certBytes) {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}

步骤3:从二进制编码字节生成私钥:

private static PrivateKey generatePrivateKey(byte[] keyBytes) {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(spec);
}

第4步:生成SSLContext:

private static SSLContext getContext() {
    X509Certificate cert = generatePublicCert(certBytes);
    PrivateKey key = generatePrivateKey(keyBytes);

    KeyStore keyStore = KeyStore.getInstance("JKS"); // Do I still need this?
    keyStore.load(null);
    keyStore.setCertificateEntry("cert-alias", cert);
    keyStore.setKeyEntry("key-alias", key, "MyPassphrase".toCharArray(), new Certificate[] {cert});

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(keyStore, "MyPassphrase".toCharArray());

    KeyManager[] km = kmf.getKeyManagers();
    context.init(km, null, null);
    return context;
 }

但是,我在第3步收到错误:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(Unknown Source)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您确定您的密钥格式正确吗?

尝试从密钥和证书文件中删除以----开头的行。