package com.qiuzhping.rsa;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.Cipher;
/**
* 非对称加密是公钥加密,私钥来解密.使用的是Bouncy Castle 是一种用于 Java 平台的开放源码的轻量级密码术包.
* 1、此Demo使用的是bcprov-ext-jdk15on-152.jar
* 2、把jar文件复制到 $JAVA_HOME$\jre\lib\ext目录下面
* 3、修改配置文件\jre\lib\security\java.security
* security.provider.1=sun.security.provider.Sun
* security.provider.2=sun.security.rsa.SunRsaSign
* security.provider.3=com.sun.net.ssl.internal.ssl.Provider
* security.provider.4=com.sun.crypto.provider.SunJCE
* security.provider.5=sun.security.jgss.SunProvider
* security.provider.6=com.sun.security.sasl.Provider
* security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
* security.provider.8=sun.security.smartcardio.SunPCSC 上述8个是JDK已经实现了的加密方式. 将
* security.provider.9=org.bouncycastle.jce.provider.BouncyCastleProvider 添加到后面.
* 非对称加密称为公钥加密,算法更加复杂,速度慢,加密和解密钥匙不相同,任何人都可以知道公钥,只有一个人持有私钥可以解密。
*
* @author Peter.Qiu
*
*/
public class RsaUtil {
/**
* 根据publicKey 对data进行加密.
*
* @param publicKey
* @param data
* @throws Exception
* @author Peter.Qiu
*/
public static byte[] encryptMode(PublicKey publicKey, byte[] data)
throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA",
new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);// ENCRYPT_MODE 加密
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize) {
cipher.doFinal(data, i * blockSize, blockSize, raw, i
* outputSize);
} else {
cipher.doFinal(data, i * blockSize, data.length - i
* blockSize, raw, i * outputSize);
}
i++;
}
return raw;
} catch (Exception e) {
throw e;
}
}
/**
* 根据privateKey 对data进行解密.
*
* @param privateKey
* @param data
* @throws Exception
* @author Peter.Qiu
*/
public static byte[] decryptMode(PrivateKey privateKey, byte[] data)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);// DECRYPT_MODE 解密
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
}
/**
* 获取密钥.
*
* @param rsaKeyStore
* @return
* @throws Exception
* @author Peter.Qiu
*/
public static KeyPair getKeyPair(String rsaKeyStore) throws Exception {
FileInputStream fis = new FileInputStream(rsaKeyStore);
ObjectInputStream oos = new ObjectInputStream(fis);
KeyPair kp = (KeyPair) oos.readObject();
oos.close();
fis.close();
return kp;
}
/**
* 将密钥写入文件.
*
* @param kp
* @param path
* @throws Exception
* @author Peter.Qiu
*/
public static void saveKeyPair(KeyPair kp, String path) throws Exception {
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
oos.writeObject(kp);
oos.close();
fos.close();
}
/**
* 用于生成公匙或私匙.
*
* @return
* @throws NoSuchAlgorithmException
* @author Peter.Qiu
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
SecureRandom sr = new SecureRandom();
KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA",
new BouncyCastleProvider());
// 注意密钥大小最好为1024,否则解密会有乱码情况.
kg.initialize(1024, sr);
KeyPair genKeyPair = kg.genKeyPair();
return genKeyPair;
}
/**
* 将公密或私密写入文件.
*
* @param obj
* @param path
* @throws Exception
* @author Peter.Qiu
*/
public static void saveFile(Object obj, String path) throws Exception {
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密钥
oos.writeObject(obj);
oos.close();
fos.close();
}
/**
* 获取公密.
*
* @param publicKeyPath
* @return
* @throws Exception
* @author Peter.Qiu
*/
public static PublicKey getPublicKey(String publicKeyPath) throws Exception {
FileInputStream fis = new FileInputStream(publicKeyPath);
ObjectInputStream oos = new ObjectInputStream(fis);
PublicKey kp = (PublicKey) oos.readObject();
oos.close();
fis.close();
return kp;
}
/**
* 获取私密.
*
* @param privateKeyPath
* @return
* @throws Exception
* @author Peter.Qiu
*/
public static PrivateKey getPrivateKey(String privateKeyPath)
throws Exception {
FileInputStream fis = new FileInputStream(privateKeyPath);
ObjectInputStream oos = new ObjectInputStream(fis);
PrivateKey kp = (PrivateKey) oos.readObject();
oos.close();
fis.close();
return kp;
}
public static void main(String[] args) throws Exception {
File dir = new File("./key/");
if (!dir.exists()) {
dir.mkdir();
}
// 获取公匙及私匙
KeyPair generateKeyPair = getKeyPair("./key/key");
// 生成公钥及私钥
// generateKeyPair = generateKeyPair();
// 存储KeyPair到本地用于后期解密 注意修改前台RSAKeyPair
// saveKeyPair(generateKeyPair,"./key/key");
System.out.println("generateKeyPair : " + generateKeyPair);
// 公匙 用于前台加密
PublicKey publicKey = null;// generateKeyPair.getPublic();
publicKey = getPublicKey("./key/publicKey.key");
System.out.println("publicKey:" + publicKey);
// saveFile(publicKey,"./key/publicKey.key");
// 私匙 存储在后台用于解密
PrivateKey privateKey = null;// generateKeyPair.getPrivate(); //
privateKey = getPrivateKey("./key/privateKey.key");//
System.out.println("privateKey:" + privateKey);
// saveFile(privateKey,"./key/privateKey.key");
// 测试加密解密
String test = "saaaa";
test = "Peter.Qiu丘丘丘邱";
System.out.println("加密前字符:" + test);
byte[] en_test = encryptMode(publicKey, test.getBytes("UTF-8"));
System.out.println("加密后字符:" + new String(en_test));
byte[] de_test = decryptMode(privateKey, en_test);
System.out.println("解密后字符:" + new String(de_test, "UTF-8"));
}
}
Java非对称加密解密(RSA)
4星 · 超过85%的资源 需积分: 0 43 浏览量
2015-03-17
17:17:14
上传
评论 3
收藏 2.77MB ZIP 举报
Nocturne2011
- 粉丝: 68
- 资源: 20
最新资源
- C# OpenCvSharp Demo - 最大内接圆.rar
- 基于python和Matlab的爬虫+情感分析+时间序列+长图自动分割项目合集(高分项目).zip
- ME2308-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
- 使用Java实现的基于最小生成树的旅行商问题.zip
- ME2308D-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
- 数据并行C++(Data Parallel C++) 英文版
- MongoDB数据库操作和面试专题及答案.zip
- C#实现通用USB摄像头的读取,拍照,视频录制等功能
- 基于Python实现的多目标旅行商问题算法优化.zip
- LN2312LT1G-VB一款SOT23封装N-Channel场效应MOS管
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈