Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

Commit

Permalink
fix: browser rsa enc/dec
Browse files Browse the repository at this point in the history
  • Loading branch information
mkg20001 authored and jacobheun committed Oct 25, 2019
1 parent 9f747a1 commit b8e2414
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"keypair": "^1.0.1",
"libp2p-crypto-secp256k1": "~0.4.0",
"multihashing-async": "~0.7.0",
"node-forge": "~0.8.5",
"node-forge": "^0.9.1",
"pem-jwk": "^2.0.0",
"protons": "^1.0.1",
"rsa-pem-to-jwk": "^1.1.3",
Expand Down
35 changes: 31 additions & 4 deletions src/keys/rsa-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,33 @@ function derivePublicFromPrivate (jwKey) {
)
}

// bloody dark magic. webcrypto's why.

/*
Explanation:
- Convert JWK to PEM
- Load PEM with nodeForge
- Convert msg buffer to nodeForge buffer
- Convert resulting nodeForge buffer to buffer
*/

const forge = require('node-forge')
const pki = forge.pki
const jwkToPem = require('pem-jwk').jwk2pem
function convertKey (key, pub, msg, handle) {
const pem = jwkToPem(key)
const fkey = pki[pub ? 'publicKeyFromPem' : 'privateKeyFromPem'](pem)
const fmsg = forge.util.hexToBytes(Buffer.from(msg).toString('hex'))
const fomsg = handle(fmsg, fkey)
return Buffer.from(forge.util.bytesToHex(fomsg), 'hex')
}

exports.encrypt = async function (key, msg) {
key = Object.assign({}, key)
return convertKey(key, true, msg, (msg, key) => key.encrypt(msg))

/* key = Object.assign({}, key)
key.key_ops = ['encrypt']
return webcrypto.subtle.importKey(
Expand All @@ -140,11 +165,13 @@ exports.encrypt = async function (key, msg) {
publicKey,
Uint8Array.from(msg)
)
}).then((enc) => Buffer.from(enc))
}).then((enc) => Buffer.from(enc)) */
}

exports.decrypt = async function (key, msg) {
key = Object.assign({}, key)
return convertKey(key, false, msg, (msg, key) => key.decrypt(msg))

/* key = Object.assign({}, key)
key.key_ops = ['decrypt']
return webcrypto.subtle.importKey(
Expand All @@ -162,5 +189,5 @@ exports.decrypt = async function (key, msg) {
privateKey,
Uint8Array.from(msg)
)
}).then((dec) => Buffer.from(dec))
}).then((dec) => Buffer.from(dec)) */
}

0 comments on commit b8e2414

Please sign in to comment.