Android / JVM在RSA解密方面的差异

时间:2012-04-24 21:53:07

标签: java android rsa

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

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模拟器中运行时,我得到了:

  

04-24 22:42:21.011:I / System.out(1041):     K_ *ݣ93 | @ 04 Y)Qk的; *阂#��A� �oiu:�����W5@$�w�j�� uSROcx&安培;升   W'/ d8uA {$ 4 U0 {Ԑt!9N    a 'Jdt2 t T D k+k ; GF \ rڼ >] y+ ^w <   “E {8R]ZHyuζ软ށ掱{A#ȟ

我认为我的问题归结为编码,但我花了一整天时间试图弄清楚什么,我真的很难过。

该字符串最初使用以下方式加密:

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;
}

2 个答案:

答案 0 :(得分:1)

由于您正在读取2000字节数组,因此您可能需要输入KeyFactory垃圾,并且您的密钥可能类似于128(1024位)或256(2048位)字节长。此外,您不应该直接使用RSA进行加密:存在安全问题,您可以加密的数据大小受RSA密钥大小的限制。

答案 1 :(得分:1)

感谢GregS在评论中提供的帮助。这是对我有用的解决方案。

private void test() {

            try {
                String stringMessage="GEQRpAPA577ks/QveudNkk7H9DjItKGLDYW6xhH1YJGabCVzrkejkBh6S+APwEXxB84UV/q0sO5rqkgXWONJQ8CoMTfqXtUkAAwkYHSc86eGewkM8WpctA0AyNVFonOxDCXm84Uq8JRMzqskSH5VXHmMxvHIvpFgdhmt9Ir0cKWzoLsuvgfY9hfypfEyBXGZcoptQeKhsZxRGIlxbXhrFl/LqhC+F6vYtZ/j5pv2LUP38wh2rTCKnAQ+xvC+7wn5SVzt/Wbr/q7GjCoJuU9uFHQSS49KQDt+BzJL2XNwAMmdbC+XHYkEBBWxVSS+0hdSQxoaKVZZJk4hTnHwQlBAkw==";
                //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, NoSuchProviderException {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            Cipher cipher = Cipher.getInstance("RSA/None/NoPadding","BC");
            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) 1216];
            is.read(encodedPrivateKey);
            is.close();

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

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

            return privateKey;

        }