import javax.crypto.Cipher;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtils {private static String ALGORITHM = "RSA";
private static int KEY_SIZE = 1024;
private static String SEED = "msat";
/**
* 生成公钥、私钥
* @return 公钥私钥
*/
public static String[] generateKeys() throws NoSuchAlgorithmException {
//1.初始化密钥对生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE,new SecureRandom(Base64Utils.encrypt(SEED.getBytes()).getBytes()));
//2.生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//3.base64编码公钥、私钥 返回
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String[] result = new String[2];
result[0] = Base64Utils.encrypt(publicKey.getEncoded());
//公钥
result[1] = Base64Utils.encrypt(privateKey.getEncoded());
return result;
}/**
* 私钥加密
* @param content 被加密内容
* @param keyPrivateBase64 私钥(base64加密)
*/
public static String encryptByPrivate(String content,String keyPrivateBase64) throws Exception {
RSAPrivateKey privateKey = obtainPrivateKey(keyPrivateBase64);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,privateKey);
byte[] encoded = cipher.doFinal(content.getBytes("UTF-8"));
return Base64Utils.encrypt(encoded);
}/**
* 私钥解密
* @param encodedContent
* @param keyPrivateBase64
* @return
*/
public static String decryptByPrivate(String encodedContent,String keyPrivateBase64) throws Exception {
RSAPrivateKey privateKey = obtainPrivateKey(keyPrivateBase64);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] bytes = cipher.doFinal(Base64Utils.decrypt(encodedContent));
return new String(bytes);
}private static RSAPrivateKey obtainPrivateKey(String keyPrivateBase64) throws Exception {
byte[] keyBytes = Base64Utils.decrypt(keyPrivateBase64);
return (RSAPrivateKey) KeyFactory.getInstance(ALGORITHM)
.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
}/**
* 公钥加密
* @param content 被加密内容
* @param keyPublicBase64 公钥(base64加密)
* @return
*/
public static String encryptByPublic(String content,String keyPublicBase64) throws Exception {
RSAPublicKey publicKey = obtainPublicKey(keyPublicBase64);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] encoded = cipher.doFinal(content.getBytes("utf-8"));
return Base64Utils.encrypt(encoded);
}/**
* 公钥解密
* @param encodedContent
* @param keyPublicBase64
* @return
*/
public static String decryptByPublic(String encodedContent,String keyPublicBase64) throws Exception {
RSAPublicKey publicKey = obtainPublicKey(keyPublicBase64);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,publicKey);
return new String(cipher.doFinal(Base64Utils.decrypt(encodedContent)));
}private static RSAPublicKey obtainPublicKey(String keyPublicBase64) throws Exception {
byte[] keyBytes = Base64Utils.decrypt(keyPublicBase64);
return (RSAPublicKey) KeyFactory.getInstance(ALGORITHM)
.generatePublic(new X509EncodedKeySpec(keyBytes));
}/**
* 存储key到文件
* @param filePath 文件路径
* @param keyBase64base64编码的key
* @return true
*/
public static boolean storeKey(String filePath,String keyBase64) throws IOException {
File target = new File(filePath);
if (target.isDirectory())
throw new RuntimeException("filePath should not be a dir path");
if (!target.exists())
target.createNewFile();
Files.write(target.toPath(),keyBase64.getBytes());
return true;
}/**
* 从文件读取key
* @param filePath
* @return
* @throws IOException
*/
public static String readKey(String filePath) throws IOException {
return new String(Files.readAllBytes(new File(filePath).toPath()));
}
}
测试:
@Test
public void test() throws Exception {
String content = "aaabbbccc";
String[] generateKeys = RSAUtils.generateKeys();
String publicKey = generateKeys[0];
String privateKey = generateKeys[1];
System.out.println("原始内容:" + content);
System.out.println("pubicKey:" + publicKey);
System.out.println("privateKey:" + privateKey);
//私钥加密
String encoded = RSAUtils.encryptByPrivate(content, privateKey);
System.out.println("私钥加密后:" + encoded);
System.out.println("公钥解密后:" + RSAUtils.decryptByPublic(encoded,publicKey));
//公钥加密
String pubEncoded = RSAUtils.encryptByPublic(content,publicKey);
System.out.println("公钥加密后:" + pubEncoded);
System.out.println("私钥解密后:" + RSAUtils.decryptByPrivate(pubEncoded,privateKey));
//将key写入文件
RSAUtils.storeKey("id_rsa",privateKey);
//私钥
RSAUtils.storeKey("id_rsa.pub",publicKey);
//公钥
System.out.println("读取到公钥:" + RSAUtils.readKey("id_rsa.pub"));
System.out.println("读取到私钥:" + RSAUtils.readKey("id_rsa"));
}
【RSA加密java工具】
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)