Android中的AES解密算法

时间:2013-08-03 08:59:48

标签: java android encryption

public static String Encrypt(String text){
    try {           
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes= new byte[16];
        byte[] b= KEY.getBytes("UTF-8");
        int len= b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);

        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
        String result = Base64.encodeToString(results, 0);
        //result = URLEncoder.encode(result.trim(),"UTF-8");
        return result;

    } catch (Exception e) {
        // TODO: handle exception
        return null;
    }
}   

public static String Decrypt(String text){
    try {           
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes= new byte[16];
        byte[] b= KEY.getBytes("UTF-8");
        int len= b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
        String result = Base64.encodeToString(results, 0);
        //result = URLEncoder.encode(result.trim(),"UTF-8");
        return result;

    } catch (Exception e) {
        // TODO: handle exception
        Log.d("decryption", e.getMessage());
        return null;
    }
}   

这是用于加密和解密的代码,我从其他一些问题获得加密算法,它对我来说工作正常,但我也需要解密,我试图像加密一样模仿它但它不起作用。例外情况说最后一块不完整。

1 个答案:

答案 0 :(得分:6)

问题是您没有以相反的顺序执行反向序列。你最终得到了base64编码的数据 - 所以你需要做的第一件事是使用base64-decode来获取二进制加密数据。然后解密,然后使用UTF-8将其转换回字符串。

public static String decrypt(String text){
    try {           
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes= new byte[16];
        byte[] b= KEY.getBytes("UTF-8");
        int len= b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
        byte[] results = cipher.doFinal(Base64.decode(text, 0));
        return new String(results, "UTF-8");
    } catch (Exception e) {
        // TODO: handle exception
        Log.d("decryption", e.getMessage());
        return null;
    }
}   

当你从某个地方获取代码时,重要的是你要真正理解它在做什么 - 特别是要理解每个阶段的数据是什么样的:

  • 以纯文本开头
  • UTF-8将其编码为字节数组
  • 加密到另一个字节数组(不是 UTF-8编码的文本)
  • Base64将加密的二进制数据编码为字符串

每当你进行这样的转换时,当你想要反转它时,你也需要颠倒步骤的顺序,以便回到原始数据。