-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
225 lines (197 loc) · 5.9 KB
/
index.ts
File metadata and controls
225 lines (197 loc) · 5.9 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import * as secp from "@noble/secp256k1";
export type Keypair = { sk: Uint8Array; pk: Uint8Array };
export function generateKeypair(): Keypair {
const sk = secp.utils.randomPrivateKey();
const pk = secp.getPublicKey(sk, true);
return { sk, pk };
}
export function fromHex(hex: Uint8Array | string): Uint8Array {
return isBytes(hex)
? Uint8Array.from(hex as any)
: secp.hexToBytes(removePrefix(hex as string));
}
export function toHex(uint8: Uint8Array, withPrefix: boolean = false): string {
const hex = Array.from(uint8)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
return withPrefix ? "0x" + hex : hex;
}
export async function getCrypto(): Promise<Crypto> {
return typeof globalThis.crypto !== "undefined"
? globalThis.crypto
: ((await import("node:crypto")).webcrypto as Crypto);
}
function isBytes(bytes: Uint8Array | string): boolean {
return (
bytes instanceof Uint8Array ||
(ArrayBuffer.isView(bytes) && bytes.constructor.name === "Uint8Array")
);
}
function removePrefix(hex: string): string {
return hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
}
export async function encrypt(
message: string,
recipientPubHex: string,
cryptoAPI: Crypto
): Promise<string> {
const encoded = new TextEncoder().encode(message);
const out = await _encrypt(encoded, fromHex(recipientPubHex), cryptoAPI);
return toHex(out);
}
export async function decrypt(
ciphertextHex: string,
recipientSkHex: string,
cryptoAPI: Crypto
): Promise<string> {
const decrypted = await _decrypt(
fromHex(ciphertextHex),
fromHex(recipientSkHex),
cryptoAPI
);
return new TextDecoder().decode(decrypted);
}
export async function encryptPadded(
message: string,
recipientPubHex: string,
cryptoAPI: Crypto,
paddedLength: number
): Promise<string> {
if (paddedLength < message.length + 4) {
throw new Error(
`Invalid padded length ${paddedLength} bytes, expected at least ${
message.length + 4
} bytes)`
);
}
let encoded = new Uint8Array(paddedLength);
// prepend with the message length info in little endian (4 bytes)
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setUint32(0, message.length, true);
encoded.set(new Uint8Array(buffer), 0);
const encodedMessage = new TextEncoder().encode(message);
encoded.set(encodedMessage, 4);
const encrypted = await _encrypt(
encoded,
fromHex(recipientPubHex),
cryptoAPI
);
return toHex(encrypted);
}
export async function decryptPadded(
ciphertextHex: string,
recipientSkHex: string,
cryptoAPI: Crypto,
paddedLength: number
): Promise<string> {
const decrypted = await _decrypt(
fromHex(ciphertextHex),
fromHex(recipientSkHex),
cryptoAPI
);
if (decrypted.length != paddedLength) {
throw new Error(
`Invalid padded length ${decrypted.length} bytes, expected ${paddedLength} bytes)`
);
}
return decodePadded(decrypted);
}
export async function decryptPaddedUnchecked(
ciphertextHex: string,
recipientSkHex: string,
cryptoAPI: Crypto
): Promise<string> {
const decrypted = await _decrypt(
fromHex(ciphertextHex),
fromHex(recipientSkHex),
cryptoAPI
);
return await decodePadded(decrypted);
}
async function hkdf(
sharedSecret: Uint8Array,
cryptoAPI: Crypto
): Promise<CryptoKey> {
const keyMaterial = await cryptoAPI.subtle.importKey(
"raw",
sharedSecret as BufferSource,
"HKDF",
false,
["deriveKey"]
);
return await cryptoAPI.subtle.deriveKey(
{
name: "HKDF",
hash: "SHA-256",
salt: new Uint8Array([]),
info: new TextEncoder().encode("ecies-secp256k1-v1") as BufferSource,
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
async function _encrypt(
message: Uint8Array,
recipientPk: Uint8Array,
cryptoAPI: Crypto
): Promise<Uint8Array> {
const recipientPub = secp.Point.fromHex(recipientPk);
const ephSk = secp.utils.randomPrivateKey();
const ephPk = secp.getPublicKey(ephSk, true);
const ephSkBigInt = BigInt(toHex(ephSk, true));
const shared = recipientPub.multiply(ephSkBigInt).toRawBytes(true);
const aesKey = await hkdf(shared, cryptoAPI);
const iv = cryptoAPI.getRandomValues(new Uint8Array(12));
const ciphertextBuffer = await cryptoAPI.subtle.encrypt(
{ name: "AES-GCM", iv },
aesKey,
message as BufferSource
);
const ciphertext = new Uint8Array(ciphertextBuffer);
const out = new Uint8Array(ephPk.length + iv.length + ciphertext.length);
out.set(ephPk);
out.set(iv, ephPk.length);
out.set(ciphertext, ephPk.length + iv.length);
return out;
}
async function _decrypt(
ciphertextBytes: Uint8Array,
recipientSkBytes: Uint8Array,
cryptoAPI: Crypto
): Promise<Uint8Array> {
const ephPk = secp.Point.fromHex(ciphertextBytes.slice(0, 33));
const iv = ciphertextBytes.slice(33, 45);
const ciphertext = ciphertextBytes.slice(45);
const skBigInt = BigInt(toHex(recipientSkBytes, true));
const shared_point = ephPk.multiply(skBigInt);
let shared = shared_point.toRawBytes(true);
const aesKey = await hkdf(shared, cryptoAPI);
const plaintextBuffer = await cryptoAPI.subtle.decrypt(
{ name: "AES-GCM", iv },
aesKey,
ciphertext as BufferSource
);
return new Uint8Array(plaintextBuffer);
}
async function decodePadded(paddedMessage: Uint8Array): Promise<string> {
if (paddedMessage.length < 4) {
throw new Error(
`Invalid padded length ${
paddedMessage.length
} bytes, expected at least ${4} bytes)`
);
}
const view = new DataView(paddedMessage.buffer);
const messageLength = view.getUint32(0, true);
if (messageLength > paddedMessage.length - 4) {
throw new Error(
`Invalid message length ${messageLength} bytes, expected at most ${
paddedMessage.length - 4
} bytes)`
);
}
return new TextDecoder().decode(paddedMessage.subarray(4, messageLength + 4));
}