copay/js/models/Passphrase.js

76 lines
2.1 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-08-26 09:02:02 -07:00
var CryptoJS = CryptoJS || require('crypto-js');
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=';
this.iterations = config.iterations || 1000;
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) {
var hash = CryptoJS.SHA256(CryptoJS.SHA256(password));
var salt = CryptoJS.enc.Base64.parse(this.salt);
2014-06-06 12:34:30 -07:00
var key512 = CryptoJS.PBKDF2(hash, salt, {
keySize: 512 / 32,
iterations: this.iterations
});
2014-04-30 12:30:25 -07:00
return key512;
};
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);
var keyBase64 = key512.toString(CryptoJS.enc.Base64);
return keyBase64;
};
2014-09-02 18:49:19 -07:00
/**
* @desc Callback for the Passphrase#getBase64Async method
* @callback passphraseCallback
* @param {string} passphrase 512 bits of a base64 encoded passphrase based on password
*/
/**
* @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;