assets for gh-pages
This commit is contained in:
parent
fc2f9558a0
commit
e250c8cb44
|
@ -0,0 +1,249 @@
|
|||
(function (exports, TEST) {
|
||||
'use strict';
|
||||
|
||||
var crypto;
|
||||
var sha1Hmac = exports.sha1Hmac || function (key, bytes) {
|
||||
if (!crypto) { crypto = require('crypto'); }
|
||||
|
||||
var hmac = crypto.createHmac('sha1', new Buffer(key));
|
||||
// Update the HMAC with the byte array
|
||||
return hmac.update(new Buffer(bytes)).digest('hex');
|
||||
};
|
||||
|
||||
/**
|
||||
* convert an integer to a byte array
|
||||
* @param {Integer} num
|
||||
* @return {Array} bytes
|
||||
*/
|
||||
function intToBytes(num) {
|
||||
var bytes = [];
|
||||
|
||||
for(var i=7 ; i>=0 ; --i) {
|
||||
bytes[i] = num & (255);
|
||||
num = num >> 8;
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* convert a hex value to a byte array
|
||||
* @param {String} hex string of hex to convert to a byte array
|
||||
* @return {Array} bytes
|
||||
*/
|
||||
function hexToBytes(hex) {
|
||||
var bytes = [];
|
||||
for(var c = 0, C = hex.length; c < C; c += 2) {
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
var hotp = {};
|
||||
|
||||
/**
|
||||
* Generate a counter based One Time Password
|
||||
*
|
||||
* @return {String} the one time password
|
||||
*
|
||||
* Arguments:
|
||||
*
|
||||
* args
|
||||
* key - Key for the one time password. This should be unique and secret for
|
||||
* every user as this is the seed that is used to calculate the HMAC
|
||||
*
|
||||
* counter - Counter value. This should be stored by the application, must
|
||||
* be user specific, and be incremented for each request.
|
||||
*
|
||||
*/
|
||||
hotp.gen = function(key, opt) {
|
||||
key = key || '';
|
||||
opt = opt || {};
|
||||
var counter = opt.counter || 0;
|
||||
|
||||
// Create the byte array
|
||||
return sha1Hmac(key, intToBytes(counter)).then(function (digest) {
|
||||
// Get byte array
|
||||
var h = hexToBytes(digest);
|
||||
|
||||
// Truncate
|
||||
var offset = h[19] & 0xf;
|
||||
var v = (h[offset] & 0x7f) << 24 |
|
||||
(h[offset + 1] & 0xff) << 16 |
|
||||
(h[offset + 2] & 0xff) << 8 |
|
||||
(h[offset + 3] & 0xff);
|
||||
|
||||
v = (v % 1000000) + '';
|
||||
|
||||
return new Array(7-v.length).join('0') + v;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Check a One Time Password based on a counter.
|
||||
*
|
||||
* @return {Object} null if failure, { delta: # } on success
|
||||
* delta is the time step difference between the client and the server
|
||||
*
|
||||
* Arguments:
|
||||
*
|
||||
* args
|
||||
* key - Key for the one time password. This should be unique and secret for
|
||||
* every user as it is the seed used to calculate the HMAC
|
||||
*
|
||||
* token - Passcode to validate.
|
||||
*
|
||||
* window - The allowable margin for the counter. The function will check
|
||||
* 'W' codes in the future against the provided passcode. Note,
|
||||
* it is the calling applications responsibility to keep track of
|
||||
* 'W' and increment it for each password check, and also to adjust
|
||||
* it accordingly in the case where the client and server become
|
||||
* out of sync (second argument returns non zero).
|
||||
* E.g. if W = 100, and C = 5, this function will check the passcode
|
||||
* against all One Time Passcodes between 5 and 105.
|
||||
*
|
||||
* Default - 50
|
||||
*
|
||||
* counter - Counter value. This should be stored by the application, must
|
||||
* be user specific, and be incremented for each request.
|
||||
*
|
||||
*/
|
||||
hotp.verify = function(token, key, opt) {
|
||||
opt = opt || {};
|
||||
var window = opt.window || 50;
|
||||
var counter = opt.counter || 0;
|
||||
var i = counter - window;
|
||||
var len = counter + window;
|
||||
|
||||
// Now loop through from C to C + W to determine if there is
|
||||
// a correct code
|
||||
function check(t) {
|
||||
opt.counter = i + 1;
|
||||
|
||||
if (!t) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (i > len) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if(t === token) {
|
||||
// We have found a matching code, trigger callback
|
||||
// and pass offset
|
||||
return i;
|
||||
}
|
||||
|
||||
// TODO count 0, -1, 1, -2, 2, ... instead of -2, -1, 0, 1, ...
|
||||
i += 1;
|
||||
|
||||
return hotp.gen(key, opt).then(check);
|
||||
}
|
||||
|
||||
opt.counter = i;
|
||||
return hotp.gen(key, opt).then(check).then(function (i) {
|
||||
if('number' === typeof i) {
|
||||
return { delta: i - counter };
|
||||
}
|
||||
|
||||
// If we get to here then no codes have matched, return null
|
||||
return null;
|
||||
});
|
||||
};
|
||||
|
||||
var totp = {};
|
||||
|
||||
/**
|
||||
* Generate a time based One Time Password
|
||||
*
|
||||
* @return {String} the one time password
|
||||
*
|
||||
* Arguments:
|
||||
*
|
||||
* args
|
||||
* key - Key for the one time password. This should be unique and secret for
|
||||
* every user as it is the seed used to calculate the HMAC
|
||||
*
|
||||
* time - The time step of the counter. This must be the same for
|
||||
* every request and is used to calculat C.
|
||||
*
|
||||
* Default - 30
|
||||
*
|
||||
*/
|
||||
totp.gen = function(key, opt) {
|
||||
opt = opt || {};
|
||||
var time = opt.time || 30;
|
||||
var _t = Date.now();
|
||||
|
||||
// Time has been overwritten.
|
||||
if(opt._t) {
|
||||
if(!TEST) {
|
||||
console.warn('Overwriting time in non-test environment!');
|
||||
}
|
||||
_t = opt._t;
|
||||
}
|
||||
|
||||
// Determine the value of the counter, C
|
||||
// This is the number of time steps in seconds since T0
|
||||
opt.counter = Math.floor((_t / 1000) / time);
|
||||
|
||||
return hotp.gen(key, opt);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check a One Time Password based on a timer.
|
||||
*
|
||||
* @return {Object} null if failure, { delta: # } on success
|
||||
* delta is the time step difference between the client and the server
|
||||
*
|
||||
* Arguments:
|
||||
*
|
||||
* args
|
||||
* key - Key for the one time password. This should be unique and secret for
|
||||
* every user as it is the seed used to calculate the HMAC
|
||||
*
|
||||
* token - Passcode to validate.
|
||||
*
|
||||
* window - The allowable margin for the counter. The function will check
|
||||
* 'W' codes either side of the provided counter. Note,
|
||||
* it is the calling applications responsibility to keep track of
|
||||
* 'W' and increment it for each password check, and also to adjust
|
||||
* it accordingly in the case where the client and server become
|
||||
* out of sync (second argument returns non zero).
|
||||
* E.g. if W = 5, and C = 1000, this function will check the passcode
|
||||
* against all One Time Passcodes between 995 and 1005.
|
||||
*
|
||||
* Default - 6
|
||||
*
|
||||
* time - The time step of the counter. This must be the same for
|
||||
* every request and is used to calculate C.
|
||||
*
|
||||
* Default - 30
|
||||
*
|
||||
*/
|
||||
totp.verify = function(token, key, opt) {
|
||||
opt = opt || {};
|
||||
var time = opt.time || 30;
|
||||
var _t = Date.now();
|
||||
|
||||
// Time has been overwritten.
|
||||
if(opt._t) {
|
||||
if(!TEST) {
|
||||
console.warn('Overwriting time in non-test environment!');
|
||||
}
|
||||
_t = opt._t;
|
||||
}
|
||||
|
||||
// Determine the value of the counter, C
|
||||
// This is the number of time steps in seconds since T0
|
||||
opt.counter = Math.floor((_t / 1000) / time);
|
||||
|
||||
return hotp.verify(token, key, opt);
|
||||
};
|
||||
|
||||
exports.hotp = hotp;
|
||||
exports.totp = totp;
|
||||
}(
|
||||
'undefined' !== typeof window ? window : module.exports
|
||||
, 'undefined' !== typeof process ? process.env.NODE_ENV : false
|
||||
));
|
|
@ -0,0 +1,73 @@
|
|||
(function (exports) {
|
||||
'use strict';
|
||||
|
||||
exports.sha1Hmac = function (key, bytes) {
|
||||
if (!window.Unibabel) {
|
||||
throw new Error("Unibabel.js is required to convert between buffers and binary strings");
|
||||
}
|
||||
|
||||
if ('string' === typeof key) {
|
||||
throw new Error("use one of Unibabel.utf8ToBuffer(key), Unibabel.base64ToBuffer(key), or Unibabel.hexToBuffer(key) before passing to sha1Hmac(key, bytes)");
|
||||
}
|
||||
|
||||
var Unibabel = window.Unibabel;
|
||||
|
||||
if (window.crypto) {
|
||||
return window.crypto.subtle.importKey(
|
||||
"raw"
|
||||
, key
|
||||
, { name: "HMAC"
|
||||
, hash: { name: "SHA-1" }
|
||||
}
|
||||
, false
|
||||
, ["sign", "verify"]
|
||||
)
|
||||
/*
|
||||
return crypto.subtle.importKey(
|
||||
"jwk", //can be "jwk" or "raw"
|
||||
{ //this is an example jwk key, "raw" would be an ArrayBuffer
|
||||
kty: "oct",
|
||||
k: "Y0zt37HgOx-BY7SQjYVmrqhPkO44Ii2Jcb9yydUDPfE",
|
||||
alg: "HS256",
|
||||
ext: true,
|
||||
},
|
||||
{ //this is the algorithm options
|
||||
name: "HMAC",
|
||||
hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
|
||||
//length: 256, //optional, if you want your key length to differ from the hash function's block length
|
||||
},
|
||||
false, //whether the key is extractable (i.e. can be used in exportKey)
|
||||
["sign", "verify"] //can be any combination of "sign" and "verify"
|
||||
)
|
||||
*/
|
||||
.then(function (key) {
|
||||
return window.crypto.subtle.sign(
|
||||
{ name: "HMAC" }
|
||||
, key // from generateKey or importKey above
|
||||
, new Uint8Array(bytes) // ArrayBuffer of data you want to sign
|
||||
)
|
||||
.then(function(signature){
|
||||
// returns an ArrayBuffer containing the signature
|
||||
return Unibabel.bufferToHex(new Uint8Array(signature));
|
||||
});
|
||||
});
|
||||
}
|
||||
else if (window.forge) {
|
||||
var forge = window.forge;
|
||||
var hmac = forge.hmac.create();
|
||||
var digest;
|
||||
hmac.start('sha1', Unibabel.bufferToBinaryString(key));
|
||||
hmac.update(Unibabel.bufferToBinaryString(bytes));
|
||||
digest = hmac.digest().toHex();
|
||||
|
||||
return window.Promise.resolve(digest);
|
||||
}
|
||||
else {
|
||||
throw new Error("WebCrypto or forge.js is required to create a sha1 hmac");
|
||||
}
|
||||
};
|
||||
|
||||
}(
|
||||
'undefined' !== typeof window ? window : module.exports
|
||||
, 'undefined' !== typeof process ? process.env.NODE_ENV : false
|
||||
));
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,286 @@
|
|||
/**
|
||||
* Cipher base API.
|
||||
*
|
||||
* @author Dave Longley
|
||||
*
|
||||
* Copyright (c) 2010-2014 Digital Bazaar, Inc.
|
||||
*/
|
||||
(function() {
|
||||
/* ########## Begin module implementation ########## */
|
||||
function initModule(forge) {
|
||||
|
||||
forge.cipher = forge.cipher || {};
|
||||
|
||||
// registered algorithms
|
||||
forge.cipher.algorithms = forge.cipher.algorithms || {};
|
||||
|
||||
/**
|
||||
* Creates a cipher object that can be used to encrypt data using the given
|
||||
* algorithm and key. The algorithm may be provided as a string value for a
|
||||
* previously registered algorithm or it may be given as a cipher algorithm
|
||||
* API object.
|
||||
*
|
||||
* @param algorithm the algorithm to use, either a string or an algorithm API
|
||||
* object.
|
||||
* @param key the key to use, as a binary-encoded string of bytes or a
|
||||
* byte buffer.
|
||||
*
|
||||
* @return the cipher.
|
||||
*/
|
||||
forge.cipher.createCipher = function(algorithm, key) {
|
||||
var api = algorithm;
|
||||
if(typeof api === 'string') {
|
||||
api = forge.cipher.getAlgorithm(api);
|
||||
if(api) {
|
||||
api = api();
|
||||
}
|
||||
}
|
||||
if(!api) {
|
||||
throw new Error('Unsupported algorithm: ' + algorithm);
|
||||
}
|
||||
|
||||
// assume block cipher
|
||||
return new forge.cipher.BlockCipher({
|
||||
algorithm: api,
|
||||
key: key,
|
||||
decrypt: false
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a decipher object that can be used to decrypt data using the given
|
||||
* algorithm and key. The algorithm may be provided as a string value for a
|
||||
* previously registered algorithm or it may be given as a cipher algorithm
|
||||
* API object.
|
||||
*
|
||||
* @param algorithm the algorithm to use, either a string or an algorithm API
|
||||
* object.
|
||||
* @param key the key to use, as a binary-encoded string of bytes or a
|
||||
* byte buffer.
|
||||
*
|
||||
* @return the cipher.
|
||||
*/
|
||||
forge.cipher.createDecipher = function(algorithm, key) {
|
||||
var api = algorithm;
|
||||
if(typeof api === 'string') {
|
||||
api = forge.cipher.getAlgorithm(api);
|
||||
if(api) {
|
||||
api = api();
|
||||
}
|
||||
}
|
||||
if(!api) {
|
||||
throw new Error('Unsupported algorithm: ' + algorithm);
|
||||
}
|
||||
|
||||
// assume block cipher
|
||||
return new forge.cipher.BlockCipher({
|
||||
algorithm: api,
|
||||
key: key,
|
||||
decrypt: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Registers an algorithm by name. If the name was already registered, the
|
||||
* algorithm API object will be overwritten.
|
||||
*
|
||||
* @param name the name of the algorithm.
|
||||
* @param algorithm the algorithm API object.
|
||||
*/
|
||||
forge.cipher.registerAlgorithm = function(name, algorithm) {
|
||||
name = name.toUpperCase();
|
||||
forge.cipher.algorithms[name] = algorithm;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets a registered algorithm by name.
|
||||
*
|
||||
* @param name the name of the algorithm.
|
||||
*
|
||||
* @return the algorithm, if found, null if not.
|
||||
*/
|
||||
forge.cipher.getAlgorithm = function(name) {
|
||||
name = name.toUpperCase();
|
||||
if(name in forge.cipher.algorithms) {
|
||||
return forge.cipher.algorithms[name];
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
var BlockCipher = forge.cipher.BlockCipher = function(options) {
|
||||
this.algorithm = options.algorithm;
|
||||
this.mode = this.algorithm.mode;
|
||||
this.blockSize = this.mode.blockSize;
|
||||
this._finish = false;
|
||||
this._input = null;
|
||||
this.output = null;
|
||||
this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;
|
||||
this._decrypt = options.decrypt;
|
||||
this.algorithm.initialize(options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts or restarts the encryption or decryption process, whichever
|
||||
* was previously configured.
|
||||
*
|
||||
* For non-GCM mode, the IV may be a binary-encoded string of bytes, an array
|
||||
* of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in
|
||||
* bytes, then it must be Nb (16) bytes in length. If the IV is given in as
|
||||
* 32-bit integers, then it must be 4 integers long.
|
||||
*
|
||||
* Note: an IV is not required or used in ECB mode.
|
||||
*
|
||||
* For GCM-mode, the IV must be given as a binary-encoded string of bytes or
|
||||
* a byte buffer. The number of bytes should be 12 (96 bits) as recommended
|
||||
* by NIST SP-800-38D but another length may be given.
|
||||
*
|
||||
* @param options the options to use:
|
||||
* iv the initialization vector to use as a binary-encoded string of
|
||||
* bytes, null to reuse the last ciphered block from a previous
|
||||
* update() (this "residue" method is for legacy support only).
|
||||
* additionalData additional authentication data as a binary-encoded
|
||||
* string of bytes, for 'GCM' mode, (default: none).
|
||||
* tagLength desired length of authentication tag, in bits, for
|
||||
* 'GCM' mode (0-128, default: 128).
|
||||
* tag the authentication tag to check if decrypting, as a
|
||||
* binary-encoded string of bytes.
|
||||
* output the output the buffer to write to, null to create one.
|
||||
*/
|
||||
BlockCipher.prototype.start = function(options) {
|
||||
options = options || {};
|
||||
var opts = {};
|
||||
for(var key in options) {
|
||||
opts[key] = options[key];
|
||||
}
|
||||
opts.decrypt = this._decrypt;
|
||||
this._finish = false;
|
||||
this._input = forge.util.createBuffer();
|
||||
this.output = options.output || forge.util.createBuffer();
|
||||
this.mode.start(opts);
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the next block according to the cipher mode.
|
||||
*
|
||||
* @param input the buffer to read from.
|
||||
*/
|
||||
BlockCipher.prototype.update = function(input) {
|
||||
if(input) {
|
||||
// input given, so empty it into the input buffer
|
||||
this._input.putBuffer(input);
|
||||
}
|
||||
|
||||
// do cipher operation until it needs more input and not finished
|
||||
while(!this._op.call(this.mode, this._input, this.output, this._finish) &&
|
||||
!this._finish) {}
|
||||
|
||||
// free consumed memory from input buffer
|
||||
this._input.compact();
|
||||
};
|
||||
|
||||
/**
|
||||
* Finishes encrypting or decrypting.
|
||||
*
|
||||
* @param pad a padding function to use in CBC mode, null for default,
|
||||
* signature(blockSize, buffer, decrypt).
|
||||
*
|
||||
* @return true if successful, false on error.
|
||||
*/
|
||||
BlockCipher.prototype.finish = function(pad) {
|
||||
// backwards-compatibility w/deprecated padding API
|
||||
// Note: will overwrite padding functions even after another start() call
|
||||
if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {
|
||||
this.mode.pad = function(input) {
|
||||
return pad(this.blockSize, input, false);
|
||||
};
|
||||
this.mode.unpad = function(output) {
|
||||
return pad(this.blockSize, output, true);
|
||||
};
|
||||
}
|
||||
|
||||
// build options for padding and afterFinish functions
|
||||
var options = {};
|
||||
options.decrypt = this._decrypt;
|
||||
|
||||
// get # of bytes that won't fill a block
|
||||
options.overflow = this._input.length() % this.blockSize;
|
||||
|
||||
if(!this._decrypt && this.mode.pad) {
|
||||
if(!this.mode.pad(this._input, options)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// do final update
|
||||
this._finish = true;
|
||||
this.update();
|
||||
|
||||
if(this._decrypt && this.mode.unpad) {
|
||||
if(!this.mode.unpad(this.output, options)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(this.mode.afterFinish) {
|
||||
if(!this.mode.afterFinish(this.output, options)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
} // end module implementation
|
||||
|
||||
/* ########## Begin module wrapper ########## */
|
||||
var name = 'cipher';
|
||||
if(typeof define !== 'function') {
|
||||
// NodeJS -> AMD
|
||||
if(typeof module === 'object' && module.exports) {
|
||||
var nodeJS = true;
|
||||
define = function(ids, factory) {
|
||||
factory(require, module);
|
||||
};
|
||||
} else {
|
||||
// <script>
|
||||
if(typeof forge === 'undefined') {
|
||||
forge = {};
|
||||
}
|
||||
return initModule(forge);
|
||||
}
|
||||
}
|
||||
// AMD
|
||||
var deps;
|
||||
var defineFunc = function(require, module) {
|
||||
module.exports = function(forge) {
|
||||
var mods = deps.map(function(dep) {
|
||||
return require(dep);
|
||||
}).concat(initModule);
|
||||
// handle circular dependencies
|
||||
forge = forge || {};
|
||||
forge.defined = forge.defined || {};
|
||||
if(forge.defined[name]) {
|
||||
return forge[name];
|
||||
}
|
||||
forge.defined[name] = true;
|
||||
for(var i = 0; i < mods.length; ++i) {
|
||||
mods[i](forge);
|
||||
}
|
||||
return forge[name];
|
||||
};
|
||||
};
|
||||
var tmpDefine = define;
|
||||
define = function(ids, factory) {
|
||||
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
|
||||
if(nodeJS) {
|
||||
delete define;
|
||||
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
}
|
||||
define = tmpDefine;
|
||||
return define.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
};
|
||||
define(['require', 'module', './util'], function() {
|
||||
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
});
|
||||
})();
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,204 @@
|
|||
/**
|
||||
* Hash-based Message Authentication Code implementation. Requires a message
|
||||
* digest object that can be obtained, for example, from forge.md.sha1 or
|
||||
* forge.md.md5.
|
||||
*
|
||||
* @author Dave Longley
|
||||
*
|
||||
* Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.
|
||||
*/
|
||||
(function() {
|
||||
/* ########## Begin module implementation ########## */
|
||||
function initModule(forge) {
|
||||
|
||||
/* HMAC API */
|
||||
var hmac = forge.hmac = forge.hmac || {};
|
||||
|
||||
/**
|
||||
* Creates an HMAC object that uses the given message digest object.
|
||||
*
|
||||
* @return an HMAC object.
|
||||
*/
|
||||
hmac.create = function() {
|
||||
// the hmac key to use
|
||||
var _key = null;
|
||||
|
||||
// the message digest to use
|
||||
var _md = null;
|
||||
|
||||
// the inner padding
|
||||
var _ipadding = null;
|
||||
|
||||
// the outer padding
|
||||
var _opadding = null;
|
||||
|
||||
// hmac context
|
||||
var ctx = {};
|
||||
|
||||
/**
|
||||
* Starts or restarts the HMAC with the given key and message digest.
|
||||
*
|
||||
* @param md the message digest to use, null to reuse the previous one,
|
||||
* a string to use builtin 'sha1', 'md5', 'sha256'.
|
||||
* @param key the key to use as a string, array of bytes, byte buffer,
|
||||
* or null to reuse the previous key.
|
||||
*/
|
||||
ctx.start = function(md, key) {
|
||||
console.log('forge key start', typeof key, Object.prototype.toString.apply(key));
|
||||
|
||||
if(md !== null) {
|
||||
if(typeof md === 'string') {
|
||||
// create builtin message digest
|
||||
md = md.toLowerCase();
|
||||
if(md in forge.md.algorithms) {
|
||||
_md = forge.md.algorithms[md].create();
|
||||
} else {
|
||||
throw new Error('Unknown hash algorithm "' + md + '"');
|
||||
}
|
||||
} else {
|
||||
// store message digest
|
||||
_md = md;
|
||||
}
|
||||
}
|
||||
|
||||
if(key === null) {
|
||||
// reuse previous key
|
||||
key = _key;
|
||||
} else {
|
||||
if(typeof key === 'string') {
|
||||
// convert string into byte buffer
|
||||
key = forge.util.createBuffer(key);
|
||||
} else if(forge.util.isArray(key)) {
|
||||
// convert byte array into byte buffer
|
||||
var tmp = key;
|
||||
key = forge.util.createBuffer();
|
||||
for(var i = 0; i < tmp.length; ++i) {
|
||||
key.putByte(tmp[i]);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('forge key', key);
|
||||
|
||||
// if key is longer than blocksize, hash it
|
||||
var keylen = key.length();
|
||||
if(keylen > _md.blockLength) {
|
||||
_md.start();
|
||||
_md.update(key.bytes());
|
||||
key = _md.digest();
|
||||
}
|
||||
|
||||
// mix key into inner and outer padding
|
||||
// ipadding = [0x36 * blocksize] ^ key
|
||||
// opadding = [0x5C * blocksize] ^ key
|
||||
_ipadding = forge.util.createBuffer();
|
||||
_opadding = forge.util.createBuffer();
|
||||
keylen = key.length();
|
||||
for(var i = 0; i < keylen; ++i) {
|
||||
var tmp = key.at(i);
|
||||
_ipadding.putByte(0x36 ^ tmp);
|
||||
_opadding.putByte(0x5C ^ tmp);
|
||||
}
|
||||
|
||||
// if key is shorter than blocksize, add additional padding
|
||||
if(keylen < _md.blockLength) {
|
||||
var tmp = _md.blockLength - keylen;
|
||||
for(var i = 0; i < tmp; ++i) {
|
||||
_ipadding.putByte(0x36);
|
||||
_opadding.putByte(0x5C);
|
||||
}
|
||||
}
|
||||
_key = key;
|
||||
_ipadding = _ipadding.bytes();
|
||||
_opadding = _opadding.bytes();
|
||||
}
|
||||
|
||||
// digest is done like so: hash(opadding | hash(ipadding | message))
|
||||
|
||||
// prepare to do inner hash
|
||||
// hash(ipadding | message)
|
||||
_md.start();
|
||||
_md.update(_ipadding);
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the HMAC with the given message bytes.
|
||||
*
|
||||
* @param bytes the bytes to update with.
|
||||
*/
|
||||
ctx.update = function(bytes) {
|
||||
_md.update(bytes);
|
||||
};
|
||||
|
||||
/**
|
||||
* Produces the Message Authentication Code (MAC).
|
||||
*
|
||||
* @return a byte buffer containing the digest value.
|
||||
*/
|
||||
ctx.getMac = function() {
|
||||
// digest is done like so: hash(opadding | hash(ipadding | message))
|
||||
// here we do the outer hashing
|
||||
var inner = _md.digest().bytes();
|
||||
_md.start();
|
||||
_md.update(_opadding);
|
||||
_md.update(inner);
|
||||
return _md.digest();
|
||||
};
|
||||
// alias for getMac
|
||||
ctx.digest = ctx.getMac;
|
||||
|
||||
return ctx;
|
||||
};
|
||||
|
||||
} // end module implementation
|
||||
|
||||
/* ########## Begin module wrapper ########## */
|
||||
var name = 'hmac';
|
||||
if(typeof define !== 'function') {
|
||||
// NodeJS -> AMD
|
||||
if(typeof module === 'object' && module.exports) {
|
||||
var nodeJS = true;
|
||||
define = function(ids, factory) {
|
||||
factory(require, module);
|
||||
};
|
||||
} else {
|
||||
// <script>
|
||||
if(typeof forge === 'undefined') {
|
||||
forge = {};
|
||||
}
|
||||
return initModule(forge);
|
||||
}
|
||||
}
|
||||
// AMD
|
||||
var deps;
|
||||
var defineFunc = function(require, module) {
|
||||
module.exports = function(forge) {
|
||||
var mods = deps.map(function(dep) {
|
||||
return require(dep);
|
||||
}).concat(initModule);
|
||||
// handle circular dependencies
|
||||
forge = forge || {};
|
||||
forge.defined = forge.defined || {};
|
||||
if(forge.defined[name]) {
|
||||
return forge[name];
|
||||
}
|
||||
forge.defined[name] = true;
|
||||
for(var i = 0; i < mods.length; ++i) {
|
||||
mods[i](forge);
|
||||
}
|
||||
return forge[name];
|
||||
};
|
||||
};
|
||||
var tmpDefine = define;
|
||||
define = function(ids, factory) {
|
||||
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
|
||||
if(nodeJS) {
|
||||
delete define;
|
||||
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
}
|
||||
define = tmpDefine;
|
||||
return define.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
};
|
||||
define(['require', 'module', './md', './util'], function() {
|
||||
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
});
|
||||
})();
|
|
@ -0,0 +1,458 @@
|
|||
/**
|
||||
* A javascript implementation of a cryptographically-secure
|
||||
* Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed
|
||||
* here though the use of SHA-256 is not enforced; when generating an
|
||||
* a PRNG context, the hashing algorithm and block cipher used for
|
||||
* the generator are specified via a plugin.
|
||||
*
|
||||
* @author Dave Longley
|
||||
*
|
||||
* Copyright (c) 2010-2014 Digital Bazaar, Inc.
|
||||
*/
|
||||
(function() {
|
||||
/* ########## Begin module implementation ########## */
|
||||
function initModule(forge) {
|
||||
|
||||
var _nodejs = (
|
||||
typeof process !== 'undefined' && process.versions && process.versions.node);
|
||||
var _crypto = null;
|
||||
if(!forge.disableNativeCode && _nodejs && !process.versions['node-webkit']) {
|
||||
_crypto = require('crypto');
|
||||
}
|
||||
|
||||
/* PRNG API */
|
||||
var prng = forge.prng = forge.prng || {};
|
||||
|
||||
/**
|
||||
* Creates a new PRNG context.
|
||||
*
|
||||
* A PRNG plugin must be passed in that will provide:
|
||||
*
|
||||
* 1. A function that initializes the key and seed of a PRNG context. It
|
||||
* will be given a 16 byte key and a 16 byte seed. Any key expansion
|
||||
* or transformation of the seed from a byte string into an array of
|
||||
* integers (or similar) should be performed.
|
||||
* 2. The cryptographic function used by the generator. It takes a key and
|
||||
* a seed.
|
||||
* 3. A seed increment function. It takes the seed and returns seed + 1.
|
||||
* 4. An api to create a message digest.
|
||||
*
|
||||
* For an example, see random.js.
|
||||
*
|
||||
* @param plugin the PRNG plugin to use.
|
||||
*/
|
||||
prng.create = function(plugin) {
|
||||
var ctx = {
|
||||
plugin: plugin,
|
||||
key: null,
|
||||
seed: null,
|
||||
time: null,
|
||||
// number of reseeds so far
|
||||
reseeds: 0,
|
||||
// amount of data generated so far
|
||||
generated: 0
|
||||
};
|
||||
|
||||
// create 32 entropy pools (each is a message digest)
|
||||
var md = plugin.md;
|
||||
var pools = new Array(32);
|
||||
for(var i = 0; i < 32; ++i) {
|
||||
pools[i] = md.create();
|
||||
}
|
||||
ctx.pools = pools;
|
||||
|
||||
// entropy pools are written to cyclically, starting at index 0
|
||||
ctx.pool = 0;
|
||||
|
||||
/**
|
||||
* Generates random bytes. The bytes may be generated synchronously or
|
||||
* asynchronously. Web workers must use the asynchronous interface or
|
||||
* else the behavior is undefined.
|
||||
*
|
||||
* @param count the number of random bytes to generate.
|
||||
* @param [callback(err, bytes)] called once the operation completes.
|
||||
*
|
||||
* @return count random bytes as a string.
|
||||
*/
|
||||
ctx.generate = function(count, callback) {
|
||||
// do synchronously
|
||||
if(!callback) {
|
||||
return ctx.generateSync(count);
|
||||
}
|
||||
|
||||
// simple generator using counter-based CBC
|
||||
var cipher = ctx.plugin.cipher;
|
||||
var increment = ctx.plugin.increment;
|
||||
var formatKey = ctx.plugin.formatKey;
|
||||
var formatSeed = ctx.plugin.formatSeed;
|
||||
var b = forge.util.createBuffer();
|
||||
|
||||
// reset key for every request
|
||||
ctx.key = null;
|
||||
|
||||
generate();
|
||||
|
||||
function generate(err) {
|
||||
if(err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// sufficient bytes generated
|
||||
if(b.length() >= count) {
|
||||
return callback(null, b.getBytes(count));
|
||||
}
|
||||
|
||||
// if amount of data generated is greater than 1 MiB, trigger reseed
|
||||
if(ctx.generated > 0xfffff) {
|
||||
ctx.key = null;
|
||||
}
|
||||
|
||||
if(ctx.key === null) {
|
||||
// prevent stack overflow
|
||||
return forge.util.nextTick(function() {
|
||||
_reseed(generate);
|
||||
});
|
||||
}
|
||||
|
||||
// generate the random bytes
|
||||
var bytes = cipher(ctx.key, ctx.seed);
|
||||
ctx.generated += bytes.length;
|
||||
b.putBytes(bytes);
|
||||
|
||||
// generate bytes for a new key and seed
|
||||
ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
|
||||
ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
|
||||
|
||||
forge.util.setImmediate(generate);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates random bytes synchronously.
|
||||
*
|
||||
* @param count the number of random bytes to generate.
|
||||
*
|
||||
* @return count random bytes as a string.
|
||||
*/
|
||||
ctx.generateSync = function(count) {
|
||||
// simple generator using counter-based CBC
|
||||
var cipher = ctx.plugin.cipher;
|
||||
var increment = ctx.plugin.increment;
|
||||
var formatKey = ctx.plugin.formatKey;
|
||||
var formatSeed = ctx.plugin.formatSeed;
|
||||
|
||||
// reset key for every request
|
||||
ctx.key = null;
|
||||
|
||||
var b = forge.util.createBuffer();
|
||||
while(b.length() < count) {
|
||||
// if amount of data generated is greater than 1 MiB, trigger reseed
|
||||
if(ctx.generated > 0xfffff) {
|
||||
ctx.key = null;
|
||||
}
|
||||
|
||||
if(ctx.key === null) {
|
||||
_reseedSync();
|
||||
}
|
||||
|
||||
// generate the random bytes
|
||||
var bytes = cipher(ctx.key, ctx.seed);
|
||||
ctx.generated += bytes.length;
|
||||
b.putBytes(bytes);
|
||||
|
||||
// generate bytes for a new key and seed
|
||||
ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
|
||||
ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
|
||||
}
|
||||
|
||||
return b.getBytes(count);
|
||||
};
|
||||
|
||||
/**
|
||||
* Private function that asynchronously reseeds a generator.
|
||||
*
|
||||
* @param callback(err) called once the operation completes.
|
||||
*/
|
||||
function _reseed(callback) {
|
||||
if(ctx.pools[0].messageLength >= 32) {
|
||||
_seed();
|
||||
return callback();
|
||||
}
|
||||
// not enough seed data...
|
||||
var needed = (32 - ctx.pools[0].messageLength) << 5;
|
||||
ctx.seedFile(needed, function(err, bytes) {
|
||||
if(err) {
|
||||
return callback(err);
|
||||
}
|
||||
ctx.collect(bytes);
|
||||
_seed();
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Private function that synchronously reseeds a generator.
|
||||
*/
|
||||
function _reseedSync() {
|
||||
if(ctx.pools[0].messageLength >= 32) {
|
||||
return _seed();
|
||||
}
|
||||
// not enough seed data...
|
||||
var needed = (32 - ctx.pools[0].messageLength) << 5;
|
||||
ctx.collect(ctx.seedFileSync(needed));
|
||||
_seed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Private function that seeds a generator once enough bytes are available.
|
||||
*/
|
||||
function _seed() {
|
||||
// create a plugin-based message digest
|
||||
var md = ctx.plugin.md.create();
|
||||
|
||||
// digest pool 0's entropy and restart it
|
||||
md.update(ctx.pools[0].digest().getBytes());
|
||||
ctx.pools[0].start();
|
||||
|
||||
// digest the entropy of other pools whose index k meet the
|
||||
// condition '2^k mod n == 0' where n is the number of reseeds
|
||||
var k = 1;
|
||||
for(var i = 1; i < 32; ++i) {
|
||||
// prevent signed numbers from being used
|
||||
k = (k === 31) ? 0x80000000 : (k << 2);
|
||||
if(k % ctx.reseeds === 0) {
|
||||
md.update(ctx.pools[i].digest().getBytes());
|
||||
ctx.pools[i].start();
|
||||
}
|
||||
}
|
||||
|
||||
// get digest for key bytes and iterate again for seed bytes
|
||||
var keyBytes = md.digest().getBytes();
|
||||
md.start();
|
||||
md.update(keyBytes);
|
||||
var seedBytes = md.digest().getBytes();
|
||||
|
||||
// update
|
||||
ctx.key = ctx.plugin.formatKey(keyBytes);
|
||||
ctx.seed = ctx.plugin.formatSeed(seedBytes);
|
||||
ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
|
||||
ctx.generated = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in default seedFile. This seedFile is used when entropy
|
||||
* is needed immediately.
|
||||
*
|
||||
* @param needed the number of bytes that are needed.
|
||||
*
|
||||
* @return the random bytes.
|
||||
*/
|
||||
function defaultSeedFile(needed) {
|
||||
// use window.crypto.getRandomValues strong source of entropy if available
|
||||
var getRandomValues = null;
|
||||
if(typeof window !== 'undefined') {
|
||||
var _crypto = window.crypto || window.msCrypto;
|
||||
if(_crypto && _crypto.getRandomValues) {
|
||||
getRandomValues = function(arr) {
|
||||
return _crypto.getRandomValues(arr);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var b = forge.util.createBuffer();
|
||||
if(getRandomValues) {
|
||||
while(b.length() < needed) {
|
||||
// max byte length is 65536 before QuotaExceededError is thrown
|
||||
// http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues
|
||||
var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);
|
||||
var entropy = new Uint32Array(Math.floor(count));
|
||||
try {
|
||||
getRandomValues(entropy);
|
||||
for(var i = 0; i < entropy.length; ++i) {
|
||||
b.putInt32(entropy[i]);
|
||||
}
|
||||
} catch(e) {
|
||||
/* only ignore QuotaExceededError */
|
||||
if(!(typeof QuotaExceededError !== 'undefined' &&
|
||||
e instanceof QuotaExceededError)) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// be sad and add some weak random data
|
||||
if(b.length() < needed) {
|
||||
/* Draws from Park-Miller "minimal standard" 31 bit PRNG,
|
||||
implemented with David G. Carta's optimization: with 32 bit math
|
||||
and without division (Public Domain). */
|
||||
var hi, lo, next;
|
||||
var seed = Math.floor(Math.random() * 0x010000);
|
||||
while(b.length() < needed) {
|
||||
lo = 16807 * (seed & 0xFFFF);
|
||||
hi = 16807 * (seed >> 16);
|
||||
lo += (hi & 0x7FFF) << 16;
|
||||
lo += hi >> 15;
|
||||
lo = (lo & 0x7FFFFFFF) + (lo >> 31);
|
||||
seed = lo & 0xFFFFFFFF;
|
||||
|
||||
// consume lower 3 bytes of seed
|
||||
for(var i = 0; i < 3; ++i) {
|
||||
// throw in more pseudo random
|
||||
next = seed >>> (i << 3);
|
||||
next ^= Math.floor(Math.random() * 0x0100);
|
||||
b.putByte(String.fromCharCode(next & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return b.getBytes(needed);
|
||||
}
|
||||
// initialize seed file APIs
|
||||
if(_crypto) {
|
||||
// use nodejs async API
|
||||
ctx.seedFile = function(needed, callback) {
|
||||
_crypto.randomBytes(needed, function(err, bytes) {
|
||||
if(err) {
|
||||
return callback(err);
|
||||
}
|
||||
callback(null, bytes.toString());
|
||||
});
|
||||
};
|
||||
// use nodejs sync API
|
||||
ctx.seedFileSync = function(needed) {
|
||||
return _crypto.randomBytes(needed).toString();
|
||||
};
|
||||
} else {
|
||||
ctx.seedFile = function(needed, callback) {
|
||||
try {
|
||||
callback(null, defaultSeedFile(needed));
|
||||
} catch(e) {
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
ctx.seedFileSync = defaultSeedFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds entropy to a prng ctx's accumulator.
|
||||
*
|
||||
* @param bytes the bytes of entropy as a string.
|
||||
*/
|
||||
ctx.collect = function(bytes) {
|
||||
// iterate over pools distributing entropy cyclically
|
||||
var count = bytes.length;
|
||||
for(var i = 0; i < count; ++i) {
|
||||
ctx.pools[ctx.pool].update(bytes.substr(i, 1));
|
||||
ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Collects an integer of n bits.
|
||||
*
|
||||
* @param i the integer entropy.
|
||||
* @param n the number of bits in the integer.
|
||||
*/
|
||||
ctx.collectInt = function(i, n) {
|
||||
var bytes = '';
|
||||
for(var x = 0; x < n; x += 8) {
|
||||
bytes += String.fromCharCode((i >> x) & 0xFF);
|
||||
}
|
||||
ctx.collect(bytes);
|
||||
};
|
||||
|
||||
/**
|
||||
* Registers a Web Worker to receive immediate entropy from the main thread.
|
||||
* This method is required until Web Workers can access the native crypto
|
||||
* API. This method should be called twice for each created worker, once in
|
||||
* the main thread, and once in the worker itself.
|
||||
*
|
||||
* @param worker the worker to register.
|
||||
*/
|
||||
ctx.registerWorker = function(worker) {
|
||||
// worker receives random bytes
|
||||
if(worker === self) {
|
||||
ctx.seedFile = function(needed, callback) {
|
||||
function listener(e) {
|
||||
var data = e.data;
|
||||
if(data.forge && data.forge.prng) {
|
||||
self.removeEventListener('message', listener);
|
||||
callback(data.forge.prng.err, data.forge.prng.bytes);
|
||||
}
|
||||
}
|
||||
self.addEventListener('message', listener);
|
||||
self.postMessage({forge: {prng: {needed: needed}}});
|
||||
};
|
||||
} else {
|
||||
// main thread sends random bytes upon request
|
||||
var listener = function(e) {
|
||||
var data = e.data;
|
||||
if(data.forge && data.forge.prng) {
|
||||
ctx.seedFile(data.forge.prng.needed, function(err, bytes) {
|
||||
worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});
|
||||
});
|
||||
}
|
||||
};
|
||||
// TODO: do we need to remove the event listener when the worker dies?
|
||||
worker.addEventListener('message', listener);
|
||||
}
|
||||
};
|
||||
|
||||
return ctx;
|
||||
};
|
||||
|
||||
} // end module implementation
|
||||
|
||||
/* ########## Begin module wrapper ########## */
|
||||
var name = 'prng';
|
||||
if(typeof define !== 'function') {
|
||||
// NodeJS -> AMD
|
||||
if(typeof module === 'object' && module.exports) {
|
||||
var nodeJS = true;
|
||||
define = function(ids, factory) {
|
||||
factory(require, module);
|
||||
};
|
||||
} else {
|
||||
// <script>
|
||||
if(typeof forge === 'undefined') {
|
||||
forge = {};
|
||||
}
|
||||
return initModule(forge);
|
||||
}
|
||||
}
|
||||
// AMD
|
||||
var deps;
|
||||
var defineFunc = function(require, module) {
|
||||
module.exports = function(forge) {
|
||||
var mods = deps.map(function(dep) {
|
||||
return require(dep);
|
||||
}).concat(initModule);
|
||||
// handle circular dependencies
|
||||
forge = forge || {};
|
||||
forge.defined = forge.defined || {};
|
||||
if(forge.defined[name]) {
|
||||
return forge[name];
|
||||
}
|
||||
forge.defined[name] = true;
|
||||
for(var i = 0; i < mods.length; ++i) {
|
||||
mods[i](forge);
|
||||
}
|
||||
return forge[name];
|
||||
};
|
||||
};
|
||||
var tmpDefine = define;
|
||||
define = function(ids, factory) {
|
||||
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
|
||||
if(nodeJS) {
|
||||
delete define;
|
||||
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
}
|
||||
define = tmpDefine;
|
||||
return define.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
};
|
||||
define(['require', 'module', './md', './util'], function() {
|
||||
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
});
|
||||
|
||||
})();
|
|
@ -0,0 +1,237 @@
|
|||
/**
|
||||
* An API for getting cryptographically-secure random bytes. The bytes are
|
||||
* generated using the Fortuna algorithm devised by Bruce Schneier and
|
||||
* Niels Ferguson.
|
||||
*
|
||||
* Getting strong random bytes is not yet easy to do in javascript. The only
|
||||
* truish random entropy that can be collected is from the mouse, keyboard, or
|
||||
* from timing with respect to page loads, etc. This generator makes a poor
|
||||
* attempt at providing random bytes when those sources haven't yet provided
|
||||
* enough entropy to initially seed or to reseed the PRNG.
|
||||
*
|
||||
* @author Dave Longley
|
||||
*
|
||||
* Copyright (c) 2009-2014 Digital Bazaar, Inc.
|
||||
*/
|
||||
(function() {
|
||||
/* ########## Begin module implementation ########## */
|
||||
function initModule(forge) {
|
||||
|
||||
// forge.random already defined
|
||||
if(forge.random && forge.random.getBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
(function(jQuery) {
|
||||
|
||||
// the default prng plugin, uses AES-128
|
||||
var prng_aes = {};
|
||||
var _prng_aes_output = new Array(4);
|
||||
var _prng_aes_buffer = forge.util.createBuffer();
|
||||
prng_aes.formatKey = function(key) {
|
||||
// convert the key into 32-bit integers
|
||||
var tmp = forge.util.createBuffer(key);
|
||||
key = new Array(4);
|
||||
key[0] = tmp.getInt32();
|
||||
key[1] = tmp.getInt32();
|
||||
key[2] = tmp.getInt32();
|
||||
key[3] = tmp.getInt32();
|
||||
|
||||
// return the expanded key
|
||||
return forge.aes._expandKey(key, false);
|
||||
};
|
||||
prng_aes.formatSeed = function(seed) {
|
||||
// convert seed into 32-bit integers
|
||||
var tmp = forge.util.createBuffer(seed);
|
||||
seed = new Array(4);
|
||||
seed[0] = tmp.getInt32();
|
||||
seed[1] = tmp.getInt32();
|
||||
seed[2] = tmp.getInt32();
|
||||
seed[3] = tmp.getInt32();
|
||||
return seed;
|
||||
};
|
||||
prng_aes.cipher = function(key, seed) {
|
||||
forge.aes._updateBlock(key, seed, _prng_aes_output, false);
|
||||
_prng_aes_buffer.putInt32(_prng_aes_output[0]);
|
||||
_prng_aes_buffer.putInt32(_prng_aes_output[1]);
|
||||
_prng_aes_buffer.putInt32(_prng_aes_output[2]);
|
||||
_prng_aes_buffer.putInt32(_prng_aes_output[3]);
|
||||
return _prng_aes_buffer.getBytes();
|
||||
};
|
||||
prng_aes.increment = function(seed) {
|
||||
// FIXME: do we care about carry or signed issues?
|
||||
++seed[3];
|
||||
return seed;
|
||||
};
|
||||
prng_aes.md = forge.md.sha256;
|
||||
|
||||
/**
|
||||
* Creates a new PRNG.
|
||||
*/
|
||||
function spawnPrng() {
|
||||
var ctx = forge.prng.create(prng_aes);
|
||||
|
||||
/**
|
||||
* Gets random bytes. If a native secure crypto API is unavailable, this
|
||||
* method tries to make the bytes more unpredictable by drawing from data that
|
||||
* can be collected from the user of the browser, eg: mouse movement.
|
||||
*
|
||||
* If a callback is given, this method will be called asynchronously.
|
||||
*
|
||||
* @param count the number of random bytes to get.
|
||||
* @param [callback(err, bytes)] called once the operation completes.
|
||||
*
|
||||
* @return the random bytes in a string.
|
||||
*/
|
||||
ctx.getBytes = function(count, callback) {
|
||||
return ctx.generate(count, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets random bytes asynchronously. If a native secure crypto API is
|
||||
* unavailable, this method tries to make the bytes more unpredictable by
|
||||
* drawing from data that can be collected from the user of the browser,
|
||||
* eg: mouse movement.
|
||||
*
|
||||
* @param count the number of random bytes to get.
|
||||
*
|
||||
* @return the random bytes in a string.
|
||||
*/
|
||||
ctx.getBytesSync = function(count) {
|
||||
return ctx.generate(count);
|
||||
};
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// create default prng context
|
||||
var _ctx = spawnPrng();
|
||||
|
||||
// add other sources of entropy only if window.crypto.getRandomValues is not
|
||||
// available -- otherwise this source will be automatically used by the prng
|
||||
var _nodejs = (
|
||||
typeof process !== 'undefined' && process.versions && process.versions.node);
|
||||
var getRandomValues = null;
|
||||
if(typeof window !== 'undefined') {
|
||||
var _crypto = window.crypto || window.msCrypto;
|
||||
if(_crypto && _crypto.getRandomValues) {
|
||||
getRandomValues = function(arr) {
|
||||
return _crypto.getRandomValues(arr);
|
||||
};
|
||||
}
|
||||
}
|
||||
if(forge.disableNativeCode || (!_nodejs && !getRandomValues)) {
|
||||
// if this is a web worker, do not use weak entropy, instead register to
|
||||
// receive strong entropy asynchronously from the main thread
|
||||
if(typeof window === 'undefined' || window.document === undefined) {
|
||||
// FIXME:
|
||||
}
|
||||
|
||||
// get load time entropy
|
||||
_ctx.collectInt(+new Date(), 32);
|
||||
|
||||
// add some entropy from navigator object
|
||||
if(typeof(navigator) !== 'undefined') {
|
||||
var _navBytes = '';
|
||||
for(var key in navigator) {
|
||||
try {
|
||||
if(typeof(navigator[key]) == 'string') {
|
||||
_navBytes += navigator[key];
|
||||
}
|
||||
} catch(e) {
|
||||
/* Some navigator keys might not be accessible, e.g. the geolocation
|
||||
attribute throws an exception if touched in Mozilla chrome://
|
||||
context.
|
||||
|
||||
Silently ignore this and just don't use this as a source of
|
||||
entropy. */
|
||||
}
|
||||
}
|
||||
_ctx.collect(_navBytes);
|
||||
_navBytes = null;
|
||||
}
|
||||
|
||||
// add mouse and keyboard collectors if jquery is available
|
||||
if(jQuery) {
|
||||
// set up mouse entropy capture
|
||||
jQuery().mousemove(function(e) {
|
||||
// add mouse coords
|
||||
_ctx.collectInt(e.clientX, 16);
|
||||
_ctx.collectInt(e.clientY, 16);
|
||||
});
|
||||
|
||||
// set up keyboard entropy capture
|
||||
jQuery().keypress(function(e) {
|
||||
_ctx.collectInt(e.charCode, 8);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* Random API */
|
||||
if(!forge.random) {
|
||||
forge.random = _ctx;
|
||||
} else {
|
||||
// extend forge.random with _ctx
|
||||
for(var key in _ctx) {
|
||||
forge.random[key] = _ctx[key];
|
||||
}
|
||||
}
|
||||
|
||||
// expose spawn PRNG
|
||||
forge.random.createInstance = spawnPrng;
|
||||
|
||||
})(typeof(jQuery) !== 'undefined' ? jQuery : null);
|
||||
|
||||
} // end module implementation
|
||||
|
||||
/* ########## Begin module wrapper ########## */
|
||||
var name = 'random';
|
||||
if(typeof define !== 'function') {
|
||||
// NodeJS -> AMD
|
||||
if(typeof module === 'object' && module.exports) {
|
||||
var nodeJS = true;
|
||||
define = function(ids, factory) {
|
||||
factory(require, module);
|
||||
};
|
||||
} else {
|
||||
// <script>
|
||||
if(typeof forge === 'undefined') {
|
||||
forge = {};
|
||||
}
|
||||
return initModule(forge);
|
||||
}
|
||||
}
|
||||
// AMD
|
||||
var deps;
|
||||
var defineFunc = function(require, module) {
|
||||
module.exports = function(forge) {
|
||||
var mods = deps.map(function(dep) {
|
||||
return require(dep);
|
||||
}).concat(initModule);
|
||||
// handle circular dependencies
|
||||
forge = forge || {};
|
||||
forge.defined = forge.defined || {};
|
||||
if(forge.defined[name]) {
|
||||
return forge[name];
|
||||
}
|
||||
forge.defined[name] = true;
|
||||
for(var i = 0; i < mods.length; ++i) {
|
||||
mods[i](forge);
|
||||
}
|
||||
return forge[name];
|
||||
};
|
||||
};
|
||||
var tmpDefine = define;
|
||||
define = function(ids, factory) {
|
||||
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
|
||||
if(nodeJS) {
|
||||
delete define;
|
||||
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
}
|
||||
define = tmpDefine;
|
||||
return define.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
};
|
||||
define(['require', 'module', './aes', './md', './prng', './util'], function() {
|
||||
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
});
|
||||
})();
|
|
@ -0,0 +1,369 @@
|
|||
/**
|
||||
* Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.
|
||||
*
|
||||
* @author Dave Longley
|
||||
*
|
||||
* Copyright (c) 2010-2015 Digital Bazaar, Inc.
|
||||
*/
|
||||
(function() {
|
||||
/* ########## Begin module implementation ########## */
|
||||
function initModule(forge) {
|
||||
|
||||
var sha1 = forge.sha1 = forge.sha1 || {};
|
||||
forge.md = forge.md || {};
|
||||
forge.md.algorithms = forge.md.algorithms || {};
|
||||
forge.md.sha1 = forge.md.algorithms.sha1 = sha1;
|
||||
|
||||
/**
|
||||
* Creates a SHA-1 message digest object.
|
||||
*
|
||||
* @return a message digest object.
|
||||
*/
|
||||
sha1.create = function() {
|
||||
// do initialization as necessary
|
||||
if(!_initialized) {
|
||||
_init();
|
||||
}
|
||||
|
||||
// SHA-1 state contains five 32-bit integers
|
||||
var _state = null;
|
||||
|
||||
// input buffer
|
||||
var _input = forge.util.createBuffer();
|
||||
|
||||
// used for word storage
|
||||
var _w = new Array(80);
|
||||
|
||||
// message digest object
|
||||
var md = {
|
||||
algorithm: 'sha1',
|
||||
blockLength: 64,
|
||||
digestLength: 20,
|
||||
// 56-bit length of message so far (does not including padding)
|
||||
messageLength: 0,
|
||||
// true message length
|
||||
fullMessageLength: null,
|
||||
// size of message length in bytes
|
||||
messageLengthSize: 8
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts the digest.
|
||||
*
|
||||
* @return this digest object.
|
||||
*/
|
||||
md.start = function() {
|
||||
// up to 56-bit message length for convenience
|
||||
md.messageLength = 0;
|
||||
|
||||
// full message length (set md.messageLength64 for backwards-compatibility)
|
||||
md.fullMessageLength = md.messageLength64 = [];
|
||||
var int32s = md.messageLengthSize / 4;
|
||||
for(var i = 0; i < int32s; ++i) {
|
||||
md.fullMessageLength.push(0);
|
||||
}
|
||||
_input = forge.util.createBuffer();
|
||||
_state = {
|
||||
h0: 0x67452301,
|
||||
h1: 0xEFCDAB89,
|
||||
h2: 0x98BADCFE,
|
||||
h3: 0x10325476,
|
||||
h4: 0xC3D2E1F0
|
||||
};
|
||||
return md;
|
||||
};
|
||||
// start digest automatically for first time
|
||||
md.start();
|
||||
|
||||
/**
|
||||
* Updates the digest with the given message input. The given input can
|
||||
* treated as raw input (no encoding will be applied) or an encoding of
|
||||
* 'utf8' maybe given to encode the input using UTF-8.
|
||||
*
|
||||
* @param msg the message input to update with.
|
||||
* @param encoding the encoding to use (default: 'raw', other: 'utf8').
|
||||
*
|
||||
* @return this digest object.
|
||||
*/
|
||||
md.update = function(msg, encoding) {
|
||||
if(encoding === 'utf8') {
|
||||
msg = forge.util.encodeUtf8(msg);
|
||||
}
|
||||
|
||||
// update message length
|
||||
var len = msg.length;
|
||||
md.messageLength += len;
|
||||
len = [(len / 0x100000000) >>> 0, len >>> 0];
|
||||
for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
|
||||
md.fullMessageLength[i] += len[1];
|
||||
len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
|
||||
md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
|
||||
len[0] = ((len[1] / 0x100000000) >>> 0);
|
||||
}
|
||||
|
||||
// add bytes to input buffer
|
||||
_input.putBytes(msg);
|
||||
|
||||
// process bytes
|
||||
_update(_state, _w, _input);
|
||||
|
||||
// compact input buffer every 2K or if empty
|
||||
if(_input.read > 2048 || _input.length() === 0) {
|
||||
_input.compact();
|
||||
}
|
||||
|
||||
return md;
|
||||
};
|
||||
|
||||
/**
|
||||
* Produces the digest.
|
||||
*
|
||||
* @return a byte buffer containing the digest value.
|
||||
*/
|
||||
md.digest = function() {
|
||||
/* Note: Here we copy the remaining bytes in the input buffer and
|
||||
add the appropriate SHA-1 padding. Then we do the final update
|
||||
on a copy of the state so that if the user wants to get
|
||||
intermediate digests they can do so. */
|
||||
|
||||
/* Determine the number of bytes that must be added to the message
|
||||
to ensure its length is congruent to 448 mod 512. In other words,
|
||||
the data to be digested must be a multiple of 512 bits (or 128 bytes).
|
||||
This data includes the message, some padding, and the length of the
|
||||
message. Since the length of the message will be encoded as 8 bytes (64
|
||||
bits), that means that the last segment of the data must have 56 bytes
|
||||
(448 bits) of message and padding. Therefore, the length of the message
|
||||
plus the padding must be congruent to 448 mod 512 because
|
||||
512 - 128 = 448.
|
||||
|
||||
In order to fill up the message length it must be filled with
|
||||
padding that begins with 1 bit followed by all 0 bits. Padding
|
||||
must *always* be present, so if the message length is already
|
||||
congruent to 448 mod 512, then 512 padding bits must be added. */
|
||||
|
||||
var finalBlock = forge.util.createBuffer();
|
||||
finalBlock.putBytes(_input.bytes());
|
||||
|
||||
// compute remaining size to be digested (include message length size)
|
||||
var remaining = (
|
||||
md.fullMessageLength[md.fullMessageLength.length - 1] +
|
||||
md.messageLengthSize);
|
||||
|
||||
// add padding for overflow blockSize - overflow
|
||||
// _padding starts with 1 byte with first bit is set (byte value 128), then
|
||||
// there may be up to (blockSize - 1) other pad bytes
|
||||
var overflow = remaining & (md.blockLength - 1);
|
||||
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
|
||||
|
||||
// serialize message length in bits in big-endian order; since length
|
||||
// is stored in bytes we multiply by 8 and add carry from next int
|
||||
var messageLength = forge.util.createBuffer();
|
||||
var next, carry;
|
||||
var bits = md.fullMessageLength[0] * 8;
|
||||
for(var i = 0; i < md.fullMessageLength.length; ++i) {
|
||||
next = md.fullMessageLength[i + 1] * 8;
|
||||
carry = (next / 0x100000000) >>> 0;
|
||||
bits += carry;
|
||||
finalBlock.putInt32(bits >>> 0);
|
||||
bits = next;
|
||||
}
|
||||
|
||||
var s2 = {
|
||||
h0: _state.h0,
|
||||
h1: _state.h1,
|
||||
h2: _state.h2,
|
||||
h3: _state.h3,
|
||||
h4: _state.h4
|
||||
};
|
||||
_update(s2, _w, finalBlock);
|
||||
var rval = forge.util.createBuffer();
|
||||
rval.putInt32(s2.h0);
|
||||
rval.putInt32(s2.h1);
|
||||
rval.putInt32(s2.h2);
|
||||
rval.putInt32(s2.h3);
|
||||
rval.putInt32(s2.h4);
|
||||
return rval;
|
||||
};
|
||||
|
||||
return md;
|
||||
};
|
||||
|
||||
// sha-1 padding bytes not initialized yet
|
||||
var _padding = null;
|
||||
var _initialized = false;
|
||||
|
||||
/**
|
||||
* Initializes the constant tables.
|
||||
*/
|
||||
function _init() {
|
||||
// create padding
|
||||
_padding = String.fromCharCode(128);
|
||||
_padding += forge.util.fillString(String.fromCharCode(0x00), 64);
|
||||
|
||||
// now initialized
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a SHA-1 state with the given byte buffer.
|
||||
*
|
||||
* @param s the SHA-1 state to update.
|
||||
* @param w the array to use to store words.
|
||||
* @param bytes the byte buffer to update with.
|
||||
*/
|
||||
function _update(s, w, bytes) {
|
||||
// consume 512 bit (64 byte) chunks
|
||||
var t, a, b, c, d, e, f, i;
|
||||
var len = bytes.length();
|
||||
while(len >= 64) {
|
||||
// the w array will be populated with sixteen 32-bit big-endian words
|
||||
// and then extended into 80 32-bit words according to SHA-1 algorithm
|
||||
// and for 32-79 using Max Locktyukhin's optimization
|
||||
|
||||
// initialize hash value for this chunk
|
||||
a = s.h0;
|
||||
b = s.h1;
|
||||
c = s.h2;
|
||||
d = s.h3;
|
||||
e = s.h4;
|
||||
|
||||
// round 1
|
||||
for(i = 0; i < 16; ++i) {
|
||||
t = bytes.getInt32();
|
||||
w[i] = t;
|
||||
f = d ^ (b & (c ^ d));
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
for(; i < 20; ++i) {
|
||||
t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
|
||||
t = (t << 1) | (t >>> 31);
|
||||
w[i] = t;
|
||||
f = d ^ (b & (c ^ d));
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
// round 2
|
||||
for(; i < 32; ++i) {
|
||||
t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
|
||||
t = (t << 1) | (t >>> 31);
|
||||
w[i] = t;
|
||||
f = b ^ c ^ d;
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
for(; i < 40; ++i) {
|
||||
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
|
||||
t = (t << 2) | (t >>> 30);
|
||||
w[i] = t;
|
||||
f = b ^ c ^ d;
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
// round 3
|
||||
for(; i < 60; ++i) {
|
||||
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
|
||||
t = (t << 2) | (t >>> 30);
|
||||
w[i] = t;
|
||||
f = (b & c) | (d & (b ^ c));
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
// round 4
|
||||
for(; i < 80; ++i) {
|
||||
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
|
||||
t = (t << 2) | (t >>> 30);
|
||||
w[i] = t;
|
||||
f = b ^ c ^ d;
|
||||
t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;
|
||||
e = d;
|
||||
d = c;
|
||||
c = (b << 30) | (b >>> 2);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
|
||||
// update hash state
|
||||
s.h0 = (s.h0 + a) | 0;
|
||||
s.h1 = (s.h1 + b) | 0;
|
||||
s.h2 = (s.h2 + c) | 0;
|
||||
s.h3 = (s.h3 + d) | 0;
|
||||
s.h4 = (s.h4 + e) | 0;
|
||||
|
||||
len -= 64;
|
||||
}
|
||||
}
|
||||
|
||||
} // end module implementation
|
||||
|
||||
/* ########## Begin module wrapper ########## */
|
||||
var name = 'sha1';
|
||||
if(typeof define !== 'function') {
|
||||
// NodeJS -> AMD
|
||||
if(typeof module === 'object' && module.exports) {
|
||||
var nodeJS = true;
|
||||
define = function(ids, factory) {
|
||||
factory(require, module);
|
||||
};
|
||||
} else {
|
||||
// <script>
|
||||
if(typeof forge === 'undefined') {
|
||||
forge = {};
|
||||
}
|
||||
return initModule(forge);
|
||||
}
|
||||
}
|
||||
// AMD
|
||||
var deps;
|
||||
var defineFunc = function(require, module) {
|
||||
module.exports = function(forge) {
|
||||
var mods = deps.map(function(dep) {
|
||||
return require(dep);
|
||||
}).concat(initModule);
|
||||
// handle circular dependencies
|
||||
forge = forge || {};
|
||||
forge.defined = forge.defined || {};
|
||||
if(forge.defined[name]) {
|
||||
return forge[name];
|
||||
}
|
||||
forge.defined[name] = true;
|
||||
for(var i = 0; i < mods.length; ++i) {
|
||||
mods[i](forge);
|
||||
}
|
||||
return forge[name];
|
||||
};
|
||||
};
|
||||
var tmpDefine = define;
|
||||
define = function(ids, factory) {
|
||||
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
|
||||
if(nodeJS) {
|
||||
delete define;
|
||||
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
}
|
||||
define = tmpDefine;
|
||||
return define.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
};
|
||||
define(['require', 'module', './util'], function() {
|
||||
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
|
||||
});
|
||||
})();
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,104 @@
|
|||
(function () {
|
||||
'use strict';
|
||||
|
||||
function utf8ToBinaryString(str) {
|
||||
var escstr = encodeURIComponent(str);
|
||||
// replaces any uri escape sequence, such as %0A,
|
||||
// with binary escape, such as 0x0A
|
||||
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) {
|
||||
return String.fromCharCode(parseInt(p1, 16));
|
||||
});
|
||||
|
||||
return binstr;
|
||||
}
|
||||
|
||||
function utf8ToBuffer(str) {
|
||||
var binstr = utf8ToBinaryString(str);
|
||||
var buf = binaryStringToBuffer(binstr);
|
||||
return buf;
|
||||
}
|
||||
|
||||
function utf8ToBase64(str) {
|
||||
var binstr = utf8ToBinaryString(str);
|
||||
return btoa(binstr);
|
||||
}
|
||||
|
||||
function binaryStringToUtf8(binstr) {
|
||||
var escstr = binstr.replace(/(.)/g, function (m, p) {
|
||||
var code = p.charCodeAt(0).toString(16).toUpperCase();
|
||||
if (code.length < 2) {
|
||||
code = '0' + code;
|
||||
}
|
||||
return '%' + code;
|
||||
});
|
||||
|
||||
return decodeURIComponent(escstr);
|
||||
}
|
||||
|
||||
function bufferToUtf8(buf) {
|
||||
var binstr = bufferToBinaryString(buf);
|
||||
|
||||
return binaryStringToUtf8(binstr);
|
||||
}
|
||||
|
||||
function base64ToUtf8(b64) {
|
||||
var binstr = atob(b64);
|
||||
|
||||
return binaryStringToUtf8(binstr);
|
||||
}
|
||||
|
||||
function bufferToBinaryString(buf) {
|
||||
var binstr = Array.prototype.map.call(buf, function (ch) {
|
||||
return String.fromCharCode(ch);
|
||||
}).join('');
|
||||
|
||||
return binstr;
|
||||
}
|
||||
|
||||
function bufferToBase64(arr) {
|
||||
var binstr = bufferToBinaryString(arr);
|
||||
return btoa(binstr);
|
||||
}
|
||||
|
||||
function binaryStringToBuffer(binstr) {
|
||||
var buf;
|
||||
|
||||
if ('undefined' !== typeof Uint8Array) {
|
||||
buf = new Uint8Array(binstr.length);
|
||||
} else {
|
||||
buf = [];
|
||||
}
|
||||
|
||||
Array.prototype.forEach.call(binstr, function (ch, i) {
|
||||
buf[i] = ch.charCodeAt(0);
|
||||
});
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
function base64ToBuffer(base64) {
|
||||
var binstr = atob(base64);
|
||||
var buf = binaryStringToBuffer(binstr);
|
||||
return buf;
|
||||
}
|
||||
|
||||
window.Unibabel = {
|
||||
utf8ToBinaryString: utf8ToBinaryString
|
||||
, utf8ToBuffer: utf8ToBuffer
|
||||
, utf8ToBase64: utf8ToBase64
|
||||
, binaryStringToUtf8: binaryStringToUtf8
|
||||
, bufferToUtf8: bufferToUtf8
|
||||
, base64ToUtf8: base64ToUtf8
|
||||
, bufferToBinaryString: bufferToBinaryString
|
||||
, bufferToBase64: bufferToBase64
|
||||
, binaryStringToBuffer: binaryStringToBuffer
|
||||
, base64ToBuffer: base64ToBuffer
|
||||
|
||||
// compat
|
||||
, strToUtf8Arr: utf8ToBuffer
|
||||
, utf8ArrToStr: bufferToUtf8
|
||||
, arrToBase64: bufferToBase64
|
||||
, base64ToArr: base64ToBuffer
|
||||
};
|
||||
|
||||
}());
|
|
@ -0,0 +1,137 @@
|
|||
/*
|
||||
Copyright (c) 2011, Chris Umbel
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
(function (exports) {
|
||||
'use strict';
|
||||
|
||||
var charTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
var byteTable = [
|
||||
0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
|
||||
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
|
||||
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
|
||||
0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
|
||||
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
|
||||
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
|
||||
0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff
|
||||
];
|
||||
|
||||
function quintetCount(buff) {
|
||||
var quintets = Math.floor(buff.length / 5);
|
||||
return buff.length % 5 === 0 ? quintets: quintets + 1;
|
||||
}
|
||||
|
||||
exports.bufferToBase32 = function(plain) {
|
||||
// plain MUST come in either as Array or Uint8Array
|
||||
if('undefined' !== typeof Uint8Array) {
|
||||
if (!(plain instanceof Uint8Array)){
|
||||
plain = new Uint8Array(plain);
|
||||
}
|
||||
}
|
||||
var i = 0;
|
||||
var j = 0;
|
||||
var shiftIndex = 0;
|
||||
var digit = 0;
|
||||
var encoded = new Array(quintetCount(plain) * 8);
|
||||
|
||||
/* byte by byte isn't as pretty as quintet by quintet but tests a bit
|
||||
faster. will have to revisit. */
|
||||
while(i < plain.length) {
|
||||
var current = plain[i];
|
||||
|
||||
if(shiftIndex > 3) {
|
||||
digit = current & (0xff >> shiftIndex);
|
||||
shiftIndex = (shiftIndex + 5) % 8;
|
||||
digit = (digit << shiftIndex) | ((i + 1 < plain.length) ?
|
||||
plain[i + 1] : 0) >> (8 - shiftIndex);
|
||||
i++;
|
||||
} else {
|
||||
digit = (current >> (8 - (shiftIndex + 5))) & 0x1f;
|
||||
shiftIndex = (shiftIndex + 5) % 8;
|
||||
if(shiftIndex === 0) { i++; }
|
||||
}
|
||||
|
||||
encoded[j] = charTable[digit];
|
||||
j++;
|
||||
}
|
||||
|
||||
for(i = j; i < encoded.length; i++) {
|
||||
encoded[i] = '=';
|
||||
}
|
||||
|
||||
return encoded.join('');
|
||||
};
|
||||
|
||||
exports.base32ToBuffer = function(encoded) {
|
||||
var shiftIndex = 0;
|
||||
var plainDigit = 0;
|
||||
var plainChar;
|
||||
var plainPos = 0;
|
||||
var len = Math.ceil(encoded.length * 5 / 8);
|
||||
var decoded;
|
||||
encoded = encoded.split('').map(function (ch) {
|
||||
return ch.charCodeAt(0);
|
||||
});
|
||||
if('undefined' !== typeof Uint8Array) {
|
||||
encoded = new Uint8Array(encoded);
|
||||
decoded = new Uint8Array(len);
|
||||
} else {
|
||||
decoded = new Array(len);
|
||||
}
|
||||
|
||||
/* byte by byte isn't as pretty as octet by octet but tests a bit
|
||||
faster. will have to revisit. */
|
||||
for(var i = 0; i < encoded.length; i++) {
|
||||
if(encoded[i] === 0x3d){ //'='
|
||||
break;
|
||||
}
|
||||
|
||||
var encodedByte = encoded[i] - 0x30;
|
||||
|
||||
if(encodedByte < byteTable.length) {
|
||||
plainDigit = byteTable[encodedByte];
|
||||
|
||||
if(shiftIndex <= 3) {
|
||||
shiftIndex = (shiftIndex + 5) % 8;
|
||||
|
||||
if(shiftIndex === 0) {
|
||||
plainChar |= plainDigit;
|
||||
decoded[plainPos] = plainChar;
|
||||
plainPos++;
|
||||
plainChar = 0;
|
||||
} else {
|
||||
plainChar |= 0xff & (plainDigit << (8 - shiftIndex));
|
||||
}
|
||||
} else {
|
||||
shiftIndex = (shiftIndex + 5) % 8;
|
||||
plainChar |= 0xff & (plainDigit >>> shiftIndex);
|
||||
decoded[plainPos] = plainChar;
|
||||
plainPos++;
|
||||
|
||||
plainChar = 0xff & (plainDigit << (8 - shiftIndex));
|
||||
}
|
||||
} else {
|
||||
throw new Error('Invalid input - it is not base32 encoded string');
|
||||
}
|
||||
}
|
||||
return decoded.slice(0, plainPos);
|
||||
};
|
||||
|
||||
}(window.Unibabel || window));
|
|
@ -0,0 +1,46 @@
|
|||
(function () {
|
||||
'use strict';
|
||||
|
||||
function bufferToHex(arr) {
|
||||
var i;
|
||||
var len;
|
||||
var hex = '';
|
||||
var c;
|
||||
|
||||
for (i = 0, len = arr.length; i < len; i += 1) {
|
||||
c = arr[i].toString(16);
|
||||
if (c.length < 2) {
|
||||
c = '0' + c;
|
||||
}
|
||||
hex += c;
|
||||
}
|
||||
|
||||
return hex;
|
||||
}
|
||||
|
||||
function hexToBuffer(hex) {
|
||||
// TODO use Uint8Array or ArrayBuffer or DataView
|
||||
var i;
|
||||
var byteLen = hex.length / 2;
|
||||
var arr;
|
||||
var j = 0;
|
||||
|
||||
if (byteLen !== parseInt(byteLen, 10)) {
|
||||
throw new Error("Invalid hex length '" + hex.length + "'");
|
||||
}
|
||||
|
||||
arr = new Uint8Array(byteLen);
|
||||
|
||||
for (i = 0; i < byteLen; i += 1) {
|
||||
arr[i] = parseInt(hex[j] + hex[j + 1], 16);
|
||||
j += 2;
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Hex Convenience Functions
|
||||
window.Unibabel.hexToBuffer = hexToBuffer;
|
||||
window.Unibabel.bufferToHex = bufferToHex;
|
||||
|
||||
}());
|
Loading…
Reference in New Issue