RSA 加密,解密,签名,验签
一、RSA加密简介
RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。
是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数学相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。
通常个人保存私钥,公钥是公开的(可能同时多人持有)。
二.使用场景:
加密和签名是两个不同的概念,又都涉及公钥和私钥的概念。
公钥和私钥相当于钥匙和锁,锁可以用来锁住东西,钥匙可以用来打开对应的锁,一把钥匙只能开一把锁,当然钥匙和锁都可以复制。
1.加密相当于我自己生成一把锁和一把钥匙,然后把锁发给你,你用我的锁把想发给我的东西锁上再发给我,我收到之后用钥匙打开锁。
天下人都能拿到我的锁,但只有我有这把锁的钥匙。这个例子中,钥匙相当于私钥,锁相当于公钥。数字加密涉及三个过程:
- 生成一对公钥和私钥
- 加密:公钥+明文->密文
- 解密:私钥+密文->明文
2。签名 相当于我自己生成一把锁和一把钥匙,然后把我想发布的内容用我的锁锁起来形成一个签名,把内容和签名一起发布,并且告诉大家我的钥匙是什么。
人们可以拿到钥匙来打开签名里的内容来验证是不是跟发布的内容一致。天下人都能拿到钥匙来验证签名与内容的一致性,但只有我有签名的锁。
这个例子中,钥匙相当于公钥,锁相当于私钥。数字签名涉及三个过程:
- 生成一对公钥和私钥
- 签名:私钥+内容->签名
- 验证:公钥+签名+内容->内容有没有改变
三。代码示例:
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.tomcat.util.codec.binary.Base64; public class TestRSA { /**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117; /**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128; /**
* 获取密钥对
*
* @return 密钥对
*/
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
return generator.generateKeyPair();
} /**
* 获取私钥
*
* @param privateKey 私钥字符串
* @return
*/
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
return keyFactory.generatePrivate(keySpec);
} /**
* 获取公钥
*
* @param publicKey 公钥字符串
* @return
*/
public static PublicKey getPublicKey(String publicKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
} /**
* RSA加密
*
* @param data 待加密数据
* @param publicKey 公钥
* @return
*/
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().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.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return new String(Base64.encodeBase64String(encryptedData));
} /**
* RSA解密
*
* @param data 待解密数据
* @param privateKey 私钥
* @return
*/
public static String decrypt(String data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.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(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
} /**
* 签名
*
* @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()));
} /**
* 验签
*
* @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()));
} public static void main(String[] args) {
try {
// 生成密钥对
KeyPair keyPair = getKeyPair();
String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
System.out.println("私钥:" + privateKey);
System.out.println("公钥:" + publicKey);
// RSA加密
String data = "待加密的文字内容";
String encryptData = encrypt(data, getPublicKey(publicKey));
System.out.println("加密后内容:" + encryptData);
// RSA解密
String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
System.out.println("解密后内容:" + decryptData); // RSA签名
String sign = sign(data, getPrivateKey(privateKey));
// RSA验签
boolean result = verify(data, getPublicKey(publicKey), sign);
System.out.print("验签结果:" + result);
} catch (Exception e) {
e.printStackTrace();
System.out.print("加解密异常");
}
}
}
参考博客:https://www.cnblogs.com/pcheng/p/9629621.html
RSA 加密,解密,签名,验签的更多相关文章
- Java RSA 加密 解密 签名 验签
原文:http://gaofulai1988.iteye.com/blog/2262802 import java.io.FileInputStream; import java.io.FileOut ...
- RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密
原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...
- js rsa sign使用笔记(加密,解密,签名,验签)
你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...
- C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic
C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...
- 支付接口中常用的加密解密以及验签rsa,md5,sha
一.常用加密类型分类 1.对称加密:采用单钥对信息进行加密和解密,即同一个秘钥既可以对信息进行加密,也可以进行解密.此类型称之为对称加密.特点速度快,常用于对大量数据信息或文件加密时使用.常用例子:D ...
- RSA加密解密与加签验签
RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...
- iOS使用Security.framework进行RSA 加密解密签名和验证签名
iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...
- Java使用RSA加密解密签名及校验
RSA加密解密类: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ...
- 数据安全管理:RSA加密算法,签名验签流程详解
本文源码:GitHub·点这里 || GitEE·点这里 一.RSA算法简介 1.加密解密 RSA加密是一种非对称加密,在公开密钥加密和电子商业中RSA被广泛使用.可以在不直接传递密钥的情况下,完成加 ...
- C#的RSA加密解密签名,就为了支持PEM PKCS#8格式密钥对的导入导出
差点造了一整个轮子 .Net Framework 4.5 里面的RSA功能,并未提供简单对PEM密钥格式的支持(.Net Core有咩?),差点(还远着)造了一整个轮子,就为了支持PEM PKCS#8 ...
随机推荐
- 【笔记整理】request模块基本使用
基本使用 发送get请求.获取响应各种请求.响应信息 def fun1(): url = "http://www.baidu.com" resp = requests.get(ur ...
- git报错解决,warning: could not find UI helper 'git-credential-manager-ui'
在克隆远程代码时,可能遇到这样的报错 warning: could not find UI helper 'git-credential-manager-ui' 这样的报错经常会在我们换了一台电脑或者 ...
- ubuntu设置系统字符集为中文
第一步:查看自己系统的字符集 先查看系统的默认字符集格式:locale 或者cat /etc/default/locale root@JumpServer-APP-T02:~# locale LANG ...
- Supershell防溯源反制配置
简介 项目地址:https://github.com/tdragon6/Supershell Supershell是一个集成了reverse_ssh服务的WEB管理平台,使用docker一键部署(快速 ...
- manjaro下使用deepin-wine5解决wechat无法发送图片的问题
问题 在manjaro操作系统下,使用了deepin-wine安装wechat.但是,wechat运行无法发送较大图片且截图功能也有问题. 解决 在参考了github之后,我找到了解决方案. 附上链接 ...
- 国产Geoscene Server 4.0编译SOE总结
背景:公司一直使用Arcgis Server 10.1.Visual Studio 2010开发SOE功能,随着国产化软件发展大趋势,SOE中的各种分析功能,需要升级到Geoscene Server环 ...
- 新一代通信协议 - Socket.D
一.简介 Socket.D 是一种二进制字节流传输协议,位于 OSI 模型中的5~6层,底层可以依赖 TCP.UDP.KCP.WebSocket 等传输层协议.由 Noear 开发.支持异步流处理.其 ...
- Provider 四种消费者
Provider.of Provider.of 方法是 Provider 库中最常用的获取共享数据的方法之一.它接收一个 BuildContext 对象和一个泛型类型参数 T,会查找 Widget 树 ...
- 云图说|AI开发难!难!难!端云协同多模态AI开发套件你需要了解一下
摘要:Huawei HiLens Kit是一款端云协同多模态AI开发套件,支持图像.视频.语音等多种数据分析与推理计算,可广泛用于智能监控.智能家庭.机器人.无人机.智慧工业.智慧门店等分析场景. 在 ...
- 万字长文|Hadoop入门笔记(附资料)
大数据迅速发展,但是Hadoop的基础地位一直没有改变.理解并掌握Hadoop相关知识对于之后的相关组件学习有着地基的作用.本文整理了Hadoop基础理论知识与常用组件介绍,虽然有一些组件已经不太常用 ...