crypto porting WIP
This commit is contained in:
parent
de9f8867d5
commit
d42b9e3df8
@ -20,6 +20,10 @@ import test from "ava";
|
||||
import { NodeEmscriptenLoader } from "./nodeEmscriptenLoader";
|
||||
import * as native from "./emscInterface";
|
||||
|
||||
import nacl = require("./nacl-fast");
|
||||
import { encodeCrock, decodeCrock } from "./nativeCrypto";
|
||||
import { timestampCheck } from "../helpers";
|
||||
|
||||
|
||||
test("string hashing", async (t) => {
|
||||
const loader = new NodeEmscriptenLoader();
|
||||
@ -30,6 +34,16 @@ test("string hashing", async (t) => {
|
||||
const hc = x.hash().toCrock();
|
||||
console.log(`# hc ${hc}`);
|
||||
t.true(h === hc, "must equal");
|
||||
|
||||
const te = new TextEncoder();
|
||||
|
||||
const x2 = te.encode("hello taler\0")
|
||||
|
||||
const hc2 = encodeCrock(nacl.hash(x2));
|
||||
|
||||
console.log(`# hc2 ${hc}`);
|
||||
t.true(h === hc2);
|
||||
|
||||
t.pass();
|
||||
});
|
||||
|
||||
@ -39,11 +53,45 @@ test("signing", async (t) => {
|
||||
const emsc = await loader.getEmscriptenEnvironment();
|
||||
|
||||
const x = native.ByteArray.fromStringWithNull(emsc, "hello taler");
|
||||
const priv = native.EddsaPrivateKey.create(emsc, );
|
||||
const priv = native.EddsaPrivateKey.create(emsc);
|
||||
const pub = priv.getPublicKey();
|
||||
const purpose = new native.EccSignaturePurpose(emsc, native.SignaturePurpose.TEST, x);
|
||||
|
||||
const purposeDataCrock = purpose.toCrock();
|
||||
const privCrock = priv.toCrock();
|
||||
const pubCrock = pub.toCrock();
|
||||
const sig = native.eddsaSign(purpose, priv);
|
||||
console.time("a");
|
||||
for (let i = 0; i < 5000; i++) {
|
||||
const sig = native.eddsaSign(purpose, priv);
|
||||
}
|
||||
console.timeEnd("a");
|
||||
t.true(native.eddsaVerify(native.SignaturePurpose.TEST, purpose, sig, pub));
|
||||
|
||||
console.log("priv size", decodeCrock(privCrock).byteLength);
|
||||
|
||||
const pair = nacl.sign_keyPair_fromSeed(new Uint8Array(decodeCrock(privCrock)));
|
||||
|
||||
console.log("emsc priv", privCrock);
|
||||
console.log("emsc pub", pubCrock);
|
||||
|
||||
console.log("nacl priv", encodeCrock(pair.secretKey));
|
||||
console.log("nacl pub", encodeCrock(pair.publicKey));
|
||||
|
||||
const d2 = new Uint8Array(decodeCrock(purposeDataCrock));
|
||||
const d3 = nacl.hash(d2);
|
||||
|
||||
console.time("b");
|
||||
for (let i = 0; i < 5000; i++) {
|
||||
const s2 = nacl.sign_detached(d3, pair.secretKey);
|
||||
}
|
||||
console.timeEnd("b");
|
||||
|
||||
const s2 = nacl.sign_detached(d3, pair.secretKey);
|
||||
|
||||
console.log("sig1:", sig.toCrock());
|
||||
console.log("sig2:", encodeCrock(s2));
|
||||
|
||||
t.pass();
|
||||
});
|
||||
|
||||
|
100
src/crypto/kdf.ts
Normal file
100
src/crypto/kdf.ts
Normal file
@ -0,0 +1,100 @@
|
||||
/*
|
||||
This file is part of GNU Taler
|
||||
(C) 2019 GNUnet e.V.
|
||||
|
||||
GNU Taler is free software; you can redistribute it and/or modify it under the
|
||||
terms of the GNU General Public License as published by the Free Software
|
||||
Foundation; either version 3, or (at your option) any later version.
|
||||
|
||||
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
||||
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with
|
||||
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
|
||||
*/
|
||||
|
||||
import nacl = require("./nacl-fast");
|
||||
import { sha256 } from "./sha256";
|
||||
|
||||
let createHmac: any;
|
||||
|
||||
export function sha512(data: Uint8Array): Uint8Array {
|
||||
return nacl.hash(data);
|
||||
}
|
||||
|
||||
export function hmac(
|
||||
digest: (d: Uint8Array) => Uint8Array,
|
||||
blockSize: number,
|
||||
key: Uint8Array,
|
||||
message: Uint8Array,
|
||||
): Uint8Array {
|
||||
if (key.byteLength > blockSize) {
|
||||
key = digest(key);
|
||||
}
|
||||
console.log("message", message);
|
||||
if (key.byteLength < blockSize) {
|
||||
const k = key;
|
||||
key = new Uint8Array(blockSize);
|
||||
key.set(k, 0);
|
||||
}
|
||||
const okp = new Uint8Array(blockSize);
|
||||
const ikp = new Uint8Array(blockSize);
|
||||
for (let i = 0; i < blockSize; i++) {
|
||||
ikp[i] = key[i] ^ 0x36;
|
||||
okp[i] = key[i] ^ 0x5c;
|
||||
}
|
||||
const b1 = new Uint8Array(blockSize + message.byteLength);
|
||||
b1.set(ikp, 0);
|
||||
b1.set(message, blockSize);
|
||||
const h0 = digest(b1);
|
||||
const b2 = new Uint8Array(blockSize + h0.length);
|
||||
b2.set(okp, 0);
|
||||
b2.set(h0, blockSize);
|
||||
return digest(b2);
|
||||
}
|
||||
|
||||
export function hmacSha512(key: Uint8Array, message: Uint8Array) {
|
||||
return hmac(sha512, 128, key, message);
|
||||
}
|
||||
|
||||
export function hmacSha256(key: Uint8Array, message: Uint8Array) {
|
||||
return hmac(sha256, 64, key, message);
|
||||
}
|
||||
|
||||
/*
|
||||
function expand(prfAlgo: string, prk: Uint8Array, length: number, info: Uint8Array) {
|
||||
let hashLength;
|
||||
if (prfAlgo == "sha512") {
|
||||
hashLength = 64;
|
||||
} else if (prfAlgo == "sha256") {
|
||||
hashLength = 32;
|
||||
} else {
|
||||
throw Error("unsupported hash");
|
||||
}
|
||||
info = info || Buffer.alloc(0);
|
||||
var N = Math.ceil(length / hashLength);
|
||||
var memo: Buffer[] = [];
|
||||
|
||||
for (var i = 0; i < N; i++) {
|
||||
memo[i] = createHmac(prfAlgo, prk)
|
||||
.update(memo[i - 1] || Buffer.alloc(0))
|
||||
.update(info)
|
||||
.update(Buffer.alloc(1, i + 1))
|
||||
.digest();
|
||||
}
|
||||
return Buffer.concat(memo, length);
|
||||
}
|
||||
*/
|
||||
|
||||
export function kdf(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array) {
|
||||
// extract
|
||||
const prk = hmacSha512(salt, ikm);
|
||||
|
||||
// expand
|
||||
|
||||
var N = Math.ceil(length / 256);
|
||||
|
||||
//return expand(prfAlgo, prk, length, info);
|
||||
return prk;
|
||||
}
|
2404
src/crypto/nacl-fast.ts
Normal file
2404
src/crypto/nacl-fast.ts
Normal file
File diff suppressed because it is too large
Load Diff
@ -19,9 +19,25 @@
|
||||
*/
|
||||
import test from "ava";
|
||||
import { encodeCrock, decodeCrock } from "./nativeCrypto";
|
||||
import { hmacSha512, sha512 } from "./kdf";
|
||||
import nacl = require("./nacl-fast");
|
||||
|
||||
function hexToBytes(hex: string) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
test("encoding", (t) => {
|
||||
function bytesToHex(bytes: Uint8Array): string {
|
||||
for (var hex = [], i = 0; i < bytes.length; i++) {
|
||||
var current = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
|
||||
hex.push((current >>> 4).toString(16));
|
||||
hex.push((current & 0xf).toString(16));
|
||||
}
|
||||
return hex.join("");
|
||||
}
|
||||
|
||||
test("encoding", t => {
|
||||
const utf8decoder = new TextDecoder("utf-8");
|
||||
const utf8encoder = new TextEncoder();
|
||||
const s = "Hello, World";
|
||||
@ -29,4 +45,41 @@ test("encoding", (t) => {
|
||||
const outBuf = decodeCrock(encStr);
|
||||
const sOut = utf8decoder.decode(outBuf);
|
||||
t.deepEqual(s, sOut);
|
||||
});
|
||||
});
|
||||
|
||||
test("taler-exchange-tvg hash code", t => {
|
||||
const input = "91JPRV3F5GG4EKJN41A62V35E8";
|
||||
const output =
|
||||
"CW96WR74JS8T53EC8GKSGD49QKH4ZNFTZXDAWMMV5GJ1E4BM6B8GPN5NVHDJ8ZVXNCW7Q4WBYCV61HCA3PZC2YJD850DT29RHHN7ESR";
|
||||
|
||||
const myOutput = encodeCrock(sha512(decodeCrock(input)));
|
||||
|
||||
t.deepEqual(myOutput, output);
|
||||
});
|
||||
|
||||
test("taler-exchange-tvg ecdhe key", t => {
|
||||
const priv1 = "YSYA38XH1PH40ZPSEZCXEFX9PH9Q3A2PE19FHM54DMTZ4MAPH9S0";
|
||||
const pub1 = "GNQRNSYF4BT4V0EV0DBXZCHFVQ79ATP0KBJ9EAY18FGSY513A5VG";
|
||||
|
||||
const myPub = nacl.x25519_edwards_keyPair_fromSecretKey(decodeCrock(priv1))
|
||||
t.deepEqual(encodeCrock(myPub), pub1);
|
||||
|
||||
//const myPub1 = nacl.scalarMult.base(decodeCrock(priv1));
|
||||
//t.deepEqual(encodeCrock(myPub1), pub1);
|
||||
|
||||
//const p = nacl.box.keyPair.fromSecretKey(decodeCrock(priv1))
|
||||
//t.deepEqual(encodeCrock(p.publicKey), pub1);
|
||||
|
||||
//const r = nacl.scalarMult(decodeCrock(priv2), decodeCrock(pub1));
|
||||
//t.deepEqual(encodeCrock(nacl.hash(r)), skm);
|
||||
|
||||
//const mySkm = nacl.
|
||||
});
|
||||
|
||||
test("taler-exchange-tvg eddsa key", t => {
|
||||
const priv = "H2JGQ2T3A5WBC5QV3YRFE31AMRGF2F9WPXZ03EM3NS3PYHM80WA0";
|
||||
const pub = "QFGMB2WTPYXMXZRPFYFEM2VMQ028M71JMECF31P3J8VC3SCJ777G";
|
||||
|
||||
const pair = nacl.sign_keyPair_fromSeed(decodeCrock(priv));
|
||||
t.deepEqual(encodeCrock(pair.publicKey), pub);
|
||||
});
|
||||
|
@ -110,13 +110,13 @@ export function encodeCrock(data: ArrayBuffer): string {
|
||||
return sb;
|
||||
}
|
||||
|
||||
export function decodeCrock(encoded: string): ArrayBuffer {
|
||||
export function decodeCrock(encoded: string): Uint8Array {
|
||||
const size = encoded.length;
|
||||
let bitpos = 0;
|
||||
let bitbuf = 0;
|
||||
let readPosition = 0;
|
||||
const outLen = Math.floor((size * 5) / 8);
|
||||
const out = new Int8Array(outLen);
|
||||
const out = new Uint8Array(outLen);
|
||||
let outPos = 0;
|
||||
|
||||
while (readPosition < size || bitpos > 0) {
|
||||
|
429
src/crypto/sha256.ts
Normal file
429
src/crypto/sha256.ts
Normal file
@ -0,0 +1,429 @@
|
||||
// SHA-256 for JavaScript.
|
||||
//
|
||||
// Written in 2014-2016 by Dmitry Chestnykh.
|
||||
// Public domain, no warranty.
|
||||
//
|
||||
// Functions (accept and return Uint8Arrays):
|
||||
//
|
||||
// sha256(message) -> hash
|
||||
// sha256.hmac(key, message) -> mac
|
||||
//
|
||||
// Classes:
|
||||
//
|
||||
// new sha256.Hash()
|
||||
export const digestLength: number = 32;
|
||||
export const blockSize: number = 64;
|
||||
|
||||
// SHA-256 constants
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98,
|
||||
0x71374491,
|
||||
0xb5c0fbcf,
|
||||
0xe9b5dba5,
|
||||
0x3956c25b,
|
||||
0x59f111f1,
|
||||
0x923f82a4,
|
||||
0xab1c5ed5,
|
||||
0xd807aa98,
|
||||
0x12835b01,
|
||||
0x243185be,
|
||||
0x550c7dc3,
|
||||
0x72be5d74,
|
||||
0x80deb1fe,
|
||||
0x9bdc06a7,
|
||||
0xc19bf174,
|
||||
0xe49b69c1,
|
||||
0xefbe4786,
|
||||
0x0fc19dc6,
|
||||
0x240ca1cc,
|
||||
0x2de92c6f,
|
||||
0x4a7484aa,
|
||||
0x5cb0a9dc,
|
||||
0x76f988da,
|
||||
0x983e5152,
|
||||
0xa831c66d,
|
||||
0xb00327c8,
|
||||
0xbf597fc7,
|
||||
0xc6e00bf3,
|
||||
0xd5a79147,
|
||||
0x06ca6351,
|
||||
0x14292967,
|
||||
0x27b70a85,
|
||||
0x2e1b2138,
|
||||
0x4d2c6dfc,
|
||||
0x53380d13,
|
||||
0x650a7354,
|
||||
0x766a0abb,
|
||||
0x81c2c92e,
|
||||
0x92722c85,
|
||||
0xa2bfe8a1,
|
||||
0xa81a664b,
|
||||
0xc24b8b70,
|
||||
0xc76c51a3,
|
||||
0xd192e819,
|
||||
0xd6990624,
|
||||
0xf40e3585,
|
||||
0x106aa070,
|
||||
0x19a4c116,
|
||||
0x1e376c08,
|
||||
0x2748774c,
|
||||
0x34b0bcb5,
|
||||
0x391c0cb3,
|
||||
0x4ed8aa4a,
|
||||
0x5b9cca4f,
|
||||
0x682e6ff3,
|
||||
0x748f82ee,
|
||||
0x78a5636f,
|
||||
0x84c87814,
|
||||
0x8cc70208,
|
||||
0x90befffa,
|
||||
0xa4506ceb,
|
||||
0xbef9a3f7,
|
||||
0xc67178f2,
|
||||
]);
|
||||
|
||||
function hashBlocks(
|
||||
w: Int32Array,
|
||||
v: Int32Array,
|
||||
p: Uint8Array,
|
||||
pos: number,
|
||||
len: number,
|
||||
): number {
|
||||
let a: number,
|
||||
b: number,
|
||||
c: number,
|
||||
d: number,
|
||||
e: number,
|
||||
f: number,
|
||||
g: number,
|
||||
h: number,
|
||||
u: number,
|
||||
i: number,
|
||||
j: number,
|
||||
t1: number,
|
||||
t2: number;
|
||||
while (len >= 64) {
|
||||
a = v[0];
|
||||
b = v[1];
|
||||
c = v[2];
|
||||
d = v[3];
|
||||
e = v[4];
|
||||
f = v[5];
|
||||
g = v[6];
|
||||
h = v[7];
|
||||
|
||||
for (i = 0; i < 16; i++) {
|
||||
j = pos + i * 4;
|
||||
w[i] =
|
||||
((p[j] & 0xff) << 24) |
|
||||
((p[j + 1] & 0xff) << 16) |
|
||||
((p[j + 2] & 0xff) << 8) |
|
||||
(p[j + 3] & 0xff);
|
||||
}
|
||||
|
||||
for (i = 16; i < 64; i++) {
|
||||
u = w[i - 2];
|
||||
t1 =
|
||||
((u >>> 17) | (u << (32 - 17))) ^
|
||||
((u >>> 19) | (u << (32 - 19))) ^
|
||||
(u >>> 10);
|
||||
|
||||
u = w[i - 15];
|
||||
t2 =
|
||||
((u >>> 7) | (u << (32 - 7))) ^
|
||||
((u >>> 18) | (u << (32 - 18))) ^
|
||||
(u >>> 3);
|
||||
|
||||
w[i] = ((t1 + w[i - 7]) | 0) + ((t2 + w[i - 16]) | 0);
|
||||
}
|
||||
|
||||
for (i = 0; i < 64; i++) {
|
||||
t1 =
|
||||
((((((e >>> 6) | (e << (32 - 6))) ^
|
||||
((e >>> 11) | (e << (32 - 11))) ^
|
||||
((e >>> 25) | (e << (32 - 25)))) +
|
||||
((e & f) ^ (~e & g))) |
|
||||
0) +
|
||||
((h + ((K[i] + w[i]) | 0)) | 0)) |
|
||||
0;
|
||||
|
||||
t2 =
|
||||
((((a >>> 2) | (a << (32 - 2))) ^
|
||||
((a >>> 13) | (a << (32 - 13))) ^
|
||||
((a >>> 22) | (a << (32 - 22)))) +
|
||||
((a & b) ^ (a & c) ^ (b & c))) |
|
||||
0;
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + t1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (t1 + t2) | 0;
|
||||
}
|
||||
|
||||
v[0] += a;
|
||||
v[1] += b;
|
||||
v[2] += c;
|
||||
v[3] += d;
|
||||
v[4] += e;
|
||||
v[5] += f;
|
||||
v[6] += g;
|
||||
v[7] += h;
|
||||
|
||||
pos += 64;
|
||||
len -= 64;
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
// Hash implements SHA256 hash algorithm.
|
||||
export class HashSha256 {
|
||||
digestLength: number = digestLength;
|
||||
blockSize: number = blockSize;
|
||||
|
||||
// Note: Int32Array is used instead of Uint32Array for performance reasons.
|
||||
private state: Int32Array = new Int32Array(8); // hash state
|
||||
private temp: Int32Array = new Int32Array(64); // temporary state
|
||||
private buffer: Uint8Array = new Uint8Array(128); // buffer for data to hash
|
||||
private bufferLength: number = 0; // number of bytes in buffer
|
||||
private bytesHashed: number = 0; // number of total bytes hashed
|
||||
|
||||
finished: boolean = false; // indicates whether the hash was finalized
|
||||
|
||||
constructor() {
|
||||
this.reset();
|
||||
}
|
||||
|
||||
// Resets hash state making it possible
|
||||
// to re-use this instance to hash other data.
|
||||
reset(): this {
|
||||
this.state[0] = 0x6a09e667;
|
||||
this.state[1] = 0xbb67ae85;
|
||||
this.state[2] = 0x3c6ef372;
|
||||
this.state[3] = 0xa54ff53a;
|
||||
this.state[4] = 0x510e527f;
|
||||
this.state[5] = 0x9b05688c;
|
||||
this.state[6] = 0x1f83d9ab;
|
||||
this.state[7] = 0x5be0cd19;
|
||||
this.bufferLength = 0;
|
||||
this.bytesHashed = 0;
|
||||
this.finished = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Cleans internal buffers and re-initializes hash state.
|
||||
clean() {
|
||||
for (let i = 0; i < this.buffer.length; i++) {
|
||||
this.buffer[i] = 0;
|
||||
}
|
||||
for (let i = 0; i < this.temp.length; i++) {
|
||||
this.temp[i] = 0;
|
||||
}
|
||||
this.reset();
|
||||
}
|
||||
|
||||
// Updates hash state with the given data.
|
||||
//
|
||||
// Optionally, length of the data can be specified to hash
|
||||
// fewer bytes than data.length.
|
||||
//
|
||||
// Throws error when trying to update already finalized hash:
|
||||
// instance must be reset to use it again.
|
||||
update(data: Uint8Array, dataLength: number = data.length): this {
|
||||
if (this.finished) {
|
||||
throw new Error("SHA256: can't update because hash was finished.");
|
||||
}
|
||||
let dataPos = 0;
|
||||
this.bytesHashed += dataLength;
|
||||
if (this.bufferLength > 0) {
|
||||
while (this.bufferLength < 64 && dataLength > 0) {
|
||||
this.buffer[this.bufferLength++] = data[dataPos++];
|
||||
dataLength--;
|
||||
}
|
||||
if (this.bufferLength === 64) {
|
||||
hashBlocks(this.temp, this.state, this.buffer, 0, 64);
|
||||
this.bufferLength = 0;
|
||||
}
|
||||
}
|
||||
if (dataLength >= 64) {
|
||||
dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
|
||||
dataLength %= 64;
|
||||
}
|
||||
while (dataLength > 0) {
|
||||
this.buffer[this.bufferLength++] = data[dataPos++];
|
||||
dataLength--;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// Finalizes hash state and puts hash into out.
|
||||
//
|
||||
// If hash was already finalized, puts the same value.
|
||||
finish(out: Uint8Array): this {
|
||||
if (!this.finished) {
|
||||
const bytesHashed = this.bytesHashed;
|
||||
const left = this.bufferLength;
|
||||
const bitLenHi = (bytesHashed / 0x20000000) | 0;
|
||||
const bitLenLo = bytesHashed << 3;
|
||||
const padLength = bytesHashed % 64 < 56 ? 64 : 128;
|
||||
|
||||
this.buffer[left] = 0x80;
|
||||
for (let i = left + 1; i < padLength - 8; i++) {
|
||||
this.buffer[i] = 0;
|
||||
}
|
||||
this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff;
|
||||
this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff;
|
||||
this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff;
|
||||
this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff;
|
||||
this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff;
|
||||
this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff;
|
||||
this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff;
|
||||
this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff;
|
||||
|
||||
hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
|
||||
|
||||
this.finished = true;
|
||||
}
|
||||
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff;
|
||||
out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;
|
||||
out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;
|
||||
out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// Returns the final hash digest.
|
||||
digest(): Uint8Array {
|
||||
const out = new Uint8Array(this.digestLength);
|
||||
this.finish(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Internal function for use in HMAC for optimization.
|
||||
_saveState(out: Uint32Array) {
|
||||
for (let i = 0; i < this.state.length; i++) {
|
||||
out[i] = this.state[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Internal function for use in HMAC for optimization.
|
||||
_restoreState(from: Uint32Array, bytesHashed: number) {
|
||||
for (let i = 0; i < this.state.length; i++) {
|
||||
this.state[i] = from[i];
|
||||
}
|
||||
this.bytesHashed = bytesHashed;
|
||||
this.finished = false;
|
||||
this.bufferLength = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// HMAC implements HMAC-SHA256 message authentication algorithm.
|
||||
export class HMAC {
|
||||
private inner: HashSha256 = new HashSha256();
|
||||
private outer: HashSha256 = new HashSha256();
|
||||
|
||||
blockSize: number = this.inner.blockSize;
|
||||
digestLength: number = this.inner.digestLength;
|
||||
|
||||
// Copies of hash states after keying.
|
||||
// Need for quick reset without hashing they key again.
|
||||
private istate: Uint32Array;
|
||||
private ostate: Uint32Array;
|
||||
|
||||
constructor(key: Uint8Array) {
|
||||
const pad = new Uint8Array(this.blockSize);
|
||||
if (key.length > this.blockSize) {
|
||||
new HashSha256()
|
||||
.update(key)
|
||||
.finish(pad)
|
||||
.clean();
|
||||
} else {
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
pad[i] = key[i];
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < pad.length; i++) {
|
||||
pad[i] ^= 0x36;
|
||||
}
|
||||
this.inner.update(pad);
|
||||
|
||||
for (let i = 0; i < pad.length; i++) {
|
||||
pad[i] ^= 0x36 ^ 0x5c;
|
||||
}
|
||||
this.outer.update(pad);
|
||||
|
||||
this.istate = new Uint32Array(8);
|
||||
this.ostate = new Uint32Array(8);
|
||||
|
||||
this.inner._saveState(this.istate);
|
||||
this.outer._saveState(this.ostate);
|
||||
|
||||
for (let i = 0; i < pad.length; i++) {
|
||||
pad[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns HMAC state to the state initialized with key
|
||||
// to make it possible to run HMAC over the other data with the same
|
||||
// key without creating a new instance.
|
||||
reset(): this {
|
||||
this.inner._restoreState(this.istate, this.inner.blockSize);
|
||||
this.outer._restoreState(this.ostate, this.outer.blockSize);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Cleans HMAC state.
|
||||
clean() {
|
||||
for (let i = 0; i < this.istate.length; i++) {
|
||||
this.ostate[i] = this.istate[i] = 0;
|
||||
}
|
||||
this.inner.clean();
|
||||
this.outer.clean();
|
||||
}
|
||||
|
||||
// Updates state with provided data.
|
||||
update(data: Uint8Array): this {
|
||||
this.inner.update(data);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Finalizes HMAC and puts the result in out.
|
||||
finish(out: Uint8Array): this {
|
||||
if (this.outer.finished) {
|
||||
this.outer.finish(out);
|
||||
} else {
|
||||
this.inner.finish(out);
|
||||
this.outer.update(out, this.digestLength).finish(out);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// Returns message authentication code.
|
||||
digest(): Uint8Array {
|
||||
const out = new Uint8Array(this.digestLength);
|
||||
this.finish(out);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns SHA256 hash of data.
|
||||
export function sha256(data: Uint8Array): Uint8Array {
|
||||
const h = new HashSha256().update(data);
|
||||
const digest = h.digest();
|
||||
h.clean();
|
||||
return digest;
|
||||
}
|
||||
|
||||
// Returns HMAC-SHA256 of data under the key.
|
||||
export function hmacSha256(key: Uint8Array, data: Uint8Array) {
|
||||
const h = new HMAC(key).update(data);
|
||||
const digest = h.digest();
|
||||
h.clean();
|
||||
return digest;
|
||||
}
|
Loading…
Reference in New Issue
Block a user