我正在尝试解密我在其他地方加密的字符串。这是我的代码:

private void test() {

    try {
        String stringMessage="Sf3O7Lr2+WN5szGyLejL3CjuBRZtQ72+ZBmgVTgWnatQZxUElzaBqFa1p0SVBqe9VWVxCxdEkejMVtDGEr0UJSVSK8EB/fPI6v8JE8dIu0JN0mMs4xlowhITy0tQR+1pcBtDFjzOl33xxQcq5JuPezxRDxFIp+IVkD8FdpqlttEKf2Tvqw9tqsdgiBKb5xDvKrkIDQXdLBh1gbAVZDSJYGHRkcOA8vz2ty/PeooKkfDK6IOn7KBwOBgSRgQr/MLBF3Xk2vRWgVGRh/fRkzu21EWo99Q5moWKxWl3HW/bbgTBQTb097XP3NTID9kSPhCfL0BEfBxonuNse5GBoeRnCw==";
        //Convert String back to Byte[] and decrpt
        byte[] byteMessage = Base64.decodeBase64(stringMessage.getBytes("UTF-8"));
        System.out.println("ENCRYPTED MESSAGE byte Length: "+byteMessage.length);

        String decryptedMsg = decryptString(byteMessage, loadCASPrivateKey());
        System.out.println(decryptedMsg);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

private static String decryptString(byte[] message, Key privateKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] cipherData = cipher.doFinal(message);
    return new String(cipherData, "UTF-8");
}

private PrivateKey loadCASPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    InputStream is = getClass().getResourceAsStream( "/keys/app-private.key" );
    if (is == null) {
        System.out.println("NULL");
    }
    byte[] encodedPrivateKey = new byte[(int) 2000];
    is.read(encodedPrivateKey);
    is.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;

}

这在我的桌面 JVM 下以我希望的方式 100% 工作,但是当我在 Android 模拟器中运行它时,我得到:



我认为我的问题归结为编码,但我已经花了一整天的时间试图找出真正难倒的东西。

该字符串最初是使用以下方法加密的:
private void test() {
    String message="22223334490384903432221";
try {
    //Encrypt message
    byte[] encryptedMsg = Base64.encodeBase64(encryptString(message, temp.loadCASPublicKey()));
} catch (Exception e) {
e.printStackTrace();
        return;
}

}

private static byte[] encryptString(String message, Key publicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] cipherData = cipher.doFinal(message.getBytes("UTF-8"));
    return cipherData;
}

最佳答案

由于您正在读入一个 2000 字节的数组,因此您可能会提供 KeyFactory 垃圾,并且您的 key 可能是 128(1024 位)或 256(2048 位)字节长。此外,您不应该真正直接使用 RSA 进行加密:这存在安全问题,您可以加密的数据大小受 RSA key 大小的限制。

关于java - RSA解密的Android/JVM差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10306560/

10-12 12:56