指定Cipher.getInstance()参数?

时间:2012-07-01 05:56:01

标签: java android encryption

我在Android应用程序和独立的Java应用程序中使用以下内容:

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

我在android和我的独立java应用程序上使用不同的加密字符串(两者都使用相同的代码和密钥)。我得到了同样的异常(javax.crypto.BadPaddingException:Blocktype mismatch:0),如下所示:

RSA Encryption: Difference between Java and Android

建议的解决方案是指定填充策略,如:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

但我使用的是“AES”,而不是“RSA”,并且不确定如何结合AES指定填充。在这种情况下,我如何构造传递给Cipher.getInstance()的字符串?我试了一下:

Cipher cipher = Cipher.getInstance("AES/PKCS1Padding");

但是会因为无效而获得例外。

由于

3 个答案:

答案 0 :(得分:6)

另一个“简短回答”,但我相信AES-GCM比CBC模式更安全并且存在了几年但是如果你想在Android中使用你需要包含spongycastle

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

答案 1 :(得分:4)

简短回答:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Long Answer

答案 2 :(得分:1)

我就这样做了:

keyGenerator.init(new
                KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(
                        KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());

cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);