import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
public class RSAKeyGenerator {
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
// 目前看algorithm有三种,DiffieHellman、DSA、RSA
// 可参考:https://m.runoob.com/manual/jdk1.6/java.base/java/security/KeyPairGenerator.html
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 设置密钥长度,一般使用2048位
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 将公钥和私钥转换成Base64编码字符串保存到文件中
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
// 保存公钥和私钥到文件
Files.write(Paths.get("public_key.pem"), publicKeyString.getBytes());
Files.write(Paths.get("private_key.pem"), privateKeyString.getBytes());
}
}
JAVA生成RSA公私钥对代码记录
于 2023-10-10 15:55:42 首次发布