-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
crypto-driver-noble.ts
71 lines (64 loc) · 2 KB
/
crypto-driver-noble.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
import { ICryptoDriver, KeypairBytes } from "./crypto-types.ts";
import { stringToBytes } from "../util/bytes.ts";
import { ed, sha256_uint8array } from "../../deps.ts";
const { createHash } = sha256_uint8array;
//--------------------------------------------------
import { Logger } from "../util/log.ts";
import { UpdatableHash } from "./updatable_hash.ts";
const logger = new Logger("crypto-driver-noble", "cyan");
//================================================================================
/**
* A version of the ICryptoDriver interface backed by noble/ed25519.
* The slowest crypto driver available, but works everywhere.
*/
export const CryptoDriverNoble: ICryptoDriver = class {
static sha256(
input: string | Uint8Array,
): Promise<Uint8Array> {
if (typeof input === "string") {
return Promise.resolve(
createHash("sha256").update(input, "utf-8").digest(),
);
} else {
return Promise.resolve(createHash("sha256").update(input).digest());
}
}
static updatableSha256() {
return new UpdatableHash({
hash: createHash("sha256"),
update: (hash, data) => hash.update(data),
digest: (hash) => hash.digest(),
});
}
static async generateKeypairBytes(): Promise<KeypairBytes> {
logger.debug("generateKeypairBytes");
const secret = ed.utils.randomPrivateKey();
const pubkey = await ed.getPublicKey(secret);
return {
pubkey,
secret,
};
}
static sign(
keypairBytes: KeypairBytes,
msg: string | Uint8Array,
): Promise<Uint8Array> {
logger.debug("sign");
if (typeof msg === "string") msg = stringToBytes(msg);
return ed.sign(msg, keypairBytes.secret);
}
static async verify(
publicKey: Uint8Array,
sig: Uint8Array,
msg: string | Uint8Array,
): Promise<boolean> {
logger.debug("verify");
try {
if (typeof msg === "string") msg = stringToBytes(msg);
const result = await ed.verify(sig, msg, publicKey);
return result;
} catch {
return false;
}
}
};