14

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

这是我的课:

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 的问题,是否有任何解决方法?

谢谢

4

2 回答 2

16

警告此答案SecureRandom用于密钥派生,这与其目的相反。SecureRandom是一个随机数生成器,不能保证在平台之间产生一致的输出(这是导致问题的原因)。密钥派生的正确机制是SecretKeyFactory. 这篇nelenkov 的博客文章对这个问题有很好的描述。此答案为您受向后兼容性要求限制的情况提供了解决方案;但是,您应该尽快迁移到正确的实现。


好的,今天有更多时间做一些研究(并删除我的旧帖子,这实际上是行不通的,抱歉)我得到了一个运行良好的答案,我确实在 Android 2.3.6、2.3.7 上进行了测试(这基本上是一样的),4.0.4 和 4.2 并且它已经工作了。我对这些链接做了一些研究:

Android 4.2 上的加密错误

升级到 1.45 时出现 BouncyCastle AES 错误

http://en.wikipedia.org/wiki/Padding_(密码学)

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

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

于 2012-11-16T02:44:59.273 回答
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”)。

于 2012-11-15T01:01:25.347 回答