summaryrefslogtreecommitdiff
path: root/lib/utils/bit.ts
blob: e54cd418b259cefa5d07eab8efceae6e188352ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { sha256 } from "urbit-key-generation/src/utils";

import "core-js/actual/typed-array";

export function shas(buf: Buffer, salt: Buffer) {
  return sha256(xor(salt, sha256(buf)));
}

export function xor(a: Buffer, b: Buffer) {
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    console.log("a", a);
    console.log("b", b);
    throw new Error("only xor buffers!");
  }
  const length = Math.max(a.byteLength, b.byteLength);
  const result = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    result[i] = a[i] ^ b[i];
  }
  return result;
}

export function shaf(buf: Buffer, salt: Buffer) {
  const result = shas(buf, salt);
  const halfway = result.length / 2;
  const front = result.slice(0, halfway);
  const back = result.slice(halfway, result.length);
  return xor(front, back);
}

export function hex2buf(hex: string) {
  return Buffer.from(hex, "hex").reverse();
}

export function buf2hex(buf: Uint8Array) {
  return Buffer.from(buf).reverse().toString("hex");
}
export function hex2bytes(hex: string) {
  const clean = hex.replace(/^0x/i, "");
  const ba = Uint8Array.fromHex(clean);
  return ba;
}

export function bytes2hex(ta: Uint8Array) {
  return ta.toHex();
}