有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从PKCS8编码的数据创建任何私钥实例(RSA、DSA或EC)

我有一个未加密的PKCS8编码文件,它表示一个私钥。它可以是这些私钥类型中的任何一种—RSA、DSA或EC。我在ASN1解码器(https://lapo.it/asn1js/)中查看了这些文件,可以在数据中看到类型(RSA、DSA或EC)

有没有一种方法可以将PKC8私钥数据读入正确的私钥Java对象,而无需在这样的代码中指定密钥类型-

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkcs8key);
KeyFactory factory = KeyFactory.getInstance("RSA"); // Avoid "RSA" here?
PrivateKey privateKey = factory.generatePrivate(spec);

有没有办法避免在KeyFactory.getInstance("RSA")中指定算法?这不应该从PKCS8EncodedKeySpec确定吗,因为它在PKCS8数据中可用

示例未加密的PKCS8数据及其ASN1编码,其中显示密钥类型-

DSA-link

EC-link

RSA-link


共 (1) 个答案

  1. # 1 楼答案

    这可以通过BouncyCastle API实现-

    /** Read a PKCS#8 format private key. */
    private static PrivateKey readPrivateKey(InputStream input)
    throws IOException, GeneralSecurityException {
        try {
            byte[] buffer = new byte[4096];
            int size = input.read(buffer);
            byte[] bytes = Arrays.copyOf(buffer, size);
            /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
            /*
             * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
             * OID and use that to construct a KeyFactory.
             */
            ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
            PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
            String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
            return KeyFactory.getInstance(algOid).generatePrivate(spec);
        } finally {
            input.close();
        }
    }