rsa java模数_使用模数和指数的RSA解密

My task: 我有加密(RSA)数据和公钥作为模数和指数 . 我必须写解密代码 .

My problem with it: 我的实现不起作用;)据我所知哲学很简单“开放文本”== rsa(public_key,rsa(private_key,“open text”)) Edit: Exactly my assumption was wrong (Assumption is mother of all fu..ups ;) ). It should be "open text" == rsa(private_key, rsa(public_key, "open text")) because in RSA, public key is used for encryption and private for decryption.

我假设我可以使用与加密期间使用的私钥不对应的公钥,因此对于测试我以这种方式创建了自己的密钥:

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

我使用命令获得公钥模数和指数:

openssl x509 -in server.crt -text

对于加密测试我正在使用代码

//Reads private key from file

//StringPasswordFinder is my tmp implementation of PasswordFinder

PEMReader pemReader = new PEMReader(new FileReader("/path/to/server.key"), new StringPasswordFinder());

KeyPair keyPair = (KeyPair) pemReader.readObject();

PrivateKey pk = keyPair.getPrivate();

//text for encryption

String openText = "openText";

//encryption

Cipher rsaCipher = Cipher.getInstance("RSA", "BC");

rsaCipher.init(Cipher.ENCRYPT_MODE, pk);

byte[] encrypted = rsaCipher.doFinal(openText.getBytes("utf-8"));

对于加密文本的解密,我使用代码

//modulus hex got using openssl

byte[] modulus = Hex.decodeHex("very long hex".toCharArray());

//exponent hex got using openssl

byte[] exponent = Hex.decodeHex("010001".toCharArray());

//initialization of rsa decryption engine

RSAEngine rsaEngine = new RSAEngine();

rsaEngine.init(false, new RSAKeyParameters(false, new BigInteger(modulus), new BigInteger(exponent)));

//input - encrypted stream

ByteArrayInputStream bais = new ByteArrayInputStream(encrypted);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

//reading blocks from the input stream and decrypting them

int bytesRead = 0;

byte[] block = new byte[rsaEngine.getInputBlockSize()];

while ((bytesRead = bais.read(block)) > -1) {

baos.write(rsaEngine.processBlock(block, 0, bytesRead));

}

//dispalying decrypted text

System.out.println(new String(baos.toByteArray(), "utf-8"));

毕竟显示的文字没有 . 任何人都可以告诉我我错在哪里吗?

Edit: Summing up this problem has no solution. Because it's not possible encrypt message using private key and later decrypt it using public one. At general I mixed up encryption with signing message and decryption with verification. Because during making signature private key is used and public is used during verification. Btw, MByD thx for important clue.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值