本文介绍了RSA Java加密和Node.js解密不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个系统,需要在javascript中生成RSA密钥对,然后将公钥存储在服务器端的数据库中(作为字符串),然后Java中的服务器端将加密一个字符串存储的公钥并将其发送到客户端,客户端将使用私钥解密字符串。

I have a system that requires a RSA keypair to be generated in javascript, have the public key then stored in a database at the server side (as a string), then the server side which is in Java will encrypt a string with the stored public key and send it to the client side which will decrypt the string with the private key.

我在客户端使用了一个browsified版本的node-rsa浏览器。

I'm using a browsified version of node-rsa on my client browser.

首先在客户端我生成一个密钥对并导出密钥,将它们存储为字符串

First at the client i generate a keypair and export the keys, storing them as strings

var NodeRSA = require('node-rsa');
var key = new NodeRSA({b: 1024});
key.exportKey("pkcs8-private");
key.exportKey("pkcs8-public-pem");

导出的私钥存储在客户端,公共服务器存储在服务器

The exported private key is stored at the client and the public at the server

接下来我使用java来加密收到公钥的字符串,所以我将pkcs8公钥解析为Java PublicKey对象。

Next i used java to encrypt a string with the public key received, so i parse the pkcs8 public key into a Java PublicKey object.

String pubKey = "<Retrieved pkcs8 public key>";
pubKey = pubKey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
byte[] keyBytes = Base64.decodeBase64(pubKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pk = kf.generatePublic(spec);

用它加密文本

byte[] cipherText;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
cipherText = cipher.doFinal("Hello World!".getBytes());
return Base64.encodeBase64String(cipherText);

哪个很好用,并返回一个像这样的Base64编码加密字符串

Which works nicely and returns me a Base64 encoded encrypted string like this

WTS1J2f4w5icsUOCtulyHDaBmB5lN7D8mnj0QWMDBkUGiPHkM8nHVx9pd0MtbQAQNasQS2X8kisLMYyEMPasFZtDH0zX1e8lNYaW0xMKsg++ge87f+95nl+TmxDy6S1m7Ce/n0wXno+0MbSv8YsJtsUcAleyyfQX2bxqX8u7Gjs=

然后我尝试在客户端解密它的字符串

Then i try to decrypt it the string at the client side

首先我重新导入node-rsa中存储的密钥

First i reimport the stored keys in node-rsa

var NodeRSA = require('node-rsa');
var key = new NodeRSA();
key.importKey("<exported private key string>","pkcs8-private");
key.importKey("<exported public key string>","pkcs8-public-pem");

然后我尝试解密Base64编码的加密字符串

Then i try to decrypt the Base64 encoded encrypted string

key.decrypt("<Base64 Encoded Encrypted>", 'utf-8');

这是问题发生的地方,javascript引发此错误

This is where the problem happens, javascript throws this error

有人能指出我在这里做错了吗?

Could anyone point out the mistake that I've made here please?

推荐答案

哦,我找到了解决方案。这是加密方法的一个区别。

Oh i found the solution. It was a difference in the encryption method.

我只需要用

Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");

而不是

Cipher.getInstance("RSA");

匹配node-rsa

to match node-rsa

这篇关于RSA Java加密和Node.js解密不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:17
查看更多