java - 无法在 Android 上使用 AES 密码

标签 java android encryption aes

我无法在 Android 上通过基本 AES 加密/解密往返单元测试。可能是我正在做的事情,但非常感谢您的指导:

public class EncryptionManager {
    private static final byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    private static final byte[] ivBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

    public byte[] encrypt(byte[] plaintext) throws Exception {
        Cipher cipher = getCipher(true);
        return cipher.doFinal(plaintext);
    }

    public byte[] decrypt(byte [] ciphertext) throws Exception {
        Cipher cipher = getCipher(false);
        return cipher.doFinal(ciphertext);
    }

    private static Cipher getCipher(boolean encrypt) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
        cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE,  
                    secretKeySpec, ivParameterSpec);
        return cipher;
    }
}

失败的单元测试如下所示:

public class EncryptionManagerTest extends TestCase {
     public void testShouldPbeRoundtrip() throws Exception {
         String unencryptedStr = "foobargum";
         byte[] unencrypted = unencryptedStr.getBytes();
         EncryptionManager encryptionManager = new EncryptionManager();
         byte[] encrypted = encryptionManager.encrypt(unencrypted);
         String encryptedStr = new String(encrypted);
         byte[] decrypted = encryptionManager.decrypt(encrypted);
         String decryptedStr = new String(encrypted);

         // assert
         assertFalse("encryption not done",      
                unencryptedStr.equalsIgnoreCase(encryptedStr));
         assertEquals("decryption didn't work", unencryptedStr, 
                decryptedStr);
     }
 }

错误:“解密未按预期进行:<[foobargum]>,而是:<[�3��jw� �|*�]>”

最佳答案

String cryptoStr = new String(encrypted); 是一个错误。加密生成的字节序列不太可能是给定字符集的有效字符串,特别是对于 Android 默认的 UTF-8 字符集。在将字节数组加密转换为 String 对象时,无效字节序列将以不可恢复的方式默默地替换为有效字符。

关于java - 无法在 Android 上使用 AES 密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860527/

相关文章:

android lollipop 和 socket.io 不能一起工作

python - C++ 中的 Crypto++ :Encrypt in Python , 解密

c++ - 使用 Windows Crypto API 和 C++ 的 PKCS #7 encryptedDigest 解密和验证

java - 在 Swing 事件中启动线程

java - 从 java beans 选择下拉菜单填充表单字段

java - 动态绘制圆弧

android - 如何编程图形界面是盲的?

java - SSLSocket 使用的密码套件

java - 将 Java 运行时的方法标记为已弃用

java - 跟踪运行时拖动事件的进度。 JavaFX