gpt4 book ai didi

java - 从 PKCS1 key 获取 RSA 公钥

转载 作者:行者123 更新时间:2023-11-30 10:00:15 25 4
gpt4 key购买 nike

我得到以下格式的公钥,我需要使用 java 使用此 key 加密一些数据

-----BEGIN RSA PUBLIC KEY----- MIGJAoGBAKDZp/3e4w1nJA/ImDMgaGowWfTnhlFkrvS86LBc6wh1/zBRt51/2F/o/ZzaA5mZ nx5YMlhDOf3vHyzyO4KzYlG8md3RQU7eKQQDxgRfW1v0f7WVQoC2Dxbupyz0JVV4jQStYUYW ifGsh76wI3rkzlq3F2Ea/+jqMxX/AZOO30tBAgMBAAE= -----END RSA PUBLIC KEY-----

最佳答案

您可以使用 BouncyCastle库来实现这一点。您的 key 在 PEM fromat 中。要阅读它,您可以使用 PEMParser :

private static PublicKey readPublicKey(String path) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
PEMParser pemParser = new PEMParser(new FileReader(path));
Object object = pemParser.readObject();
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) object;

RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);

RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
return kf.generatePublic(rsaSpec);
}

然后用这个 key 加密:

PublicKey publicKey = readPublicKey("src/main/resources/key.pem");

String dataToEncrypt = "myMessage";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(dataToEncrypt.getBytes(StandardCharsets.UTF_8));

测试版本:bcpkix-jdk15onbcprov-jdk15on .

关于java - 从 PKCS1 key 获取 RSA 公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com