java - 使用给定公钥的 RSA 加密(Java 中)

标签 java encryption rsa

我正在寻找一个 Java 示例,如何使用 给定的公钥 进行 RSA 加密(我有它的 base64 格式,似乎是 1024 位长度)。

下面是我的代码,但我有 InvalidKeySpec 异常。

String publicKey = "AJOnAeTfeU4K+do5QdBM2BQUhfrRI2rYf/Gk4a3jZJB2ewekgq2VgLNislBdql/glA39w0NjXZyTg0mW917JdUlHqKoQ9765pJc4aTjvX+3IxdFhteyO2jE3vKX1GgA3i3n6+sMBAJiT3ax57i68mbT+KAeP1AX9199aj2W4JZeP";
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] res = new Base64Encoder().decode(publicKey.getBytes());
X509EncodedKeySpec KeySpec = new X509EncodedKeySpec(res);
RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(KeySpec);

// here the exception occurs..

Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(input.getBytes());
return cipherData;

请给我 sample ,

最佳答案

以下是我设法仅使用 RSA 公钥加密字符串的方法。

首先将 PEM 格式的公钥保存到文件名 pubkey.pem

-----BEGIN PUBLIC KEY-----
AJOnAeTfeU4K+do5QdBM2BQUhfrRI2rYf/Gk4...
-----END PUBLIC KEY-----

查找公共(public) RSA key 模数

$ openssl rsa -pubin -in pubkey.pem -modulus -noout
Modulus=F56D...

找到公钥 RSA key 指数

$ openssl rsa -pubin -in pubkey.pem -text -noout
...
Exponent: 65537 (0x10001)

然后将它们插入到下面的代码中。

BigInteger modulus = new BigInteger("F56D...", 16);
BigInteger pubExp = new BigInteger("010001", 16);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] cipherData = cipher.doFinal(text.getBytes());

关于java - 使用给定公钥的 RSA 加密(Java 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5789685/

相关文章:

Java Makefile 替代方案

android - 无法从 KeyStore 检索私钥

cryptography - 自动解密文件的软件工具,其加密算法(和/或加密 key )未知?

c# - RSA公钥解密c#(powershell)

c# - OAEP RSA 参数与 RSACryptoServiceProvider.Encrypt

encryption - 分解 RSA 128 位 key 长度需要多长时间?

java - JVM 中老年代空间利用率

java - Java EE 技术中的数据访问控制

java - OpenCMS - 301 重定向

.net - 处理 CryptoStream 是否会刷新最终 block ?