简体   繁体   English

在JavaScript中使用RSA加密的问题

[英]Issue using RSA encryption in javascript

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. 我正在使用一个当前正在Salesforce apex类(使用Crypto库)中进行加密的项目,该逻辑需要移到javascript文件中。 The node.js package I'm trying to use to do the encryption is node-rsa . 我试图用来加密的node.js包是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);

And here's the initial javascript implementation: 这是最初的javascript实现:

  var tmp = forge.util.decode64(pKey); var privateKey2 = new NodeRSA(tmp); payload = 'some payload var encrypted = key.encrypt(payload, 'base64'); 

The problem I'm having is that the line: var privateKey2 = new NodeRSA(tmp); 我遇到的问题是该行:var privateKey2 = new NodeRSA(tmp);

is causing the following error: Invalid PEM format 导致以下错误:无效的PEM格式

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在其示例中使用的私钥在密钥的开头和结尾处具有以下市场:---- BEGIN RSA PRIVATE KEY ----- ---- END RSA PRIVATE KEY -----

So I'm not sure if I have to somehow indicate to the node-rsa library that this key is in a different format. 因此,我不确定是否必须以某种方式向node-rsa库指示该密钥的格式不同。 Or maybe there's another RSA javascript library I could try using? 或者,也许还有另一个我可以尝试使用的RSA javascript库?

I left you a response for how to do this using forge here: https://github.com/digitalbazaar/forge/issues/150 我给你一个关于如何在这里使用伪造做到这一点的回应: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM