-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSchnorr.ts
77 lines (61 loc) · 1.9 KB
/
Schnorr.ts
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import bigInt from "big-integer";
const crypto = require("crypto-js");
import {
exponentiationInField,
multiplyInField,
subtractInField,
} from "./field_math_exports";
const P = bigInt("15943542169520389343");
const Q = bigInt("7971771084760194671");
const g = bigInt(2);
function pickNumber(min: bigInt.BigInteger, max: bigInt.BigInteger) {
while (true) {
let pick = bigInt.randBetween(min, max);
if (bigInt.gcd(pick, Q).equals(bigInt(1))) {
return pick;
}
}
}
function sign(message: string, x: bigInt.BigInteger) {
const k = pickNumber(bigInt(1), Q.minus(bigInt(1)));
console.log("k: " + k);
console.log("Q: " + Q);
const r = exponentiationInField(g, k, P);
const toHash = r.toString(16) + message;
const e = crypto.SHA256(toHash); // ? hash
const HASH = e.toString();
const HASH_AS_INT = bigInt(HASH, 16);
console.log("HASHASINT :" + HASH_AS_INT);
const xe = multiplyInField(x, HASH_AS_INT, Q);
const s = subtractInField(k, xe, Q);
console.log("sign : " + [s, e]);
return [s, HASH_AS_INT];
}
function verify(
y: bigInt.BigInteger,
e: bigInt.BigInteger,
s: bigInt.BigInteger,
message: string
): boolean {
const gs = exponentiationInField(g, s, P);
const ye = exponentiationInField(y, e, P);
const rv = multiplyInField(gs, ye, P);
const rv_to_string = rv.toString(16) + message;
const ev = crypto.SHA256(rv_to_string).toString();
const ev_to_int = bigInt(ev, 16);
console.log("e : " + e);
console.log("evt : " + ev_to_int);
const isequal = ev_to_int.compare(e);
isequal === 0 ? console.log(true) : console.log(false);
return isequal == 0 ? true : false;
}
function getPublicAndPrivate() {
const x = pickNumber(bigInt(1), Q.minus(bigInt(1)));
// ? private key
const y = exponentiationInField(g, x, P);
// ? public key
const [s, e] = sign("hi", x);
verify(y, e, s, "hix");
console.log("public key: " + y);
}
getPublicAndPrivate();