-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
62 lines (53 loc) · 1.81 KB
/
Copy pathindex.ts
File metadata and controls
62 lines (53 loc) · 1.81 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
import { box, randomBytes } from "tweetnacl";
import {
decodeUTF8,
encodeUTF8,
encodeBase64,
decodeBase64,
} from "tweetnacl-util";
const newNonce = () => randomBytes(box.nonceLength);
export const generateKeyPair = () => box.keyPair();
export const encrypt = (
secretOrSharedKey: Uint8Array,
json: any,
key?: Uint8Array
) => {
const nonce = newNonce();
const messageUint8 = decodeUTF8(JSON.stringify(json));
const encrypted = key
? box(messageUint8, nonce, key, secretOrSharedKey)
: box.after(messageUint8, nonce, secretOrSharedKey);
const fullMessage = new Uint8Array(nonce.length + encrypted.length);
fullMessage.set(nonce);
fullMessage.set(encrypted, nonce.length);
const base64FullMessage = encodeBase64(fullMessage);
return base64FullMessage;
};
export const decrypt = (
secretOrSharedKey: Uint8Array,
messageWithNonce: string,
key?: Uint8Array
) => {
const messageWithNonceAsUint8Array = decodeBase64(messageWithNonce);
const nonce = messageWithNonceAsUint8Array.slice(0, box.nonceLength);
const message = messageWithNonceAsUint8Array.slice(
box.nonceLength,
messageWithNonce.length
);
const decrypted = key
? box.open(message, nonce, key, secretOrSharedKey)
: box.open.after(message, nonce, secretOrSharedKey);
if (!decrypted) {
throw new Error("Could not decrypt message");
}
const base64DecryptedMessage = encodeUTF8(decrypted);
return JSON.parse(base64DecryptedMessage);
};
const user = { name: "JOHN Doe", password: "1234567890" };
const pairA = generateKeyPair();
const pairB = generateKeyPair();
const sharedA = box.before(pairB.publicKey, pairA.secretKey);
const sharedB = box.before(pairA.publicKey, pairB.secretKey);
const encrypted = encrypt(sharedA, user);
const decrypted = decrypt(sharedB, encrypted);
console.log(user, encrypted, decrypted);