From 61149b5a13bfec25bb0cfc67551973069ef3686a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Kr=C3=BCger?= Date: Sun, 17 Jun 2018 18:24:53 +0200 Subject: [PATCH] feat: add (rsa)pubKey.encrypt and (rsa)privKey.decrypt nodeJS only for now --- src/keys/rsa-browser.js | 8 ++++++++ src/keys/rsa-class.js | 8 ++++---- src/keys/rsa.js | 24 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/keys/rsa-browser.js b/src/keys/rsa-browser.js index d23bd0ba..27d16de3 100644 --- a/src/keys/rsa-browser.js +++ b/src/keys/rsa-browser.js @@ -115,3 +115,11 @@ function derivePublicFromPrivate (jwKey) { ['verify'] ) } + +exports.encrypt = function (key, bytes, cb) { + return cb(new Error('rsa.pubKey.encrypt() not yet implemented in the browser! (PRs welcome: https://github.com/libp2p/js-libp2p-crypto)')) +} + +exports.decrypt = function (key, bytes, cb) { + return cb(new Error('rsa.privKey.decrypt() not yet implemented in the browser! (PRs welcome: https://github.com/libp2p/js-libp2p-crypto)')) +} diff --git a/src/keys/rsa-class.js b/src/keys/rsa-class.js index afaea88e..548b07e6 100644 --- a/src/keys/rsa-class.js +++ b/src/keys/rsa-class.js @@ -30,8 +30,8 @@ class RsaPublicKey { }) } - encrypt (bytes) { - return this._key.encrypt(bytes, 'RSAES-PKCS1-V1_5') + encrypt (bytes, cb) { + crypto.encrypt(this._key, bytes, cb) } equals (key) { @@ -69,8 +69,8 @@ class RsaPrivateKey { return new RsaPublicKey(this._publicKey) } - decrypt (msg, callback) { - crypto.decrypt(this._key, msg, callback) + decrypt (bytes, cb) { + crypto.decrypt(this._key, bytes, cb) } marshal () { diff --git a/src/keys/rsa.js b/src/keys/rsa.js index 2da2678b..ec1202df 100644 --- a/src/keys/rsa.js +++ b/src/keys/rsa.js @@ -77,3 +77,27 @@ exports.hashAndVerify = function (key, sig, msg, callback) { callback(null, result) }) } + +exports.encrypt = function (key, bytes, cb) { + let res + + try { + res = crypto.publicEncrypt(jwkToPem(key), bytes) + } catch (err) { + return cb(err) + } + + return cb(null, res) +} + +exports.decrypt = function (key, bytes, cb) { + let res + + try { + res = crypto.privateDecrypt(jwkToPem(key), bytes) + } catch (err) { + return cb(err) + } + + return cb(null, res) +}