kjur / jsrsasign

The 'jsrsasign' (RSA-Sign JavaScript Library) is an opensource free cryptography library supporting RSA/RSAPSS/ECDSA/DSA signing/validation, ASN.1, PKCS#1/5/8 private/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES and JSON Web Signature/Token in pure JavaScript.
https://kjur.github.io/jsrsasign
Other
3.25k stars 645 forks source link

RSA encrypt Symmetric Key #514

Closed dumpvn closed 2 years ago

dumpvn commented 2 years ago

This is not an issue, but may be a feature / enhancement. (or maybe I am wrong).

one common use case is using RSA to encrypt a symmetric key. let's say I have an AES Key that need to be encrypted and send to the backend.

var rs = require('jsrsasign');
let pem = `-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA6vWQm3ZjytbSiGehLDmZ
JX7ms3F6iV+mmw6Q0IG7F9LNrnImFsNksitdB4v0XLwHd3koDUpJ32HmfSy1n+eU
EUIs/w+byv8prSyzwR6L6oLoge714UOQdAagvl9si8m6IRVzblpd8dA2mLw6FKYj
LY6lFpbevA3zoOHt2FsdSvTR2N6xVrd9tpFuQYMUJGCQJeEyEMbOqfwjWCq8jVse
kBzqhiJlXvYJl0UMag/yNfM6Ax4ztOXsnTgQxXa/9ZyAS0oNaYY8PX7SnWLafS/6
/F7I6YPNOzWJuRgUxBCafmvAiix/O0kj04RYuioOUv7dL/u42p2mwToxNLzy++hQ
6AG2U5tatn4/WjFQmZF1gJn+HO/EKueEnAf/tyDH6rgQQPXWeUdGxqaC7HrHbeAE
kRLCrweZI0Bu1NPhI9XIv9PZW8MC5SEpqubc2ZGdBoeIITjFp8B/2CIA8Udn5Vyj
UQw0d9YWG1S/jXN2Jsa6DYAiOMCBZqewHZzhqtABnLcdAgMBAAE=
-----END PUBLIC KEY-----`;
let aesKey = '297FB573BFE66DA13D6D45BFE9628ADF';
let keyObj = rs.KEYUTIL.getKey(pem);
let enc = rs.crypto.Cipher.encrypt(aesKey, keyObj);

I can not make it work with the backend, because the backend expects the key was encrypted as 0x29, 0x7F, 0xB5...(hex to byte array) however, the jsrsasign library encrypted it as 0x32 0x39 0x37.... (ASCII encoding of the string). Is there anyway I can specify a string as hex encoded instead of ascii encoded?

I tried to search for a solution for a day already, and I can pretty sure it is a limitation and so posting here instead of stackoverflow.

Thank you for your help!

kjur commented 2 years ago

I think "dataencrypt" and "datadecrypt" samples help you.

https://github.com/kjur/jsrsasign/blob/master/sample_node/dataencrypt https://github.com/kjur/jsrsasign/blob/master/sample_node/datadecrypt

They can encrypt and decrypt any text file including AES key string with public and private key.

dumpvn commented 2 years ago

that is actually not the problem (and so the solution). anyway, thank you for closing the issue.