java.security.InvalidKeyException:从.CRT文件

时间:2019-11-25 12:25:02

标签: java encryption aes rsa

我正在尝试从.crt文件加载密钥。下面是我的代码

Path path = Paths.get(filePath);
byte[] bytes;

try {
    bytes = Files.readAllBytes(path);

    /* Generate public key. */
        X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pubKey = kf.generatePublic(ks);

@ kf.generatePublic(ks)引发异常。

异常:java.security.InvalidKeyException:无效的密钥格式

下面是.crt文件的内容

-----BEGIN CERTIFICATE-----
MIIBpzCCAVECBEqbmP4wDQYJKoZIhvcNAQEEBQAwXTELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRF
//trimmed key
-----END CERTIFICATE-----

我找不到我的代码有什么问题。该密钥用于RSA公共加密C代码中的密钥(PBKDF2密钥)。

//openssl
RSA_public_encrypt(msgLen, msg, encryptedMsg, rsaPubKey, RSA_PKCS1_PADDING)

我正在尝试用Java实现它。我有什么想念的吗?请指导

更新1:

使用以下代码克服异常:

        InputStream inStream = null;
    try {
        inStream = RefundUtil.class.getClassLoader().getResourceAsStream("refund.crt");

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        PublicKey pubKey = cert.getPublicKey();

        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);

        byte[] cipherText = encryptCipher.doFinal(sessionKey);

        inStream.close();
        return Base64.getEncoder().encodeToString(cipherText);

    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }

0 个答案:

没有答案