RSA解密出现 javax.crypto.BadPaddingException Create Breakpoint: Decryption error 解决过程

问题业务描述:
数据上传第三方接口需要对数据进行RSA加密验签,加密的数据本地demo是可以通过的线上加密数据对方无法解密。
报错内容:

javax.crypto.BadPaddingException: Decryption error
	at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:379)
	at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
	at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:358)
	at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
	at javax.crypto.Cipher.doFinal(Cipher.java:2226)
	at com.bangdao.park.openapi.common.tools.RSAUtil.decryptByPublicKey(RSAUtil.java:218)
	at com.bangdao.park.openapi.common.tools.RSAUtil.main(RSAUtil.java:266)

分析问题:
无法解密主要问题可能是依赖包不一致,或者与对方环境不一致,根据报错内容可以可以看出主要是在: com.sun.crypto.provider.RSACipher.engineDoFinal 也就是
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()),
**解决过程:**这时打印 logger.info(“provider: {}” , cipher.getProvider().getClass().getName());对应的类
打印结果是:
线上:provider: org.bouncycastle.jce.provider.BouncyCastleProvider
本地 : provider: com.sun.crypto.provider.SunJCE
我们不难发现 本地环境和对方环境一致,与线上环境不一致。导致问题根本原因是java环境不一样,这在对接第三方接口是很容易发生的事情。这时我们执行 java -version发现
线上环境:
在这里插入图片描述
本地或者对方环境:
RSA解密出现 javax.crypto.BadPaddingException Create Breakpoint: Decryption error 解决过程_第1张图片

以上分析解决方案:提供者
在得到cipher时指定
源代码:
RSA解密出现 javax.crypto.BadPaddingException Create Breakpoint: Decryption error 解决过程_第2张图片
修改后代码:

RSA解密出现 javax.crypto.BadPaddingException Create Breakpoint: Decryption error 解决过程_第3张图片
总结: 对接外部接口时涉及加密时要保证依赖包一致性,环境一致性。
附万能的RSA加密Utils

`package com.bangdao.park.openapi.common.tools;

import com.alibaba.fastjson.JSONObject;
import com.sun.crypto.provider.SunJCE;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

import static java.util.regex.Pattern.compile;


/***
 * RSA公钥/私钥/签名工具包
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 * @author trace * @Date 2022-5-17 * @version 1.0 */
public class RSAUtil { private static Logger logger = LoggerFactory.getLogger(RSAUtil.class); /** *//** * 加密算法RSA */ public static final String KEY_ALGORITHM = "RSA"; /** *//** * 签名算法 */ public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /** *//** * RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117; private static final int MAX_DECRYPT_BLOCK = 128; private static final String PUBLIC_KEY ="publicKey"; private static final String PRIVATE_KEY ="privateKey"; /** *//** * <p> * 用私钥对信息生成数字签名 * </p> * * @param content 已加密数据 * @param privateKey 私钥(BASE64编码) * * @return * @throws Exception */ public static String sign(String content, String privateKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(privateKey); byte[] data = content.getBytes(Charset.forName("UTF-8")); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); RSAPrivateKey privateK = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64.encodeBase64String(signature.sign()); } //ASN1Primitive asn1Prime = new ASN1InputStream(decoded).readObject(); // // org.bouncycastle.asn1.pkcs.RSAPublicKey rsaPub = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(asn1Prime); // /** *//** * <p> * 私钥加密 * </p> * * @param privateKey 源数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static String encryptByPrivateKey(String content, String privateKey) throws Exception { compile("com.sun.crypto.provider.SunJCE"); byte[] keyBytes = Base64.decodeBase64(privateKey); byte[] data = content.getBytes(Charset.forName("UTF-8")); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); RSAPrivateKey privateK = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec); SunJCE provider=new com.sun.crypto.provider.SunJCE(); Security.addProvider(provider); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm(),provider); cipher.init(Cipher.ENCRYPT_MODE, privateK); logger.info("provider: {}" , cipher.getProvider().getClass().getName()); 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 Base64.encodeBase64String(encryptedData); } public static String encryptByPublicKey(String content, String publicKey) throws Exception { compile("com.sun.crypto.provider.SunJCE"); byte[] data = content.getBytes(Charset.forName("UTF-8")); byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 SunJCE provider=new com.sun.crypto.provider.SunJCE(); Security.addProvider(provider); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm(),provider); cipher.init(Cipher.ENCRYPT_MODE, publicK); 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 Base64.encodeBase64String(encryptedData); } public static String decryptByPrivateKey(String dataStr, String privateKeyStr) throws Exception { compile("com.sun.crypto.provider.SunJCE"); byte[] encryptedData = Base64.decodeBase64(dataStr.getBytes("UTF-8")); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyStr)); KeyFactory factory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec); //RSA加密 SunJCE provider=new com.sun.crypto.provider.SunJCE(); Security.addProvider(provider); Cipher cipher = Cipher.getInstance("RSA",provider); cipher.init(Cipher.DECRYPT_MODE, privateKey); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); String outStr = new String(decryptedData,"UTF-8"); return outStr; } public static String decryptByPublicKey(String dataStr, String publicKey) throws Exception { compile("com.sun.crypto.provider.SunJCE"); byte[] data = Base64.decodeBase64(dataStr); // 得到私钥 byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes()); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); SunJCE provider=new com.sun.crypto.provider.SunJCE(); Security.addProvider(provider); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm(),provider); cipher.init(Cipher.DECRYPT_MODE, publicK); // SealedObject obj = new SealedObject(data, cipher); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解�? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); //byte[] messageBytes = (byte[]) obj.getObject(cipher); return new String(decryptedData); } }

`

你可能感兴趣的:(JAVA,对接第三方接口,项目集成,java,开发语言)