无法在Android上使用AES密码

时间:2016-01-18 17:21:38

标签: java android encryption aes

我无法获得基本的AES加密/解密往返单元测试以传递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);
     }
 }

错误:"解密没有预期的工作:< [foobargum]>但是:< [�3���jw��| *�]>"

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

我认为你有一个复制粘贴错误:

id