在JavaScript中使用RSA加密问题 [英] Issue using RSA encryption in javascript
问题描述
我正在使用一个目前正在使用salesforce apex类进行加密的项目(使用Crypto库),该逻辑需要被转移到一个javascript文件中。我正在尝试加密的node.js包是 node-rsa 。
I'm working with a project that currently is doing encryption in a salesforce apex class (using the Crypto library) and that logic needs to be moved into a javascript file. The node.js package I'm trying to use to do the encryption is node-rsa.
以下是当前存在于顶点的代码:
Here's the code that currently exists in apex:
String algName = 'RSA';
blob signature;
String signGen = '';
String pKey = 'MIIEvgIBADANBgkqhkiG<rest of key snipped>';
String payload = 'some payload';
blob privateKey = EncodingUtil.base64Decode(pKey);
blob input = Blob.valueOf(payload);
signature = Crypto.sign(algName, input, privateKey);
signGen = EncodingUtil.base64Encode(signature);
这是初始的javascript实现:
And here's the initial javascript implementation:
var tmp = forge.util.decode64(pKey);
var privateKey2 = new NodeRSA(tmp);
payload = 'some payload
var encrypted = key.encrypt(payload, 'base64');
我遇到的问题是行:
var privateKey2 = new NodeRSA(tmp);
The problem I'm having is that the line: var privateKey2 = new NodeRSA(tmp);
导致以下错误:
无效的PEM格式
is causing the following error: Invalid PEM format
node-rsa在其示例中使用的私钥在以下关键字的开始和结尾处具有市场:
---- BEGIN RSA私有密钥-----
- --- END RSA PRIVATE KEY -----
The private key that the node-rsa uses in their example has markets at the beginning and end of the key of: ---- BEGIN RSA PRIVATE KEY ----- ---- END RSA PRIVATE KEY -----
所以我不知道我是否必须以某种方式向node-rsa库指示这个键是不同的格式。或者也许还有另一个可以尝试使用的RSA JavaScript库?
So I'm not sure if I have to somehow indicate to the node-rsa library that this key is in a different format. Or maybe there's another RSA javascript library I could try using?
推荐答案
我给你留下了如何使用伪造这样做的回应: https://github.com/digitalbazaar/forge/issues/150
I left you a response for how to do this using forge here: https://github.com/digitalbazaar/forge/issues/150
var pkey = 'some base64-encoded private key';
var pkeyDer = forge.util.decode64(pkey);
var pkeyAsn1 = forge.asn1.fromDer(pkeyDer);
var privateKey = forge.pki.privateKeyFromAsn1(pkeyAsn1);
// above could be simplified if pkey is stored in standard PEM format, then just do this:
// var pkey = 'some private key in pem format';
// var privateKey = forge.pki.privateKeyFromPem(pkey);
var payload = 'some string payload';
var md = forge.md.sha1.create();
md.update(payload, 'utf8');
var signature = privateKey.sign(md);
var signature64 = forge.util.encode64(signature);
// signature64 is now a base64-encoded RSA signature on a SHA-1 digest
// using PKCS#1v1.5 padding... see the examples for other padding options if necessary
这篇关于在JavaScript中使用RSA加密问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!