javax.crypto.BadPaddingException: error:0407106B:rsa routines:RSA_padding_check_PKCS1_type_2:block t

来源:互联网 发布:网络平台的案例分析 编辑:程序博客网 时间:2024/06/05 04:48

RSA超过长度时报这个错,解决方法是  加密使用117 解密使用128


public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey){int MAX_ENCRYPT_BLOCK = 117;try{Cipher cipher = Cipher.getInstance(CIPHER);// 编码前设定编码方式及密钥cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段加密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();return encryptedData;} catch (Exception e){e.printStackTrace();return null;}}

public static byte[] decryptByPrivateKey(byte[] encryptedData, PrivateKey privateKey){int MAX_ENCRYPT_BLOCK = 128;try{Cipher cipher = Cipher.getInstance(CIPHER);cipher.init(Cipher.DECRYPT_MODE, privateKey);ByteArrayOutputStream out = new ByteArrayOutputStream();int inputLen = encryptedData.length;int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(encryptedData, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptData = out.toByteArray();out.close();return encryptData;} catch (Exception e){e.printStackTrace();return null;}}


阅读全文
0 0
原创粉丝点击