[英]Specify Cipher.getInstance() arguments?
我在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),如下所示:
建議的解決方案是指定填充策略,如:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
但我使用的是“AES”,而不是“RSA”,並且不確定如何結合AES指定填充。 在這種情況下,我如何構造傳遞給Cipher.getInstance()的字符串? 我試了一下:
Cipher cipher = Cipher.getInstance("AES/PKCS1Padding");
但得到一個關於無效的例外。
謝謝
另一個“簡短回答”,但我相信AES-GCM比CBC模式更安全並且已經存在了幾年但是如果你想在Android中使用你需要包括spongycastle
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
我就是這樣做的:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.