RSA不对称加密
package sinRsa; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; public class RSAUtil {
// 数字签名,密钥算法
private static final String RSA_KEY_ALGORITHM = "RSA"; // 数字签名签名/验证算法
private static final String SIGNATURE_ALGORITHM = "MD5withRSA"; // RSA密钥长度
private static final int KEY_SIZE = 1024; //RSA最大加密明文大小
private static final int MAX_ENCRYPT_BLOCK = 117; //RSA最大解密密文大小
private static final int MAX_DECRYPT_BLOCK = 128; /**
* 初始化RSA密钥对
* @return RSA密钥对
* @throws Exception 抛出异常
*/
private static void initKey(String pubkeyfile, String privatekeyfile) throws Exception {
KeyPairGenerator keygen = KeyPairGenerator
.getInstance(RSA_KEY_ALGORITHM);
SecureRandom secrand = new SecureRandom();
secrand.setSeed("hahaha".getBytes());// 初始化随机产生器
keygen.initialize(KEY_SIZE, secrand); // 初始化密钥生成器
KeyPair keys = keygen.genKeyPair();
String pub_key = Base64.encodeBase64String(keys.getPublic().getEncoded());
String pri_key = Base64.encodeBase64String(keys.getPrivate().getEncoded());
// 生成私钥
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
privatekeyfile));
oos.writeObject(pri_key);
oos.flush();
oos.close();
// 生成公钥
oos = new ObjectOutputStream(new FileOutputStream(pubkeyfile));
oos.writeObject(pub_key);
oos.flush();
oos.close();
System.out.println("公钥:" + pub_key);
System.out.println("私钥:" + pri_key);
} /**
* 数字签名
* @param data 待签名数据
* @param pri_key 私钥
* @return 签名
* @throws Exception 抛出异常
*/
public static String sign(byte[] data, String pri_key) throws Exception {
// 取得私钥
byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key_bytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 生成私钥
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initSign(priKey);
// 更新
signature.update(data);
return Base64.encodeBase64String(signature.sign());
} /**
* RSA校验数字签名
* @param data 数据
* @param sign 签名
* @param pub_key 公钥
* @return 校验结果,成功为true,失败为false
* @throws Exception 抛出异常
*/
public boolean verify(byte[] data, byte[] sign, String pub_key) throws Exception {
// 转换公钥材料
// 实例化密钥工厂
byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 初始化公钥
// 密钥材料转换
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key_bytes);
// 产生公钥
PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initVerify(pubKey);
// 更新
signature.update(data);
// 验证
return signature.verify(sign);
} /**
* 公钥加密
* @param data 待加密数据
* @param pub_key 公钥
* @return 密文
* @throws Exception 抛出异常
*/
private static byte[] encryptByPubKey(byte[] data, byte[] pub_key) throws Exception {
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
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 encryptedData;
} /**
* 公钥加密
* @param data 待加密数据
* @param pub_key 公钥
* @return 密文
* @throws Exception 抛出异常
*/
public static String encryptByPubKey(String data, String pub_key) throws Exception {
// 私匙加密
byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
byte[] enSign = encryptByPubKey(data.getBytes(), pub_key_bytes);
return Base64.encodeBase64String(enSign);
} /**
* 私钥加密
* @param data 待加密数据
* @param pri_key 私钥
* @return 密文
* @throws Exception 抛出异常
*/
private static byte[] encryptByPriKey(byte[] data, byte[] pri_key) throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
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 encryptedData;
} /**
* 私钥加密
* @param data 待加密数据
* @param pri_key 私钥
* @return 密文
* @throws Exception 抛出异常
*/
public static String encryptByPriKey(String data, String pri_key) throws Exception {
// 私匙加密
byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
byte[] enSign = encryptByPriKey(data.getBytes(), pri_key_bytes);
return Base64.encodeBase64String(enSign);
} /**
* 公钥解密
* @param data 待解密数据
* @param pub_key 公钥
* @return 明文
* @throws Exception 抛出异常
*/
private static byte[] decryptByPubKey(byte[] data, byte[] pub_key) throws Exception {
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
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();
return decryptedData;
} /**
* 公钥解密
* @param data 待解密数据
* @param pub_key 公钥
* @return 明文
* @throws Exception 抛出异常
*/
public static String decryptByPubKey(String data, String pub_key) throws Exception {
// 公匙解密
byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
byte[] design = decryptByPubKey(Base64.decodeBase64(data), pub_key_bytes);
return new String(design);
} /**
* 私钥解密
* @param data 待解密数据
* @param pri_key 私钥
* @return 明文
* @throws Exception 抛出异常
*/
private static byte[] decryptByPriKey(byte[] data, byte[] pri_key) throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
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();
return decryptedData;
} /**
* 私钥解密
* @param data 待解密数据
* @param pri_key 私钥
* @return 明文
* @throws Exception 抛出异常
*/
public static String decryptByPriKey(String data, String pri_key) throws Exception {
// 私匙解密
byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
byte[] design = decryptByPriKey(Base64.decodeBase64(data), pri_key_bytes);
return new String(design);
} /**
* @param args
*/
public static void main(String[] args) throws Exception {
String pubfile = "d:/temp/pub.key";
String prifile = "d:/temp/pri.key"; initKey(pubfile,prifile); //获取公钥
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(pubfile));
String pub_key = (String) ois.readObject();
ois.close();
//获取私钥
ois = new ObjectInputStream(new FileInputStream(prifile));
String pri_key = (String) ois.readObject();
ois.close(); RSAUtil das = new RSAUtil();
String datastr = "这是我第一次写rsa加密。";
System.out.println("待加密数据:\n" + datastr); // 公匙加密
String pubKeyStr = RSAUtil.encryptByPubKey(datastr, pub_key);
System.out.println("公匙加密结果:\n" + pubKeyStr);
// 私匙解密
String priKeyStr = RSAUtil.decryptByPriKey(pubKeyStr, pri_key);
System.out.println("私匙解密结果:\n" + priKeyStr); //换行
System.out.println(); // 数字签名
String str1 = "天地玄黄";
String str2 = "宇宙洪荒";
System.out.println("正确的签名:" + str1 + "\n错误的签名:" + str2);
String sign = RSAUtil.sign(str1.getBytes(), pri_key);
System.out.println("数字签名:\n" + sign);
boolean vflag1 = das.verify(str1.getBytes(), Base64.decodeBase64(sign), pub_key);
System.out.println("数字签名验证结果1:\n" + vflag1);
boolean vflag2 = das.verify(str2.getBytes(), Base64.decodeBase64(sign), pub_key);
System.out.println("数字签名验证结果2:\n" + vflag2);
}
}
RSA不对称加密的更多相关文章
- RSA不对称加密,公钥加密私钥解密,私钥加密公钥解密
RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一 ...
- RSA不对称加密和公钥 私钥
理论上只要有加密的规则 基本都是可以解密的 但是如果解密需要消耗的时间过长 比如1000年 解密过后已经没什么意义了 此时可认为这种算法不能被破解 也就是说此加密可信 MD5 是一种单向操作 加密后不 ...
- C#不对称加密
对称加密的缺点是双方使用相同的密钥和IV进行加密.解密.由于接收方必须知道密钥和IV才能解密数据,因此发送方需要先将密钥和IV传递给接收方.这就 有一个问题,如果攻击者截获了密钥和IV,也就等于知道了 ...
- android 对称加密,非对称加密 android 常见的加密
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha android 常见的加密 ======== 不可逆加密:md5,sha1 可逆的加密中 ...
- AES,RSA对称加密和非对称加密
1.关于RSA加密机制:是非对称加密方式,两个钥,公钥和私钥,公钥用于加密数据,可以分享给其他用户,私钥可以用于解密用公钥加密的数据,关于安全问题是公钥泄露不会影响安全问题,公钥与私钥是一一对应的关系 ...
- [Node.js] 对称加密、公钥加密和RSA
原文地址:http://www.moye.me/2015/06/14/cryptography_rsa/ 引子 对于加解密,我一直处于一种知其然不知其所以然的状态,项目核心部分并不倚重加解密算法时,可 ...
- 加密算法(对称加密)AES、DES (非对称加密)RSA、DSA
目前主流的加密方式有:(对称加密)AES.DES (非对称加密)RSA.DSA
- 数字签名中公钥和私钥是什么?对称加密与非对称加密,以及RSA的原理
http://baijiahao.baidu.com/s?id=1581684919791448393&wfr=spider&for=pc https://blog.csdn.net/ ...
- 对称加密与非对称加密,以及RSA的原理
一 , 概述 在现代密码学诞生以前,就已经有很多的加密方法了.例如,最古老的斯巴达加密棒,广泛应用于公元前7世纪的古希腊.16世纪意大利数学家卡尔达诺发明的栅格密码,基于单表代换的凯撒密码.猪圈密码, ...
随机推荐
- xBIM 基础06 将STEP物理文件转换为XML
系列目录 [已更新最新开发文章,点击查看详细] 一.STEP标准简介 STEP,它是Standard for the Exchange of Product model data的缩写.产品数 ...
- JavaScript学习记录一
title: JavaScript学习记录一 toc: true date: 2018-09-11 18:26:52 --<JavaScript高级程序设计(第2版)>学习笔记 要多查阅M ...
- python网页问题
#django-admin不是个命令 添加环境变量 D:\Python36\Scripts #localhost加载失败 命令行 python manage.py runserver 0.0.0.0: ...
- 51nod 1065 最小正字段和 解决办法:set存前缀和,二分插入和二分查找
题目: 这题要求大于0的最小字段和,常规O(n)求最大字段和的方法肯定是没法解的. 我的解法是:用sum[i]存前i项的和,也就是前缀和. 这题就变成了求sum[j]-sum[i]的大于0的最小值( ...
- PostgreSQL 数据库性能调优的注意点
PostgreSQL提供了一些性能调优的功能.主要有如下几个方面.1.使用EXPLAIN EXPLAIN命令可以查看执行计划,这个方法是我们最主要的调试工具. 2.及时更新执行计划中使用的统计信息 ...
- 《剑指offer》数组中出现次数超过一半的数字
一.题目描述 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字.例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}.由于数字2在数组中出现了5次,超过数组长度的一半,因此输出 ...
- 《剑指offer》二叉搜索树与双向链表
一.题目描述 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表.要求不能创建任何新的结点,只能调整树中结点指针的指向 二.输入描述 输入一棵二叉搜索树 三.输出描述 将该二叉搜索树转换成一个 ...
- centos下nginx配置
转自 http://www.linuxidc.com/Linux/2016-09/134907.htm 安装所需环境 Nginx 是 C语言 开发,建议在 Linux 上运行,当然,也可以安装 Wi ...
- 1,http协议的细节部分学习
http协议(80端口)https(443端口) 主要是一直对三次握手模模糊糊,并且抓包的时候不知道那些Accept.User-Agent什么意思,就仔细找课程学了一下. 学习简介: 1,涉及工具(w ...
- ActiveMQ学习笔记(8)----ActiveMQ的消息存储持久化
1. 概述 ActiveMQ不仅支持persistent和non-persistent两种方式,还支持消息的恢复(recovery)方式. 2. PTP Queue的存储是很简单的,其实就是FIFO的 ...