解决超长内容加密失败解决方案
作者:互联网
来自:https://www.itread01.com/p/1452444.html
java rsa 解密 報:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytesat com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at com.asymmetric.rsa.TestRSA.testDecrypt(TestRSA.java:82)
at com.asymmetric.rsa.TestRSA.main(TestRSA.java:33)
異常解釋
加密塊大小錯誤,rsa 加密 塊大小為117 ,解密塊大小為128 ,和公鑰加密或者私鑰加密無關,
測試程式碼如下:
package com.asymmetric.rsa; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; public class TestRSA { public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQgEoj3z9JrdPNI23DbMQkl3gkGuDke7iBr5yrYyqolkTyxuBLWFwHNuGv4VKOj9fXg61QxpaJ/fxDBvMvmkBSRowHBloGFceVTx8wV/8u0DcjvTCu0IZ1zp6wjG6xBn5j66Sg/q+9hvaY2p7fkKmsvcW6VoNPgQHU1Cf01DLZmQIDAQAB+oXcINOiE3AsuZ4VJmwNZg9Y/7fY+OFRS2JAh5YMsrv2qyoGP+Z9ksre26NYR+Lt91B2lhdwJHLpQpziaANZm/ONb31fj/lwIDAQAB"; public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANCASiPfP0mt080jbcNsxCSXeCQa4OR7uIGvnKtjKqiWRPLG4EtYXAc24a/hUo6P19eDrVDGlon9/EMG8y+aQFJGjAcGWgYVx5VPHzBX/y7QNyO9MK7QhnXOnrCMbrEGfmPrpKD+r72G9pjant+Qqay9xbpWg0+BAdTUJ/TUMtmZAgMBAAECgYBSozY/Z4FW+31h5fPgK+DFu/8TGFAgXuTvCaJnz2Md9IkZTDejxT6cYWUr53toI5zhvz/XLw6FXNQ54KxMJq/s9PiZYUgq/PMrnyU4gBSTm5BmiWjdaGicVEZ1lofHjpkAchPNW/CzwxD8AeKI7QaObE+EkWbLAi6sa+nRdHKgrQJBAOwYLD2DncU15XCKS0RNzTrNohdBQcisOPHdtQO0CGZlxx3xjuU4WL6/EpdmbjTeYbOSDKCmY5vyVbYZdOWfEs8CQQDiFIwWpvW2WLxLVw3i2P55WmMMXuecwEzg++ae3Ht7nW0zNcWSsyvHh40sM8XqEzmWOzMY6JOePbkuVfWTc4cXAkBRzf5mQhiEoKwjVofF3v9hhKbJT/8vPR1uENgLtHHEqTdZFL3ihqeZUDNs6jz9bKCFy/E8KOsSueEg+6kZdwjZAkEAj2RW4fstd2VasDJb5ViaNqAEmJENOBej60L6KCJR07qqy0M8t+oaR2iLOtDvo6Jj8QxFQXQqRMCDVodAxjANKwJAL3KuaqA6kdy9RxdV3uP8nRXLY7C/1ZIK6U0pyZqKXEwpD+7Ar3hwwhPz9TeuoqjB/cCknZjw70BQFQ0/VUHW2g=="; private static String algorithm = "RSA"; //$NON-NLS-1$ private static String data = "這是一個test"; //$NON-NLS-1$ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { byte[] test = testEncrypt(privateKey,data); String testDecrypt = testDecrypt(publicKey, test); System.out.println(testDecrypt); } /** * 加密 * @param key * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException */ public static byte[] testEncrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException{ byte[] decode = Base64.getDecoder().decode(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); KeyFactory kf = KeyFactory.getInstance(algorithm); PrivateKey generatePrivate = kf.generatePrivate(pkcs8EncodedKeySpec); Cipher ci = Cipher.getInstance(algorithm); ci.init(1, generatePrivate); byte[] doFinal = ci.doFinal(data.getBytes()); // return Base64.getEncoder().encodeToString(doFinal); return doFinal; } /** * 解密 * @param key * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws BadPaddingException * @throws IllegalBlockSizeException */ public static String testDecrypt(String key,byte[] data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException{ byte[] decode = Base64.getDecoder().decode(key); // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); //java底層 RSA公鑰只支援X509EncodedKeySpec這種格式 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode); KeyFactory kf = KeyFactory.getInstance(algorithm); PublicKey generatePublic = kf.generatePublic(x509EncodedKeySpec); Cipher ci = Cipher.getInstance(algorithm); ci.init(1,generatePublic); // byte[] doFinal = ci.doFinal(Base64.getDecoder().decode(data)); byte[] doFinal = ci.doFinal(Base64.getDecoder().decode(data)); return Base64.getEncoder().encodeToString(doFinal); } }
問題點:
後來發現是解密的時候.cipher.init(1,generatePublic) cipher 模式填錯了,1就代表是加密模式,2是解密模式
將解密方法裡的cipher初始化改為 cipher.init(2,generatePublic) 即可
後來看到這個異常用大量資料去測試,也報這個異常,說明rsa加密必須對加密資料進行分組加密
查api指出:IllegalBlockSizeException
- 如果此 Cipher 為 Cipher 塊,未請求任何填充(只針對加密模式),並且由此 Cipher 處理的資料總輸入長度不是塊大小的倍數;如果此加密演算法無法處理所提供的輸入資料。
修正後的程式碼:
package com.asymmetric.rsa; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; public class TestRSA { public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQgEoj3z9JrdPNI23DbMQkl3gkGuDke7iBr5yrYyqolkTyxuBLWFwHNuGv4VKOj9fXg61QxpaJ/fxDBvMvmkBSRowHBloGFceVTx8wV/8u0DcjvTCu0IZ1zp6wjG6xBn5j66Sg/q+9hvaY2p7fkKmsvcW6VoNPgQHU1Cf01DLZmQIDAQAB+oXcINOiE3AsuZ4VJmwNZg9Y/7fY+OFRS2JAh5YMsrv2qyoGP+Z9ksre26NYR+Lt91B2lhdwJHLpQpziaANZm/ONb31fj/lwIDAQAB"; public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANCASiPfP0mt080jbcNsxCSXeCQa4OR7uIGvnKtjKqiWRPLG4EtYXAc24a/hUo6P19eDrVDGlon9/EMG8y+aQFJGjAcGWgYVx5VPHzBX/y7QNyO9MK7QhnXOnrCMbrEGfmPrpKD+r72G9pjant+Qqay9xbpWg0+BAdTUJ/TUMtmZAgMBAAECgYBSozY/Z4FW+31h5fPgK+DFu/8TGFAgXuTvCaJnz2Md9IkZTDejxT6cYWUr53toI5zhvz/XLw6FXNQ54KxMJq/s9PiZYUgq/PMrnyU4gBSTm5BmiWjdaGicVEZ1lofHjpkAchPNW/CzwxD8AeKI7QaObE+EkWbLAi6sa+nRdHKgrQJBAOwYLD2DncU15XCKS0RNzTrNohdBQcisOPHdtQO0CGZlxx3xjuU4WL6/EpdmbjTeYbOSDKCmY5vyVbYZdOWfEs8CQQDiFIwWpvW2WLxLVw3i2P55WmMMXuecwEzg++ae3Ht7nW0zNcWSsyvHh40sM8XqEzmWOzMY6JOePbkuVfWTc4cXAkBRzf5mQhiEoKwjVofF3v9hhKbJT/8vPR1uENgLtHHEqTdZFL3ihqeZUDNs6jz9bKCFy/E8KOsSueEg+6kZdwjZAkEAj2RW4fstd2VasDJb5ViaNqAEmJENOBej60L6KCJR07qqy0M8t+oaR2iLOtDvo6Jj8QxFQXQqRMCDVodAxjANKwJAL3KuaqA6kdy9RxdV3uP8nRXLY7C/1ZIK6U0pyZqKXEwpD+7Ar3hwwhPz9TeuoqjB/cCknZjw70BQFQ0/VUHW2g=="; private static String algorithm = "RSA"; //$NON-NLS-1$ private static final int MAX_ENCRYPT_BLOCK = 117; private static final int MAX_DECRYPT_BLOCK = 128; private static String data = "test jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihgtest jiojiogeiojigouihg"; //$NON-NLS-1$ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException { String test = testEncrypt(privateKey,data); String testDecrypt = testDecrypt(publicKey, test); System.out.println(testDecrypt); } /** * 加密 * @param key * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws IOException */ public static String testEncrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException{ byte[] decode = Base64.getDecoder().decode(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); KeyFactory kf = KeyFactory.getInstance(algorithm); PrivateKey generatePrivate = kf.generatePrivate(pkcs8EncodedKeySpec); Cipher ci = Cipher.getInstance(algorithm); ci.init(Cipher.ENCRYPT_MODE, generatePrivate); byte[] bytes = data.getBytes(); int inputLen = bytes.length; int offLen = 0;//偏移量 int i = 0; ByteArrayOutputStream bops = new ByteArrayOutputStream(); while(inputLen - offLen > 0){ byte [] cache; if(inputLen - offLen > 117){ cache = ci.doFinal(bytes, offLen,117); }else{ cache = ci.doFinal(bytes, offLen,inputLen - offLen); } bops.write(cache); i++; offLen = 117 * i; } bops.close(); byte[] encryptedData = bops.toByteArray(); String encodeToString = Base64.getEncoder().encodeToString(encryptedData); return encodeToString; } /** * 解密 * @param key * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IOException */ public static String testDecrypt(String key,String data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, IOException{ byte[] decode = Base64.getDecoder().decode(key); // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); //java底層 RSA公鑰只支援X509EncodedKeySpec這種格式 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode); KeyFactory kf = KeyFactory.getInstance(algorithm); PublicKey generatePublic = kf.generatePublic(x509EncodedKeySpec); Cipher ci = Cipher.getInstance(algorithm); ci.init(Cipher.DECRYPT_MODE,generatePublic); byte[] bytes = Base64.getDecoder().decode(data); int inputLen = bytes.length; int offLen = 0; int i = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while(inputLen - offLen > 0){ byte[] cache; if(inputLen - offLen > 128){ cache = ci.doFinal(bytes,offLen,128); }else{ cache = ci.doFinal(bytes,offLen,inputLen - offLen); } byteArrayOutputStream.write(cache); i++; offLen = 128 * i; } byteArrayOutputStream.close(); byte[] byteArray = byteArrayOutputStream.toByteArray(); return new String(byteArray); } }
更多相關知識…
java rsa 解密 報:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
Exception in thread "main" javax.crypto.IllegalBlock...
Data must not be longer than 117 bytes異常 RSA加密解密內容超長報錯
在使用 RSA加密解密內容時會出現這樣的異常 :Data must not be longer than 117 b...
java rsa 解密報:javax.crypto.BadPaddingException: Decryption error
Exception in thread "main" javax.crypto.BadPaddingEx...
java AES 加密,報javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decryp
java 使用AES解密報這個異常,字面理解很容易,就是解密的字串的陣列必須是16的倍數 javax.crypto.I...
java rsa加密報java.security.InvalidKeyException: IOException : algid parse error, not a sequence
java rsa 加密報這個異常,應該祕鑰的問題,: rsa 祕鑰不是pks8 格式 Caused by: java....
RSA 解密的時候報錯 而且有亂碼:java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block
報錯: 03-22 10:21:20.805 507-507/? E/AndroidRuntime: FATAL ...
塊加密演算法-3des 長度不對時的處理方法,解決 javax.crypto.IllegalBlockSizeException:
引用http://www.cnblogs.com/DrWang/archive/2011/03/30/2000124.h...
java加密演算法分享(rsa解密、對稱加密、md5加密)
import java.io.UnsupportedEncodingException; import java....
[JAVA加解密]RSA演算法、ElGamal演算法
一、RSA演算法: 1、簡介:RSA公鑰加密演算法是1977年由羅納德·李維斯特(Ron Rivest)、阿迪·薩莫爾...
C# 與 Java Rsa加密與解密互通
Rsa 加密標準的制定已經過去了十多年了. 這兩天在看rsa 加密的文章,基本上都是在說 .net 與 java 之間的...
java RSA 加密解密演算法 入門
java RSA 加密解密演算法 入門 一、入門閒話 最近在學javase,想拿個小題目練習。...
java RSA 加密解密演算法 入門 .
一、入門閒話 最近在學javase,想拿個小題目練習。拿到一個關於socket介面實現基於TCP協議的通訊...
java RSA 加密解密
RSA工具類.java package com.zjp.common.utils;import java.io.Byte...
java加解密工具類,支援RSA,AES
import java.security.Key; import java.security.KeyPair; im...
UDP協議實現對等通訊Java+RSA加密解密傳送資訊實現
UDP協議實現對等通訊Java+RSA加密解密傳送資訊實現 RSA演算法部分使用了:Java實現RSA加密解密演算法 ...
标签:加密,String,java,解决方案,RSA,超长,import,throws 来源: https://www.cnblogs.com/duende99/p/11910227.html