nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
93 lines (92 loc) • 3.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.md5 = md5;
exports.sha1 = sha1;
exports.sha256 = sha256;
const primitives_1 = require("../guards/primitives");
const helpers_1 = require("./helpers");
const utils_1 = require("./utils");
function md5(str) {
const state = [1732584193, -271733879, -1732584194, 271733878];
const len = str.length;
let i;
for (i = 64; i <= len; i += 64) {
(0, helpers_1._md5cycle)(state, (0, helpers_1._stringToNumbers)(str.substring(i - 64, i)));
}
const $str = str.substring(i - 64);
const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < $str.length; i++) {
tail[i >> 2] |= $str.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
(0, helpers_1._md5cycle)(state, tail);
for (let j = 0; j < 16; j++) {
tail[j] = 0;
}
}
tail[14] = len * 8;
(0, helpers_1._md5cycle)(state, tail);
return state.map(helpers_1._numToHex).join('');
}
function sha1(msg) {
const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
const utf8 = (0, utils_1.utf8ToBytes)(msg);
const rotl = (n, bits) => (n << bits) | (n >>> (32 - bits));
const toHex = (n) => (n >>> 0).toString(16).padStart(8, '0');
const len = utf8.length;
const padBytes = (len + 9) % 64 ? 64 - ((len + 9) % 64) : 0;
const total = len + 1 + padBytes + 8;
const words = new Uint32Array(total >>> 2);
for (let i = 0; i < utf8.length; i++) {
words[i >> 2] |= utf8[i] << (24 - (i % 4) * 8);
}
words[utf8.length >> 2] |= 0x80 << (24 - (utf8.length % 4) * 8);
words[words.length - 1] = utf8.length * 8;
const h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
const W = new Uint32Array(80);
for (let i = 0; i < words.length; i += 16) {
for (let j = 0; j < 16; j++)
W[j] = words[i + j] | 0;
for (let j = 16; j < 80; j++) {
W[j] = rotl(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1);
}
let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
for (let j = 0; j < 80; j++) {
let f, k;
if (j < 20) {
f = (b & c) | (~b & d);
k = K[0];
}
else if (j < 40) {
f = b ^ c ^ d;
k = K[1];
}
else if (j < 60) {
f = (b & c) | (b & d) | (c & d);
k = K[2];
}
else {
f = b ^ c ^ d;
k = K[3];
}
const temp = (rotl(a, 5) + f + e + k + W[j]) | 0;
e = d;
d = c;
c = rotl(b, 30);
b = a;
a = temp;
}
h[0] = (h[0] + a) | 0;
h[1] = (h[1] + b) | 0;
h[2] = (h[2] + c) | 0;
h[3] = (h[3] + d) | 0;
h[4] = (h[4] + e) | 0;
}
return h.map(toHex).join('');
}
function sha256(msg) {
if (!(0, primitives_1.isString)(msg))
throw new TypeError('Input must be of type string!');
return (0, utils_1.bytesToHex)((0, utils_1.sha256Bytes)((0, utils_1.utf8ToBytes)(msg)));
}