java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=111, too big.
RSA用私钥签名的时候发现报错,删除以下内容即可
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; /**
* @author :cza
* @date :2021/4/14 9:52
* @description :
* @modyified By:
*/
public class RSAEncrypt {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
//加密字符串
String message = "df723820";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = encrypt(message,keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = decrypt(messageEn,keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
} /**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0,publicKeyString); //0表示公钥
keyMap.put(1,privateKeyString); //1表示私钥
}
/**
* RSA公钥加密
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encrypt(String str, String publicKey ) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
} /**
* RSA私钥解密
*
* @param str
* 加密字符串
* @param privateKey
* 私钥
* @return 铭文
* @throws Exception
* 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
} /**
* 签名
*
* @param data 待签名数据
* @param privateKey 私钥
* @return 签名
*/
public static String sign(String data, PrivateKey privateKey) throws Exception {
byte[] keyBytes = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(key);
signature.update(data.getBytes());
return new String(Base64.encodeBase64(signature.sign()));
} /**
* rsa签名
*
* @param content
* 待签名的字符串
* @param privateKey
* rsa私钥字符串
* @param charset
* 字符编码
* @return 签名结果
* @throws Exception
* 签名失败则抛出异常
*/
public static String sign(String content, String privateKey) throws Exception { //base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
try {
//RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); // 取得私钥
byte[] pri_key_bytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key_bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 生成私钥
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); return sign(content,priKey);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} /**
* 验签
*
* @param srcData 原始字符串
* @param publicKey 公钥
* @param sign 签名
* @return 是否验签通过
*/
public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
byte[] keyBytes = publicKey.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(key);
signature.update(srcData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
} /**
* 验签
*
* @param srcData 原始字符串
* @param publicKey 公钥
* @param sign 签名
* @return 是否验签通过
*/
public static boolean verify(String srcData, String publicKey, String sign) throws Exception {
byte[] publicBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
return verify(srcData,pubKey,sign);
}
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=111, too big.的更多相关文章
- 支付宝APP支付开发- IOException : DerInputStream.getLength(): lengthTag=127, too big.
支付宝APP支付Java开发报错: IOException : DerInputStream.getLength(): lengthTag=127, too big. 后来排查是因为没有设置私钥.
- java集成支付宝移动快捷支付时报错java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
出错原因是代码中的私钥设置错误,不是填原始的私钥,而是转换为PKCS8格式的私钥(Java格式的) ,改成后就会报创建交易异常了
- Rsa2加密报错java.security.spec.InvalidKeySpecException的解决办法
最近在和支付宝支付做个对接,Java项目中用到了RSA2进行加解密,在加密过程中遇到了错误: java.security.spec.InvalidKeySpecException: java.secu ...
- RSA解密报错java.security.spec.InvalidKeySpecException的解决办法
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid p ...
- 坑爹微信之读取PKCS12流时出现的java.io.IOException: DerInputStream.getLength
背景 微信退款接口需要使用到证书,我参考微信的官方Demo进行,部分代码如下: char[] password = config.getMchID().toCharArray(); InputStre ...
- What is the reason for - java.security.spec.InvalidKeySpecException: Unknown KeySpec type: java.security.spec.ECPublicKeySpec
支付中心Project重构完成,经过本地测试,并未发现问题.发布到测试环境后,测试发现请求光大扫码https接口时,出现了如下的异常: javax.net.ssl.SSLException: Serv ...
- java.security.InvalidKeyException: IOException : Short read of DER length
今天支付服务器测试退款的时候爆了异常:Caused by: java.security.InvalidKeyException: IOException : Short read of DER len ...
- 【Java安全】关于Java中常用加密/解密方法的实现
安全问题已经成为一个越来越重要的问题,在Java中如何对重要数据进行加密解密是本文的主要内容. 一.常用的加密/解密算法 1.Base64 严格来说Base64并不是一种加密/解密算法,而是一种编码方 ...
- java.lang.SecurityManager、java.security包
学习java大概3年多了,一直没有好好研究过java安全相关的问题,总是会看到 SecurityManger sm = System.getSecurityManager(); if(sm!=null ...
随机推荐
- FreeRTOS --(14)队列管理之概述
转载自 https://blog.csdn.net/zhoutaopower/article/details/107221175 在任何的 OS 中,都需要支持任务与任务,中断与任务之间的数据传输机制 ...
- 交互式 .Net
名词解析 1. 交互式 交互式是指输入代码后可直接运行该代码,然后持续输入运行代码. 2. 交互式 .Net .Net 是一种编译型语言,不像 python 这类的脚本型语言,可以边输入代码边运行结果 ...
- linux下虚拟环境venv的创建与使用以及virtualenvwrapper
1.linux安装学习python虚拟环境 linux提供的虚拟环境工具 有virtualenv pipenv 2.我们需求是在linux上可以运行 一个django2 运行一个django1 3.安 ...
- Linux-Mycat实现MySQL的读写分离
centos8 服务器共三台 client 10.0.0.88 mariadb-10.4.24 mycat-server 10.0.0.18 ...
- layui数据表格搜索
简单介绍 我是通过Servlet传递json给layui数据表格模块,实现遍历操作的,不过数据量大的话还是需要搜索功能的.这是我参考网上大佬代码写出的搜索功能. 实现原理 要实现搜索功能,肯定需要链接 ...
- 造个海洋球池来学习物理引擎【Three.js系列】
github地址:https://github.com/hua1995116/Fly-Three.js 大家好,我是秋风.继上一篇<Three.js系列: 游戏中的第一/三人称视角>今 ...
- MongoDB 体系结构与数据模型
每日一句 If no one else guards the world, then I will come forward. 如果没有别人保卫这个世界,那么我将挺身而出. 概述 MongoDB主要是 ...
- drools动态增加、修改、删除规则
目录 1.背景 2.前置知识 1.如何动态构建出一个kmodule.xml文件 2.kmodule.xml应该被谁加载 3.我们drl规则内容如何加载 4.动态构建KieContainer 3.需求 ...
- DML数据操作语言
DML数据操作语言 用来对数据库中表的数据记录进行更新.(增删改) 插入insert -- insert into 表(列名1,列名2,列名3...) values (值1,值2,值3...):向表中 ...
- 在linux上开启酸酸乳,未完待续
在服务器调试深度学习环境的时候总需要下载conda的包,一直以来都觉得是因为国内访问慢,于是想在服务器上开 ,或者ssr.由于过去用ssr多一些,于是想了解ssr on linux. 1.首先win1 ...