使用 openssl 生成 rsa 密钥
/*
# 1. 使用 linux 平台下的 openssl工具
$ openssl
# 2.生成私钥
OpenSSL> genrsa -out rsa_private_key.pem 2048
# 3. Java开发者需要将私钥转换成 PKCS8 格式
OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem
# 4. 生成公钥
OpenSSL> rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
# 5.退出 OpenSSL 程序
OpenSSL> exit
参考:https://opendocs.alipay.com/open/58/103242
*/
编写工具类 RSAUtil.java,分三类方法,详见 region xxx
:
- 加解密
- 签名
- 辅助方法
import javax.crypto.Cipher;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAUtil {
private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
// region encrypt-part
/**
* 公钥加密
*/
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainTextData);
} catch (Exception e) {
System.out.println("failed to encrypt, exception: [ " + e + " ]");
return new byte[0];
}
}
/**
* 私钥加密过程
*/
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(plainTextData);
} catch (Exception e) {
System.out.println("failed to encrypt, exception: [ " + e + " ]");
return new byte[0];
}
}
/**
* 私钥解密过程
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(cipherData);
} catch (Exception e) {
System.out.println("failed to decrypt, exception: [ " + e + " ]");
return new byte[0];
}
}
/**
* 公钥解密过程
*/
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(cipherData);
} catch (Exception e) {
System.out.println("failed to decrypt, exception: [ " + e + " ]");
return new byte[0];
}
}
// endregion
// region signature-part
private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
/*
* 用 RSA 私钥对信息生成数字签名
*/
public static String sign(String content, PrivateKey privateKey) {
try {
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(privateKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return byte2Hex(signature.sign());
} catch (Exception e) {
System.out.println("failed to sign, exception: [ " + e + " ]");
return null;
}
}
/**
* 校验数字签名
*/
public static boolean verify(String content, RSAPublicKey publicKey, String sign) throws Exception {
try {
java.security.Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(publicKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return signature.verify(hex2Bytes(sign));
} catch (Exception e) {
System.out.println("failed to verify, exception: [ " + e + " ]");
return false;
}
}
// endregion
// region regular-method
/**
* 从文件加载 PKCS8 格式的 RSA 公钥
*/
public static RSAPublicKey readPublicKeyFromFile(String path) throws Exception {
String publicKeyPEM = readFileFromClassPath(path);
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\r", "").replaceAll("\\n", "");
byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
}
/**
* 从类路径读取文件, fileName 是相对 resources/ 目录的文件路径
*/
private static String readFileFromClassPath(String fileName) {
try (InputStream inputStream = RSAUtil.class.getClassLoader().getResourceAsStream(fileName)) {
if (inputStream == null) {
throw new IOException("can't read file: " + fileName);
}
byte[] bs = new byte[512];
StringBuilder sb = new StringBuilder();
int len;
while ((len = inputStream.read(bs)) != -1) {
sb.append(new String(bs, 0, len, StandardCharsets.UTF_8));
}
return sb.toString();
} catch (Exception e) {
System.out.println("failed to read file content, + [ " + e.toString() + "]");
return "";
}
}
/**
* 从文件加载 RSA 私钥
*/
public static RSAPrivateKey readPrivateKeyFromFile(String path) throws Exception {
String privateKeyPEM = readFileFromClassPath(path);
privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\r", "").replaceAll("\\n", "");
byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyDER));
}
/**
* 字节数据转十六进制字符串(不带空格)
*/
public static String byte2Hex(byte[] srcBytes) {
StringBuilder hexRetSB = new StringBuilder();
for (byte b : srcBytes) {
String hexString = Integer.toHexString(0x00ff & b);
hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
}
return hexRetSB.toString();
}
/**
* 十六进制字符串(不带空格)转字节数组
*/
public static byte[] hex2Bytes(String source) {
byte[] sourceBytes = new byte[source.length() / 2];
for (int i = 0; i < sourceBytes.length; i++) {
sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
}
return sourceBytes;
}
// endregion
}
测试:
- 生成公私密钥,放在 resources/rsa/ 下;
- 使用上述工具类进行测试;
@Test
public void encrypt1() throws Exception {
RSAPublicKey publicKey = RSAUtil.readPublicKeyFromFile("rsa/public.txt");
RSAPrivateKey privateKey = RSAUtil.readPrivateKeyFromFile("rsa/private.txt");
String rawData = "今晚8点小树林见";
//公钥加密
byte[] content = RSAUtil.encrypt(publicKey, rawData.getBytes(StandardCharsets.UTF_8));
System.out.println(new String(content, StandardCharsets.UTF_8));
System.out.println("--------------------------");
//私钥解密
byte[] data = RSAUtil.decrypt(privateKey, content);
System.out.println(new String(data, StandardCharsets.UTF_8));
}
@Test
public void encrypt2() throws Exception {
RSAPublicKey publicKey = RSAUtil.readPublicKeyFromFile("rsa/public.txt");
RSAPrivateKey privateKey = RSAUtil.readPrivateKeyFromFile("rsa/private.txt");
String rawData = "今晚8点小树林见";
//私钥加密
byte[] content = RSAUtil.encrypt(privateKey, rawData.getBytes(StandardCharsets.UTF_8));
System.out.println(new String(content, StandardCharsets.UTF_8));
System.out.println("--------------------------");
//公钥解密
byte[] data = RSAUtil.decrypt(publicKey, content);
System.out.println(new String(data, StandardCharsets.UTF_8));
}
@Test
public void signature() throws Exception {
RSAPublicKey publicKey = RSAUtil.readPublicKeyFromFile("rsa/public.txt");
RSAPrivateKey privateKey = RSAUtil.readPrivateKeyFromFile("rsa/private.txt");
String data = "eugene";
String sign = RSAUtil.sign(data, privateKey);
System.out.println(RSAUtil.verify(data, publicKey, sign));
}
参考:
- https://www.cnblogs.com/scofi/p/6617394.html
- https://www.cnblogs.com/linjiqin/p/11133435.html