使用给定公钥的RSA加密(在Java中) [英] RSA Encryption with given public key (in Java)

查看:202
本文介绍了使用给定公钥的RSA加密(在Java中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a Java sample how to do RSA Encryption with a given public key (I have it in base64 format, seems it is 1024 bit length).

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

Below is my code, but I have InvalidKeySpec exception.

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;

请给我样本,

推荐答案

这是我如何使用RSA公钥加密字符串。

Here's how I manage to encrypt a string with only a RSA public key.

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

First save the public key in PEM-format to the filename pubkey.pem

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

查找公共RSA密钥模数

Find the public RSA key modulus

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

查找公共RSA密钥指数

Find the public RSA key Exponent

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

然后将它们插入以下代码。

Then insert them into the following code.

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());

这篇关于使用给定公钥的RSA加密(在Java中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆