Android 4.2 破坏了我的 AES 加密/解密代码

标签 android aes

这是我第一次在这里寻求帮助,我的部门(政府)已经在市场上发布了一些应用程序(Google Play),直到昨天我拿到果冻 bean 时,加密和描述都运行良好4.2 在我的 Nexus 上。 加密工作正常,它实际上是加密要存储的信息。虽然在解密时,我得到了一个完全像这样的异常:pad block corrupted。 我已经检查了该字符串,它与其他设备上的字符串一致(使用相同的 key 进行测试),这意味着它完全相同。 问题是我们需要保持与以前版本的向后兼容性,这意味着如果我更改代码中的某些内容,它应该能够读取旧的加密信息。它存储在 SQLite 上的加密信息,因为我需要将它编码为 Base64。异常发生在这一行 byte[] decrypted = cipher.doFinal(encrypted);

这是我的类(class):

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class EncodeDecodeAES {

    private final static String HEX = "0123456789ABCDEF";

    public static String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        String fromHex = toHex(result);
        String base64 = new String(Base64.encodeToString(fromHex.getBytes(), 0));
        return base64;
    }


    public static String decrypt(String seed, String encrypted) throws Exception {
        String base64 = new String(Base64.decode(encrypted, 0));
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = toByte(base64);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
    }


    public static byte[] encryptBytes(String seed, byte[] cleartext) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext);
        return result;
    }


    public static byte[] decryptBytes(String seed, byte[] encrypted) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = decrypt(rawKey, encrypted);
        return result;
    }



    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        try {
            kgen.init(256, sr);
        } catch (Exception e) {
    //      Log.w(LOG, "This device doesn't suppor 256bits, trying 192bits.");
            try {
                kgen.init(192, sr);
            } catch (Exception e1) {
    //          Log.w(LOG, "This device doesn't suppor 192bits, trying 128bits.");
                kgen.init(128, sr);
            }
        }
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }


    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }


    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }


    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }


    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }


    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }


    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }


    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

}

我想知道(如果有人帮助我),我对这段代码做错了什么,或者它是否是 Android 4.2 的问题,如果有任何解决方法,是否是 4.2 的问题?

谢谢

最佳答案

警告 此答案使用 SecureRandom 进行 key 派生,这与其目的相反。 SecureRandom 是一个随机数生成器,保证在平台之间产生一致的输出(这是导致问题的原因)。 key 派生的正确机制是 SecretKeyFactory。这个 nelenkov's blog post 在这个问题上有一篇很好的文章。当您受到向后兼容性要求的约束时,此答案为您提供了解决方案;但是,您应该尽快迁移到正确的实现。


好吧,今天有更多时间做一些研究(并删除我的旧帖子,那实际上是行不通的,抱歉)我得到了一个工作正常的答案,我实际上在 Android 2.3.6 上测试过它, 2.3.7(基本相同)、4.0.4 和 4.2 都有效。 我对这些链接做了一些研究:

Encryption error on Android 4.2 ,

BouncyCastle AES error when upgrading to 1.45 ,

http://en.wikipedia.org/wiki/Padding_(cryptography)

然后由于上面这些链接上的内容,我得到了这个解决方案。 这是我的类(class)(现在工作正常):

    package au.gov.dhsJobSeeker.main.readwriteprefssettings.util;

    import java.security.SecureRandom;

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    import android.util.Base64;

    public class EncodeDecodeAES {

private final static String HEX = "0123456789ABCDEF";
private final static int JELLY_BEAN_4_2 = 17;
private final static byte[] key = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };


// static {
// Security.addProvider(new BouncyCastleProvider());
// }

public static String encrypt(String seed, String cleartext) throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext.getBytes());
    String fromHex = toHex(result);
    String base64 = new String(Base64.encodeToString(fromHex.getBytes(), 0));
    return base64;
}


public static String decrypt(String seed, String encrypted) throws Exception {
    byte[] seedByte = seed.getBytes();
    System.arraycopy(seedByte, 0, key, 0, ((seedByte.length < 16) ? seedByte.length : 16));
    String base64 = new String(Base64.decode(encrypted, 0));
    byte[] rawKey = getRawKey(seedByte);
    byte[] enc = toByte(base64);
    byte[] result = decrypt(rawKey, enc);
    return new String(result);
}


public static byte[] encryptBytes(String seed, byte[] cleartext) throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext);
    return result;
}


public static byte[] decryptBytes(String seed, byte[] encrypted) throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = decrypt(rawKey, encrypted);
    return result;
}


private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES"); // , "SC");
    SecureRandom sr = null;
    if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) {
        sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    } else {
        sr = SecureRandom.getInstance("SHA1PRNG");
    }
    sr.setSeed(seed);
    try {
        kgen.init(256, sr);
        // kgen.init(128, sr);
    } catch (Exception e) {
        // Log.w(LOG, "This device doesn't suppor 256bits, trying 192bits.");
        try {
            kgen.init(192, sr);
        } catch (Exception e1) {
            // Log.w(LOG, "This device doesn't suppor 192bits, trying 128bits.");
            kgen.init(128, sr);
        }
    }
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}


private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES"); // /ECB/PKCS7Padding", "SC");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}


private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES"); // /ECB/PKCS7Padding", "SC");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}


public static String toHex(String txt) {
    return toHex(txt.getBytes());
}


public static String fromHex(String hex) {
    return new String(toByte(hex));
}


public static byte[] toByte(String hexString) {
    int len = hexString.length() / 2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
    return result;
}


public static String toHex(byte[] buf) {
    if (buf == null) return "";
    StringBuffer result = new StringBuffer(2 * buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}


private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}

    }

但是 PBrando 的答案(上面,也有效,因为我将其标记为解决方案。),虽然我正在寻找一种方法来保持与现在相似的应用程序文件大小,但我选择使用这种方法.因为我不需要导入外部 Jars。 我确实放了整个类(class),以防万一你们中的任何人遇到同样的问题,并且只想复制并粘贴它。

关于Android 4.2 破坏了我的 AES 加密/解密代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13389870/

相关文章:

嵌入式系统中的密码伪随机数生成器?

java - 错误的 AES 加密

android - 如何在 Picasso (Android) 中加载(内容丰富的) Assets

android - 在 Android 上保存临时捕获的图像

android - 如何从 android studio 安装两个不同版本的应用程序?

java - 如何在 Android 上跟踪 "like"系统?

java - 使用 GSON 反序列化嵌套对象

C# AES 算法 - 我应该在哪里以及如何存储 key 和 IV

c# - 在客户端-服务器环境中使用 AES 加密

java - 如何在 Java 中生成 AES 128 位 key 。我想要这样的东西。 Es8NxqG/f3VMzcd9mrPSQQ==