1

我有一个类似于这个问题的加密/解密代码。不同之处在于我只是解密了一个我之前加密的密钥,并将其作为字符串存储在我的常量类中。

它工作正常,但今天我刚刚发现代码因此错误而死:

javax.crypto.BadPaddingException: pad block corrupted
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:709)
at javax.crypto.Cipher.doFinal(Cipher.java:1111)

此错误仅在使用 Galaxy Nexus Android 4.2.2 时发生。我已经在其他设备上测试了我的代码,包括平板电脑和从 2.3 到 4.0.3 的其他 Android 版本。我没有在其他 4.2.2 设备上测试过这个,因为我只得到了这台具有 Android 4.2.2 的设备。

有谁知道如何解决这个问题?

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;
}  

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(KEY_SIZE, sr);
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}  

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), END_POSITION).byteValue();
    }

    return result;
}

public static void generateKey() {
    try {
        byte[] seed = SEED_STRING.getBytes("UTF-8");
        byte[] rawKey = getRawKey(seed);           
        byte[] toDecrypt = toByte(Constants.ENCRYPTED);

        mKey = new String(decrypt(rawKey, toDecrypt), "UTF-8");      

    } catch (Exception e) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "encryption: ", e);
        }
    }   
}

编辑:我刚刚发现,当我在问题设备上执行密钥加密时,每次启动应用程序时都会生成不同的密钥。与我之前测试的其他设备不同,每次只生成相同的密钥。

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));
}

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());
    return toHex(result);
}    

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;
}

代码来源:http ://www.androidsnippets.com/encryptdecrypt-strings

4

0 回答 0