加密和解密使用不同的密钥(公钥/私钥),非对称加密/解密的安全性是基于复杂数学难题,特点是运算复杂、速度慢,主要应用于金融、军事等重大机密的系统。
使用RSA加密数据时需要使用密钥对,也就是一个公钥,一个私钥。如A、B双方发送数据,A生成密钥对,将公钥发送给B,A将数据用私钥加密后发送给B,而B用A提供的公钥对数据进行解密。如果是B向A发送数据,B用公钥加密数据并发送给A,A使用私钥对数据进行解密。
非常重要的RSAUtils.java完整代码:
package com.example.myfirstkotlin.model;
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
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 java.util.HashMap;
import java.util.Map;
/**
* 非对称加密算法RSA
*/
public class RSAUtils {
/**
* 指定加密算法为RSA
*/
private static final String ALGORITHM = "RSA";
/**
* 加密填充方式
*/
public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
/**
* 密钥长度,用来初始化
*/
private static final int KEYSIZE = 1024;
/**
* 公钥
*/
private static Key publicKey = null;
/**
* 私钥
*/
private static Key privateKey = null;
/**
* 公钥字符串
*/
private static String publicKeyString ="";
/**
* 私钥字符串
*/
private static String privateKeyString ="";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 生成密钥对
*
* @throws Exception
*/
public static Map generateKeyPair() throws Exception {
// // /** RSA算法要求有一个可信任的随机数源 */
SecureRandom secureRandom = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
keyPairGenerator.initialize(KEYSIZE, secureRandom);
// /** 生成密匙对 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Map keyMap = new HashMap();
// /** 得到公钥 */
BASE64Encoder encoder = new BASE64Encoder();
keyMap.put("public", new String(encoder.encode(keyPair.getPublic().getEncoded()).getBytes(), "UTF-8"));
keyMap.put("private", new String(encoder.encode(keyPair.getPrivate().getEncoded()).getBytes(), "UTF-8"));
return keyMap;
}
/**
* 生成公钥对象
*
* @param publicKeyStr
* @throws Exception
*/
public static void setPublicKey(String publicKeyStr) throws Exception {
RSAUtils.publicKey = generatePublicKey(publicKeyStr);
}
/**
* 生成私钥对象
*
* @param privateKeyStr
* @throws Exception
*/
public static void setPrivateKey(String privateKeyStr) throws Exception {
RSAUtils.privateKey = generatePrivateKey(privateKeyStr);
}
/**
* 私钥加密方法
*
* @param privatekey
* @return
* @throws Exception
*/
public static String encryptByPrivateKey(String source, String privatekey) throws Exception {
generatePrivateKey(privatekey);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] data = source.getBytes();
/** 执行数据分组加密操作 */
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();
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(encryptedData);
}
/**
* 使用公钥解密算法
*
* @param cryptoSrc 密文
* @return
* @throws Exception
*/
public static String decryptByPublicKey(String cryptoSrc, String publicStr) throws Exception {
setPublicKey(publicStr);
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
BASE64Decoder decoder = new BASE64Decoder();
byte[] encryptedData = decoder.decodeBuffer(cryptoSrc);
/** 执行解密操作 */
int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, 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);
}
/**
* 公钥加密方法
*
* @param pubString
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String source, String pubString) throws Exception {
setPublicKey(pubString);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] data = source.getBytes();
/** 执行分组加密操作 */
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();
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(encryptedData);
}
/**
* 私钥解密算法
*
* @param cryptoSrc 密文
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String cryptoSrc, String privatekey) throws Exception {
//生成私钥对象
setPrivateKey(privatekey);
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
BASE64Decoder decoder = new BASE64Decoder();
byte[] encryptedData = decoder.decodeBuffer(cryptoSrc);
/** 执行解密操作 */
int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, 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);
}
/**
* 将给定的公钥字符串转换为公钥对象
*
* @param publicKeyStr
* @return
* @throws Exception
*/
private static Key generatePublicKey(String publicKeyStr) throws Exception {
publicKeyString = publicKeyStr;
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
return publicKey;
} 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 privateKeyStr
* @return
* @throws Exception
*/
private static Key generatePrivateKey(String privateKeyStr) throws Exception {
privateKeyString = privateKeyStr;
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (IOException e) {
throw new Exception("私钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
public static void main(String[] args) throws Exception {
Map keyMap = generateKeyPair();
System.out.println("public------" + keyMap.get("public"));
System.out.println("private------" + keyMap.get("private"));
publicKeyString=keyMap.get("public");
privateKeyString=keyMap.get("private");
setPublicKey(publicKeyString);
setPrivateKey(privateKeyString);
long a = System.currentTimeMillis();
System.out.println("公钥字符串: ");
System.out.println(publicKeyString);
System.out.println();
System.out.println();
System.out.println("公钥字符串长度" + publicKeyString.length());
System.out.println();
System.out.println();
System.out.println("私钥字符串: ");
System.out.println(privateKeyString);
System.out.println();
System.out.println();
System.out.println("私钥字符串长度" + privateKeyString.length());
System.out.println();
System.out.println();
System.out.println("公钥对象: ");
System.out.println(publicKey);
System.out.println();
System.out.println();
System.out.println("私钥对象: ");
System.out.println(privateKey);
String origin = "高考放榜,有人欣喜,有人失意,无论结果如何,只要奋斗过,就青春无悔。高考能改变人生,但不会决定人生,只要你不停止努力,就可以成为更好的自己。";
String s = new String(new BASE64Encoder().encodeBuffer(origin.getBytes()));
String en = encryptByPublicKey(s, publicKeyString);
System.out.println("en-->" + en);
String encodedString=new String(new BASE64Decoder().decodeBuffer(decryptByPrivateKey(en, privateKeyString)));
System.out.println("解密后的字符串====》"+encodedString);
System.out.println(System.currentTimeMillis() - a);
}
}