当前位置:网站首页>RSA 非对称 加密解密 加签验签工具
RSA 非对称 加密解密 加签验签工具
2022-07-27 03:44:00 【bug修复机器人】
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;
/**
* @Author:
* @Description: RSA 非对称 加密解密 加签验签工具
* @Date: Created in 15:01 2016/4/9
*/
public class AbutmentRSAUtil {
public static final String SHA1_WITH_RSA = "SHA1WithRSA";
private static final String SHA256_WITH_RSA = "SHA256WithRSA";
public static final String MD5_WITH_RSA = "MD5WithRSA";
public static final int KEY_SIZE_2048 = 2048;
public static final int KEY_SIZE_1024 = 1024;
/**
* SHA1WithRSA签名
*/
public static String sign(String in,String pivateKey,String algorithm) throws Exception{
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(pivateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signa = Signature.getInstance(algorithm!=null?algorithm:SHA256_WITH_RSA);
signa.initSign(priKey);
signa.update(in.getBytes());
byte[] signdata = signa.sign();
return Base64.encodeBase64String(signdata);
}
/**
* SHA1WithRSA签名
*/
public static String sign(String in,String pivateKey) throws Exception{
return sign(in,pivateKey,null);
}
/**
* SHA1WithRSA验签
*/
public static boolean isValid(String in,String signData,String publicKey,String algorithm) throws Exception{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decodeBase64(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signa = Signature.getInstance(algorithm!=null?algorithm:SHA256_WITH_RSA);
signa.initVerify(pubKey);
signa.update(in.getBytes());
byte[] sign_byte = Base64.decodeBase64(signData);
boolean flag = signa.verify(sign_byte);
return flag;
}
/**
* SHA1WithRSA验签
*/
public static boolean isValid(String in,String signData,String publicKey) throws Exception{
return isValid(in,signData,publicKey, null);
}
/**
* RSA公钥加密
*/
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;
}
/**
* 私钥加密
*/
public static String privateEncrypt( String str, String privateKey) throws Exception{
//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.ENCRYPT_MODE, priKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*/
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;
}
/**
* RSA公钥解密
*/
public static String publicDecrypt(String str, String publicKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//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.DECRYPT_MODE, pubKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
/**
* 随机生成密钥对
* 也可以用阿里的生成工具
*/
public static void genKeyPair(Integer keySize) throws NoSuchAlgorithmException {
if(keySize==null){
keySize = KEY_SIZE_2048;
}
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(keySize, 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
System.out.println("公钥:"+publicKeyString);
System.out.println("私钥:"+privateKeyString);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
genKeyPair(null);
}
}边栏推荐
- Five basic data structures of redis
- Is VR panorama just needed now? After reading it, you will understand
- ffmpeg合并视频功能
- 【小样本分割】MSANet: Multi-Similarity and Attention Guidance for Boosting Few-Shot Segmentation
- C get UUID
- Nacos startup and login
- 佳明手表怎么设置用户定制显示
- 微服务的feign调用header头被丢弃两种解决方案(附源码)
- 【LeetCode】Day104-无重叠区间
- JS three methods of traversing arrays: map, foreach, filter
猜你喜欢

DINO 论文精度,并解析其模型结构 & DETR 的变体

shel自动设置目录权限

从零开始C语言精讲篇4:数组

一张图看懂KingbaseES V9

scala 不可变Map 、 可变Map 、Map转换为其他数据类型

JMeter learning notes 004-csv file line number control cycle times

Navicat将MySQL导出表结构以及字段说明

BSN IPFS(星际文件系统)专网简介、功能、架构及特性、接入说明

spark练习案例(升级版)

Worship the 321 page PDF of the core technology of Internet entrepreneurship that Alibaba is pushing internally. It's really kneeling
随机推荐
STM32基于HAL库的串口接受中断和空闲中断
[untitled]
网工知识角|只需四个步骤,教会你使用SecureCRT连接到eNSP,常用工具操作指南必看
There are two solutions for the feign call header of microservices to be discarded (with source code)
微信小程序轮播图
scala 不可变Map 、 可变Map 、Map转换为其他数据类型
Rust:axum学习笔记(1) hello world
spark练习案例(升级版)
ROS camera calibration sensor_ Msgs/camerainfo message data type and meaning
ASP语音通知接口对接demo
BSN IPFS(星际文件系统)专网简介、功能、架构及特性、接入说明
P1438 无聊的数列 线段树+差分
How to set user-defined display for Jiaming Watch
Some common instructions in JVM tuning
People don't talk much, engineers don't talk much
项目参数做成可配置项,@ConfigurationProperties注解的使用
【C语言】递归详解汉诺塔问题
Framework learning journey: init process startup process
Navicat exports Mysql to table structure and field description
2022-07-26:以下go语言代码输出什么?A:5;B:hello;C:编译错误;D:运行错误。 package main import ( “fmt“ ) type integer in