使用AES进行Android加密和解密不会返回没有特殊字符的预期结果

时间:2015-04-13 19:55:27

标签: android encryption encoding cryptography aes

我试图在android中加密和解密一个abritrary字符串,我想将其发送到网络服务器。

我的Teststring如下:

  

Wert wert [aa] wert

这是我的加密和解密功能:

public static String encrypt(String value, String key) {
    SecretKey secretKey;
    String ex;
    try {
        byte[] encodedKey = Base64.decode(key, Base64.DEFAULT);

        secretKey = new SecretKeySpec(encodedKey,
                "AES");
        Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        encrypt.init(Cipher.ENCRYPT_MODE, secretKey,ivSpec);
        byte[] valueDecode = value.getBytes("UTF-16");
        byte[] valueInput = Base64.decode(value, Base64.DEFAULT);
        byte[] valueOutput = encrypt.doFinal(valueInput);


        return 
                 Base64.encodeToString( valueOutput, Base64.DEFAULT );
    } catch (Exception e) {
        e.printStackTrace();
        ex = e.toString();
    }
//  Log.d(TAG, ex);
    return null;
}

private static String decrypt(String value, String key) {
    SecretKey secretKey;
    String ex;

    byte[] encodedKey;
    try {
        encodedKey = Base64.decode(key, Base64.DEFAULT);

        secretKey = new SecretKeySpec(encodedKey, 
                "AES");
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decrypt.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] valueInput = Base64.decode(value,Base64.DEFAULT);
        byte[] valueOutput = decrypt.doFinal(valueInput);

        return Base64.encodeToString(valueOutput, Base64.DEFAULT);
    } catch ( Exception e) {
        e.printStackTrace();
    }
    return null;
}

当我对字符串执行加密和解密时,我会收到以下结果:

  

wertwertaawerg ==

缺少所有空格和[]字符,并且接收字符串的结尾也不正确。

为什么它不能正常工作的任何建议?

我正在使用Android 4.0.3版。

2 个答案:

答案 0 :(得分:2)

请不要尝试自己构建一个(微小的)加密系统。有很多事情可能会出错。有关详细信息,请参阅此博客文章:http://tozny.com/blog/encrypting-strings-in-android-lets-make-better-mistakes/

读完之后,请转到Github并使用以下代码:https://github.com/tozny/java-aes-crypto

更新:根据博客文章,典型的错误是:

  • 密钥生成错误
  • 过时密钥生成(旧版Android上的SecureRandom错误)
  • 使用ECB
  • Bad Padding
  • 没有诚信
  • 不正确的IV
  • 弱算法

至少以粗体标出的问题出现在OP的代码中。

答案 1 :(得分:0)

这是编码问题。你用明文做的第一件事就是你从Base 64解码它来得到一个字节数组。空格或[]等字符不属于默认的Base 64字母表,在进一步处理之前会自动删除。

通常您会使用以下内容从明文byte[]获取String

// during encryption
byte[] valueDecode = value.getBytes("UTF-8");
byte[] valueOutput = encrypt.doFinal(valueDecode);

// during decryption
return new String(valueOutput, "UTF-8");

如果密文可能被操纵(恶意或非恶意),您应该对其进行完整性检查。在加密 - 然后 - MAC方案中使用HMAC很难做到这一点,因此您应该使用经过验证的操作模式,如GCM或EAX。