summaryrefslogtreecommitdiff
path: root/lib/utils/bit.ts
blob: bc1ed1aff8556fd7e5906980c2e25c5f96c4b4df (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
import { sha256 } from "urbit-key-generation/src/utils";

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");
}