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

时间:2012-11-15 00:39:21

标签: android aes

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

这是我的班级:

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的问题?

谢谢

2 个答案:

答案 0 :(得分:16)

警告此答案使用SecureRandom进行密钥派生,这与其目的相反。 SecureRandom是一个随机数生成器,并且保证在平台之间产生一致的输出(这是导致问题出现问题的原因)。密钥派生的正确机制是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)

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

    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。 我确实把整个课程都放在了以防你们中的任何人遇到同样的问题,并且只想复制并粘贴它。

答案 1 :(得分:1)

您可以尝试使用SpongyCastle库。 这是在Android上编译的BouncyCastle补丁。

由于它与BouncyCastle兼容(只有包名和服务提供商不同,“SC”而不是“BC”),Android使用BouncyCastle的子集,在代码中集成SpongyCastle应该是一项微不足道的任务。

您可以在此处找到SpongyCastle:http://rtyley.github.com/spongycastle/

按照其网站上的说明注意注册SpongyCastle:

static {
    Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
}

获取加密对象的实例时,还要指定提供者(“SC”)。