85 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-05-19 18:47:48 +02:00
'use strict'
2016-05-19 21:45:43 +02:00
const protobuf = require('protocol-buffers')
const pbm = protobuf(require('./crypto.proto'))
const c = require('./crypto')
2016-05-19 21:45:43 +02:00
exports.hmac = c.hmac
exports.aes = c.aes
exports.webcrypto = c.webcrypto
2016-05-19 18:47:48 +02:00
const keys = exports.keys = require('./keys')
const KEY_TYPES = ['rsa', 'ed25519']
exports.keyStretcher = require('./key-stretcher')
exports.generateEphemeralKeyPair = require('./ephemeral-keys')
2016-05-19 18:47:48 +02:00
// Generates a keypair of the given type and bitsize
exports.generateKeyPair = (type, bits, cb) => {
2016-05-19 20:18:31 +02:00
let key = keys[type.toLowerCase()]
if (!key) {
return cb(new Error('invalid or unsupported key type'))
2016-05-19 18:47:48 +02:00
}
key.generateKeyPair(bits, cb)
2016-05-19 18:47:48 +02:00
}
2016-05-19 21:45:43 +02:00
// Converts a protobuf serialized public key into its
// representative object
exports.unmarshalPublicKey = (buf) => {
const decoded = pbm.PublicKey.decode(buf)
switch (decoded.Type) {
case pbm.KeyType.RSA:
return keys.rsa.unmarshalRsaPublicKey(decoded.Data)
case pbm.KeyType.Ed25519:
return keys.ed25519.unmarshalEd25519PublicKey(decoded.Data)
2016-05-19 21:45:43 +02:00
default:
throw new Error('invalid or unsupported key type')
}
}
// Converts a public key object into a protobuf serialized public key
exports.marshalPublicKey = (key, type) => {
type = (type || 'rsa').toLowerCase()
if (KEY_TYPES.indexOf(type) < 0) {
2016-05-19 21:45:43 +02:00
throw new Error('invalid or unsupported key type')
}
return key.bytes
2016-05-19 21:45:43 +02:00
}
// Converts a protobuf serialized private key into its
// representative object
exports.unmarshalPrivateKey = (buf, callback) => {
2016-05-19 21:45:43 +02:00
const decoded = pbm.PrivateKey.decode(buf)
switch (decoded.Type) {
case pbm.KeyType.RSA:
return keys.rsa.unmarshalRsaPrivateKey(decoded.Data, callback)
case pbm.KeyType.Ed25519:
return keys.ed25519.unmarshalEd25519PrivateKey(decoded.Data, callback)
2016-05-19 21:45:43 +02:00
default:
callback(new Error('invalid or unsupported key type'))
2016-05-19 21:45:43 +02:00
}
}
// Converts a private key object into a protobuf serialized private key
exports.marshalPrivateKey = (key, type) => {
type = (type || 'rsa').toLowerCase()
if (KEY_TYPES.indexOf(type) < 0) {
2016-05-19 21:45:43 +02:00
throw new Error('invalid or unsupported key type')
}
return key.bytes
2016-05-19 21:45:43 +02:00
}
exports.randomBytes = (number) => {
if (!number || typeof number !== 'number') {
throw new Error('first argument must be a Number bigger than 0')
}
const buf = new Buffer(number)
c.rsa.getRandomValues(buf)
return buf
}