-
Notifications
You must be signed in to change notification settings - Fork 3
/
asymmetric.ts
39 lines (34 loc) · 1.38 KB
/
asymmetric.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
import { packSymmetricalyEncryptedData, unpackSymmetricalyEncryptedData } from './symmetric';
import { YlideMisusageError } from '../errors/YlideMisusageError';
import { randomBytes, box as naclbox } from 'tweetnacl';
/**
* @category Crypto
* @description Method to asymmetrically encrypt the data using *x25519-xsalsa20-poly1305* algorithm.
*
* @param data Data to encrypt
* @param mySecretKey My private key
* @param theirPublicKey Recipient's public key
* @returns Encrypted data
*/
export const asymmetricEncrypt = (data: Uint8Array, mySecretKey: Uint8Array, theirPublicKey: Uint8Array) => {
const nonce = randomBytes(24);
const encData = naclbox(data, nonce, theirPublicKey, mySecretKey);
return packSymmetricalyEncryptedData(encData, nonce);
};
/**
* @category Crypto
* @description Method to asymmetrically decrypt the data using *x25519-xsalsa20-poly1305* algorithm.
*
* @param data Data to decrypt
* @param mySecretKey My private key
* @param theirPublicKey Sender's public key
* @returns Decrypted data
*/
export const asymmetricDecrypt = (data: Uint8Array, mySecretKey: Uint8Array, theirPublicKey: Uint8Array) => {
const { nonce, encData } = unpackSymmetricalyEncryptedData(data);
const decData = naclbox.open(encData, nonce, theirPublicKey, mySecretKey);
if (!decData) {
throw new YlideMisusageError('asymmetricDecrypt', 'Invalid box or key');
}
return decData;
};