在Android上使用OpenSSL enc子命令加密的解密文件

时间:2016-05-27 06:30:21

标签: android encryption openssl cryptography aes

我使用OpenSSL命令在服务器中有一个加密文件:

openssl enc -aes-256-ecb -salt -in ori.pdf -out encrypted.pdf -pass pass:testpassword -p

以下是加密完成后显示的密钥和盐:

salt=BE1EFCBAE984CB24
key=50B62ECEF1B777353372A44CDDC463987815F783E39D68B8EE6A0AB74A79C7FA

我试图用以下解密来解密:

String key  = "50B62ECEF1B777353372A44CDDC463987815F783E39D68B8EE6A0AB74A79C7FA";
byte[] keyBytes = key.getBytes("UTF-8");
SecretKey keySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
buffer = cipher.doFinal(buffer);

如何在Android中解密加密文件?

1 个答案:

答案 0 :(得分:0)

我对原来的答案进行了嘲讽。我误读了字符串为“base 64”。事实上,它只是“十六进制编码”。

更改此声明:

byte[] keyBytes = key.getBytes("UTF-8");

要成为这样:

byte [] keyBytes = hexStringToByteArray(key);

其中hexStringToByteArray是函数lifted from this answer here.

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}