copay/js/models/Passphrase.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

2014-04-30 12:30:25 -07:00
'use strict';
2014-09-02 18:49:19 -07:00
// 65.7% typed (by google's closure-compiler account)
2014-10-09 06:34:57 -07:00
var sjcl = require('../../lib/sjcl');
2014-09-02 18:49:19 -07:00
var preconditions = require('preconditions').instance();
var _ = require('underscore');
2014-08-26 09:02:02 -07:00
2014-09-02 18:49:19 -07:00
/**
* @desc
* Class for a Passphrase object, uses PBKDF2 to expand a password
*
* @constructor
* @param {object} config
* @param {string=} config.salt - 'mjuBtGybi/4=' by default
* @param {number=} config.iterations - 1000 by default
*/
2014-04-30 12:30:25 -07:00
function Passphrase(config) {
2014-09-02 18:49:19 -07:00
preconditions.checkArgument(!config || !config.salt || _.isString(config.salt));
preconditions.checkArgument(!config || !config.iterations || _.isNumber(config.iterations));
2014-06-06 12:34:30 -07:00
config = config || {};
this.salt = config.salt || 'mjuBtGybi/4=';
2014-10-15 11:02:14 -07:00
this.iterations = config.iterations;
2014-04-30 12:30:25 -07:00
};
2014-09-02 18:49:19 -07:00
/**
* @desc Generate a WordArray expanding a password
*
* @param {string} password - the password to expand
* @returns WordArray 512 bits with the expanded key generated from password
*/
2014-04-30 12:30:25 -07:00
Passphrase.prototype.get = function(password) {
2014-10-09 06:34:57 -07:00
var hash = sjcl.hash.sha256.hash(sjcl.hash.sha256.hash(password));
var salt = sjcl.codec.base64.toBits(this.salt);
var crypto2 = function(key, salt, iterations, length, alg) {
return sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2(key, salt, iterations, length * 8,
alg == 'sha1' ? function(key) {
return new sjcl.misc.hmac(key, sjcl.hash.sha1)
} : null
))
};
var key512 = crypto2(hash, salt, this.iterations, 64, 'sha1');
2014-04-30 12:30:25 -07:00
return key512;
};
2014-10-09 06:34:57 -07:00
2014-09-02 18:49:19 -07:00
/**
* @desc Generate a base64 encoded key
*
* @param {string} password - the password to expand
* @returns {string} 512 bits of a base64 encoded passphrase based on password
*/
2014-04-30 12:30:25 -07:00
Passphrase.prototype.getBase64 = function(password) {
var key512 = this.get(password);
2014-10-09 06:34:57 -07:00
var sbase64 = sjcl.codec.base64.fromBits(sjcl.codec.hex.toBits(key512));
return sbase64;
};
2014-09-02 18:49:19 -07:00
/**
* @desc Generate a base64 encoded key, without blocking
*
* @param {string} password - the password to expand
* @param {passphraseCallback} cb
*/
2014-06-06 12:34:30 -07:00
Passphrase.prototype.getBase64Async = function(password, cb) {
2014-05-07 14:48:56 -07:00
var self = this;
setTimeout(function() {
var ret = self.getBase64(password);
return cb(ret);
2014-09-02 18:49:19 -07:00
}, 0);
2014-05-07 14:48:56 -07:00
};
2014-04-30 12:30:25 -07:00
module.exports = Passphrase;