import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
public class RSAEncrypt {
private static final String DEFAULT_PUBLIC_KEY1=""
+"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGaeXY1/bTQ/exo57QGqZ30FNV"
+"saPKyz1SJtjVj+5gYs0ml9YGqzXm2Y3xtR9q2xkdO5TKMkDeL95Lidp49RAOMC8/"
+"105LkyESwZVVAWB8GKS5RbCi7chbct0alYT2eSJkI9ihEc8aouQ2/P5+sGUUqzVP"
+"e/n+bs7fTlL4OJV/bQIDAQAB";
private static final String DEFAULT_PRIVATE_KEY=""
+"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMZp5djX9tND97Gj"
+"ntAapnfQU1Wxo8rLPVIm2NWP7mBizSaX1garNebZjfG1H2rbGR07lMoyQN4v3kuJ"
+"2nj1EA4wLz/XTkuTIRLBlVUBYHwYpLlFsKLtyFty3RqVhPZ5ImQj2KERzxqi5Db8"
+"/n6wZRSrNU97+f5uzt9OUvg4lX9tAgMBAAECgYA6ijQObmmcm4kRGD1bGQHUh9qO"
+"hgLVanGFM4D2QakLNxtgL5wuC4WzvqxqjA3g8RPP1CxqG7mX1He5wcp7tZIumHa3"
+"iE7jok0y8behrf3/esw3RGiPia2q7ue1kQeC6CoRd1kByhaBs/z6W0g7/YdEpwI+"
+"T7rWVwI03p2Z8XrgAQJBAOUIqhTRKscLnaBRHBk1zG3UjFmJKgrp9gHGyYJfax5d"
+"SZDl25e8WT9sdIBQfHysH1bvQIsdfMJPXvfwr2pPXQECQQDdxk6Yx1LGJDdlH/Qy"
+"15NFZvke/xDYvN2YqjkFoMdp2aFH7T+p1nBUVtd0fWcQaMAulQBnePh81BPDIJvb"
+"POZtAkBwvWcbgCrSeAFLXSG7tyO+HJZJrJ8paClUjom6x0VvWPRRgxQpCOnVsolW"
+"cEgXBpMWtAbNc+Jps7BH1A5FAnQBAkArFoVcv5VAc/bjSeMLIcE2QbxzHkFqqr8v"
+"ExuDEWrNEQB51gmBeO1YJYs00cx9bqywIDj04Zb9wcKZLbO6U8m9AkAEIOaCFC9A"
+"3I4kC+n3PI2RiyKm2Y4pIc8hvLF7fdKRJLhE6CU54HfnWfp60cafLQbArfQPaJeq"
+"fRwmeXX3YHU1";
/**
* 私钥
*/
private RSAPrivateKey privateKey;
/**
* 公钥
*/
private RSAPublicKey publicKey;
/**
* 字节数据转字符串专用集合
*/
private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 获取私钥
* @return 当前的私钥对象
*/
public RSAPrivateKey getPrivateKey() {
return privateKey;
}
/**
* 获取公钥
* @return 当前的公钥对象
*/
public RSAPublicKey getPublicKey() {
return publicKey;
}
/**
* 随机生成密钥对
*/
public void genKeyPair(){
KeyPairGenerator keyPairGen= null;
try {
keyPairGen= KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair= keyPairGen.generateKeyPair();
this.privateKey= (RSAPrivateKey) keyPair.getPrivate();
this.publicKey= (RSAPublicKey) keyPair.getPublic();
}
/**
* 从文件中输入流中加载公钥
* @param in 公钥输入流
* @throws Exception 加载公钥时产生的异常
*/
public void loadPublicKey(InputStream in) throws Exception{
try {
BufferedReader br= new BufferedReader(new InputStreamReader(in));
String readLine= null;
StringBuilder sb= new StringBuilder();
while((readLine= br.readLine())!=null){
if(readLine.charAt(0)=='-'){
continue;
}else{
sb.append(readLine);
sb.append('\r');
}
}
loadPublicKey(sb.toString());
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输入流为空");
}
}
/**
* 从字符串中加载公钥
* @param publicKeyStr 公钥数据字符串
* @throws Exception 加载公钥时产生的异常
*/
public void loadPublicKey(String publicKeyStr) throws Exception{
try {
BASE64Decoder base64Decoder= new BASE64Decoder();
byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer);
this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 从文件中加载私钥
* @param keyFileName 私钥文件名
* @return 是否成功
* @throws Exception
*/
public void loadPrivateKey(InputStream in) throws Exception{
try {
BufferedReader br= new BufferedReader(new InputStreamReader(in));
String readLine= null;
StringBuilder sb= new StringBuilder();
while((readLine= br.readLine())!=null){
if(readLine.charAt(0)=='-'){
continue;
}else{
sb.append(readLine);
sb.append('\r');
}
}
loadPrivateKey(sb.toString());
} catch (IOException e) {
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥输入流为空");
}
}
public void loadPrivateKey(String privateKeyStr) throws Exception{
try {
BASE64Decoder base64Decoder= new BASE64Decoder();
byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (IOException e) {
throw new Exception("私钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
/**
* 加密过程
* @param publicKey 公钥
* @param plainTextData 明文数据
* @return
* @throws Exception 加密过程中的异常信息
*/
public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception{
if(publicKey== null){
throw new Exception("加密公钥为空, 请设置");
}
Cipher cipher= null;
try {
cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output= cipher.doFinal(plainTextData);
return output;
} catch (NoSuchAlgorit
RSA对称加密算法
最新推荐文章于 2024-07-08 13:11:11 发布