1

我正在使用以下代码解密 RSA 加密的 base64 编码字符串。但是,解密后的字符串在实际字符串前附加了一些无效字符。我一直在试图找出可能导致这些垃圾数据出现的原因,但我在这方面的有限专业知识限制了我。

使用终端中的 openssl 使用以下命令对数据进行加密。

使用的 OpenSSL 命令:

openssl genrsa -out priv_key.pem 2048  
openssl rsa -pubout -in priv_key.pem -out pub_key.pem 
openssl rsautl -encrypt -in userdata.json -out user_encrypted_with_pub_key -inkey pub_key.pem –pubin

我以编程方式做的唯一一件事就是解码使用上述命令加密的数据。我正在使用 bouncyCastle 最新版本。

代码:

decipherString(priv, decodeBase64(base64StringBuilder.toString()).toByteArray());

private static void decipherString(PrivateKey privateKey, byte[] encodedStringData) {
        byte[] dectyptedText = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            dectyptedText = cipher.doFinal(encodedStringData);
            Timber.w("Deciphered text is: %s", new String(dectyptedText, "UTF-8"));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

输出:

T1.O�Y1�{�l�M�X�`��������/ 9���Z��yt�戋��Eo��Z3���~7A���rtj)j�� x ')��e�/�$iJ���;����1&��I�U�#�$����}�C�����4P��E�-ρ��� ��?�wQ���Z�n�b��Py�%�>�I�X����TqDv�_��?��{ “ssid”:“PT”,“密码”: “XYZ123”,“安全”:“WPA2”}

4

1 回答 1

3

永远不要这样做:

Cipher cipher = Cipher.getInstance("RSA");

始终指定完整的转换字符串:“算法/模式/填充”。不这样做将导致代码不可移植,因为默认值是特定于提供者的。在您的情况下,默认值相当于

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");

但这不是你在这里需要的。openssl rsautl默认情况下使用 PKCS#1 v1.5 加密填充,所以你需要的是

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
于 2018-02-18T01:04:24.477 回答