简体   繁体   中英

Using RSA public key to encrypt a string

I've been working on my expressjs project, but now I've run into a dead end. I need to encrypt a string with a specific modulus and exponent. I should probably mention that I really don't know much about cryptography.

So for example I have these:

var mod = "99F496606F25ABC3FB26D21D58B1B9D7714B016E870B57EB3220DD60B55796A2E6A3CE65C59CCAD42AE8DCBD475125BF031DA2A66DAE0C5CBF5E5C445B89FE13C879D519FC9603C337226D23E230C986D6E057214A309BF7B954C899FF920690A8558056D95E69F932CF1BDAA55E90D871040C614D7CDB496741E16B8728F6E5B3CE9A39D76F0BF1E5CF244DC4B88117B4F45A48C103CEE5CCEE3E227B0C1D6DDB24E9FC140A05A4C6E094CA0D9512379964B0C1000F9E94F7071BE7F0B04178FE6B60222FA4896D5D7F4AECE29D83AD1167A0AE023C1B9F29265B290E695913D83E965335364014BB227284A6D2A825CE4A3D839431546CA6BEA98691E53CE9";
var exponent = "010001";

And if I've understood correctly I now need to create a public key with this? I looked up lots of nodejs modules for rsa encryption, but they all seem to require the key to be in PEM format. So I found this thread and used it like this:

rsaPublicKeyPem(new Buffer(mod).toString('base64'), new Buffer(exponent).toString('base64'));

Which gave me this:

-----BEGIN RSA PUBLIC KEY-----
MIICDAKCAgA5OUY0OTY2MDZGMjVBQkMzRkIyNkQyMUQ1OEIxQjlENzcxNEIwMTZF
ODcwQjU3RUIzMjIwREQ2MEI1NTc5NkEyRTZBM0NFNjVDNTlDQ0FENDJBRThEQ0JE
NDc1MTI1QkYwMzFEQTJBNjZEQUUwQzVDQkY1RTVDNDQ1Qjg5RkUxM0M4NzlENTE5
RkM5NjAzQzMzNzIyNkQyM0UyMzBDOTg2RDZFMDU3MjE0QTMwOUJGN0I5NTRDODk5
RkY5MjA2OTBBODU1ODA1NkQ5NUU2OUY5MzJDRjFCREFBNTVFOTBEODcxMDQwQzYx
NEQ3Q0RCNDk2NzQxRTE2Qjg3MjhGNkU1QjNDRTlBMzlENzZGMEJGMUU1Q0YyNDRE
QzRCODgxMTdCNEY0NUE0OEMxMDNDRUU1Q0NFRTNFMjI3QjBDMUQ2RERCMjRFOUZD
nMTQwQTA1QTRDNkUwOTRDQTBEOTUxMjM3OTk2NEIwQzEwMDBGOUU5NEY3MDcxQkU3
RjBCMDQxNzhGRTZCNjAyMjJGQTQ4OTZENUQ3RjRBRUNFMjlEODNBRDExNjdBMEFF
MDIzQzFCOUYyOTI2NUIyOTBFNjk1OTEzRDgzRTk2NTMzNTM2NDAxNEJCMjI3Mjg0
QTZEMkE4MjVDRTRBM0Q4Mzk0MzE1NDZDQTZCRUE5ODY5MUU1M0NFOQIGMDEwMDAx
-----END RSA PUBLIC KEY-----

Which I then tried to use with the ursa library

var key = ursa.createPublicKey(pem);

But it says that its not a public key. I also tried to use it with node-rsa but got pretty much the same error :/

Any ideas what I did wrong here or alternative methods?

Thanks, really appreciate it!

The PEM format is a Base64-encoded version of the DER format. You can use OpenSSL to help you build up DER, and then output PEM. I gave this answer to another question, which has some Ruby code that outputs a PEM-formatted file, given just the modulus and exponent. This should lead you to a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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