bitmessage-js/lib/crypto-platform.browser.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2014-12-13 19:56:14 +01:00
/**
2014-12-26 17:47:25 +01:00
* Browser Bitmessage crypto implementation.
2014-12-30 18:00:28 +01:00
* @see {@link http://www.w3.org/TR/WebCryptoAPI/}
* @see {@link http://caniuse.com/#feat=cryptography}
* @see {@link https://sites.google.com/a/chromium.org/dev/blink/webcrypto}
2014-12-13 19:56:14 +01:00
*/
"use strict";
2014-12-18 17:47:18 +01:00
require("es6-promise").polyfill();
var assert = require("assert");
2014-12-18 17:47:18 +01:00
var ripemd160 = require("ripemd160");
2014-12-18 21:54:27 +01:00
// Support `webkit` prefix for Safari (not tested yet).
// TODO(Kagami): Try to support IE11.
var subtle = window.crypto.subtle || window.crypto.webkitSubtle;
assert(subtle, "WebCryptoAPI is not supported");
2014-12-18 17:47:18 +01:00
exports.sha512 = function(buf) {
2014-12-18 21:54:27 +01:00
return subtle.digest({name: "SHA-512"}, buf).then(function(arr) {
return new Buffer(new Uint8Array(arr));
});
};
2014-12-18 17:47:18 +01:00
2014-12-19 13:34:33 +01:00
exports.sha256 = function(buf) {
return subtle.digest({name: "SHA-256"}, buf).then(function(arr) {
return new Buffer(new Uint8Array(arr));
});
};
2014-12-18 17:47:18 +01:00
exports.ripemd160 = function(buf) {
2014-12-27 22:04:23 +01:00
// XXX(Kagami): RIPEMD is not defined in WebCryptoAPI so we provide it
// using pure JS third-party implementation.
2014-12-18 17:47:18 +01:00
return Promise.resolve(ripemd160(buf));
};
2014-12-26 18:17:01 +01:00
exports.randomBytes = function(size) {
var arr = new Uint8Array(size);
window.crypto.getRandomValues(arr);
return new Buffer(arr);
};