当前位置:网站首页>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);
}
}边栏推荐
- 利用JSON类型在mysql中实现数组功能
- Plato Farm全新玩法,套利ePLATO稳获超高收益
- 第二轮Okaleido Tiger即将登录Binance NFT,或持续创造销售神绩
- 微信小程序轮播图
- People don't talk much, engineers don't talk much
- ISG index shows that the it and business service market in the Asia Pacific region fell sharply in the second quarter
- 使用kubesphere图形界面dashboard开启devops功能
- Prometheus Node Exporter 常用监控指标
- JS modify the key value of the object array
- 微信input组件添加清除图标,点击清空不生效
猜你喜欢

Overview of communication protocols

使用WebMvcConfigurer进行接口请求拦截进行中增强(附源码)

There are two solutions for the feign call header of microservices to be discarded (with source code)

Redis面试题(2022)

e.target与e.currentTarget的区别

【C语言】递归详解汉诺塔问题

Eureka-服务注册中心

From scratch, C language intensive Lecture 4: array

Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化

scala 不可变Map 、 可变Map 、Map转换为其他数据类型
随机推荐
Brightcove appoints Dan Freund as chief revenue Officer
Ribbon负载均衡策略与配置、Ribbon的懒加载和饥饿加载
els 兼容性DC、传递图片到窗口
xxx is not in the sudoers file. This incident will be reported
第二轮Okaleido Tiger即将登录Binance NFT,或持续创造销售神绩
JVM调优中的一些常见指令
Convolution neural network -- a detailed introduction to convolution of 24 bit color images
Okaleido生态核心权益OKA,尽在聚变Mining模式
管理信息系统期末复习
Overview of communication protocols
Eureka service registry
Elastic open source community: Developer Recruitment
ASP voice notification interface docking demo
电商分账系统重要吗,平台应该如何选择分账服务商呢?
Plato farm has a new way of playing, and the arbitrage eplato has secured super high returns
PX4模块设计之十二:High Resolution Timer设计
Differences and uses of SRAM, DRAM, SDRAM and DDR
Worship the 321 page PDF of the core technology of Internet entrepreneurship that Alibaba is pushing internally. It's really kneeling
Nacos startup and login
tcp协议知识详解