无法在 Android 上使用 AES 密码

Can't get AES cipher working on Android

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

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

错误:"decryption didn't work expected:<[foobargum]> but was:<[�3���jw� �|*�]>"

我认为你有一个 copy-paste 错误:

String decryptedStr = new String(encrypted);

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