-
Notifications
You must be signed in to change notification settings - Fork 1
/
tweetnacl-example.js
54 lines (43 loc) · 1.6 KB
/
tweetnacl-example.js
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
import tweetnaclpkg from 'tweetnacl';
const { secretbox, randomBytes } = tweetnaclpkg;
import tweetnacl_utilpkg from 'tweetnacl-util';
const {
decodeUTF8,
encodeUTF8,
encodeBase64,
decodeBase64
} = tweetnacl_utilpkg;
const newNonce = () => randomBytes(secretbox.nonceLength);
export const generateKey = () => encodeBase64(randomBytes(secretbox.keyLength));
export const encrypt = (json, key) => {
const keyUint8Array = decodeBase64(key);
const nonce = newNonce();
const messageUint8 = decodeUTF8(JSON.stringify(json));
const box = secretbox(messageUint8, nonce, keyUint8Array);
const fullMessage = new Uint8Array(nonce.length + box.length);
fullMessage.set(nonce);
fullMessage.set(box, nonce.length);
const base64FullMessage = encodeBase64(fullMessage);
return base64FullMessage;
};
export const decrypt = (messageWithNonce, key) => {
const keyUint8Array = decodeBase64(key);
const messageWithNonceAsUint8Array = decodeBase64(messageWithNonce);
const nonce = messageWithNonceAsUint8Array.slice(0, secretbox.nonceLength);
const message = messageWithNonceAsUint8Array.slice(
secretbox.nonceLength,
messageWithNonce.length
);
const decrypted = secretbox.open(message, nonce, keyUint8Array);
if (!decrypted) {
throw new Error("Could not decrypt message");
}
const base64DecryptedMessage = encodeUTF8(decrypted);
return JSON.parse(base64DecryptedMessage);
};
const key = generateKey();
const obj = { "hello": "world" };
const encrypted = encrypt(obj, key);
const decrypted = decrypt(encrypted, key);
console.log(encrypted);
console.log(decrypted); // should be shallow equal