Java 指定Cipher.getInstance()参数?

Java 指定Cipher.getInstance()参数?,java,android,encryption,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

我在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不匹配:0):

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

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

Cipher cipher = Cipher.getInstance("AES/PKCS1Padding");
但是得到一个关于无效的例外

谢谢

简短回答:

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

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

我就是这样做的:

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

试试这个Cipher=Cipher.getInstance(“AES/CBC/ISO10126Padding”,“JsafeJCE”);Blast不起作用:java.security.NoSuchProviderException:没有这样的提供程序:JsafeJCEIt听起来像是你在试图编写加密代码,把随机的代码块扔到墙上,希望有东西粘在墙上。通过使用低级API,您可以理解诸如对称和非对称加密之间的差异、分组密码模式之间的差异以及填充方案、IVs等。你似乎一点都不懂。也许你应该从这里开始。在我的例子中,我调用了cipher.update,而它本应该是cipher.doFinal.java.security.nosuchalgorithException:AES/GCM/NoPadding SecretKeyFactory not available我收到了这个错误
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);