meshblu-encryption
Version:
Common encryption functions and patterns for Meshblu
97 lines (70 loc) • 2.48 kB
text/coffeescript
NodeRSA = require 'node-rsa'
_ = require 'lodash'
class Encryption
constructor: ({nodeRsa}) ->
= nodeRsa
toEnvironmentValue: =>
()
toDer: =>
.exportKey('private-der').toString 'base64'
toPublicEnvironmentValue: =>
()
toPublicDer: =>
.exportKey('public-der').toString 'base64'
toOldEnvironmentValue: =>
pem = .exportKey()
new Buffer(pem).toString 'base64'
toPublicOldEnvironmentValue: =>
pem = .exportKey 'public'
new Buffer(pem).toString 'base64'
toPem: () =>
.exportKey()
toPublicPem: () =>
.exportKey 'public'
authToCode: ({uuid, token}) =>
newAuth = "#{uuid}:#{token}"
verifier =
auth: newAuth
signature: newAuth
return new Buffer(JSON.stringify(verifier)).toString('base64')
codeToAuth: (code) =>
{auth, signature} = JSON.parse(new Buffer(code, 'base64').toString())
verified = auth, signature
[uuid, token] = auth.split ':'
return {uuid, token, verified}
encrypt: (options) =>
.encrypt(JSON.stringify options).toString 'base64'
decrypt: (options) =>
decryptedOptions = JSON.parse .decrypt(options)
sign: (options) =>
optionsString = JSON.stringify(options)
.sign(optionsString).toString 'base64'
verify: (options, signature) =>
optionsString = JSON.stringify options
signatureBuffer = new Buffer signature, 'base64'
.verify optionsString, signatureBuffer
: (pem) =>
nodeRsa = new NodeRSA pem
encryption = new Encryption {nodeRsa}
: (der) =>
keyBinary = new Buffer der, 'base64'
nodeRsa = new NodeRSA keyBinary, 'pkcs1-der'
encryption = new Encryption {nodeRsa}
: (oldEnv) =>
pem = new Buffer(oldEnv, 'base64').toString()
Encryption.fromPem pem
: (env) =>
Encryption.fromDer env
: (thing) =>
return new Encryption nodeRsa: thing if thing instanceof NodeRSA
return Encryption.fromPem thing if Encryption.isPem thing
return Encryption.fromOldEnvironmentValue thing if Encryption.isOldEnvironmentValue thing
thing
: (thing) =>
thing = _.trim thing
_.startsWith(thing, '-----') && _.endsWith(thing, '-----')
: (thing) =>
thing = _.trim thing
decoded = new Buffer(thing, 'base64').toString()
decoded
module.exports = Encryption