-
Notifications
You must be signed in to change notification settings - Fork 105
/
encryption.ts
70 lines (60 loc) · 2.11 KB
/
encryption.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
import { Field, Scalar, Group } from './core.js';
import { Poseidon } from './hash.js';
import { Provable } from './provable.js';
import { PrivateKey, PublicKey } from './signature.js';
export { encrypt, decrypt };
type CipherText = {
publicKey: Group;
cipherText: Field[];
};
/**
* Public Key Encryption, using a given array of {@link Field} elements and encrypts it using a {@link PublicKey}.
*/
function encrypt(message: Field[], otherPublicKey: PublicKey) {
// key exchange
let privateKey = Provable.witness(Scalar, () => Scalar.random());
let publicKey = Group.generator.scale(privateKey);
let sharedSecret = otherPublicKey.toGroup().scale(privateKey);
let sponge = new Poseidon.Sponge();
sponge.absorb(sharedSecret.x); // don't think we need y, that's enough entropy
// encryption
let cipherText = [];
for (let i = 0; i < message.length; i++) {
let keyStream = sponge.squeeze();
let encryptedChunk = message[i].add(keyStream);
cipherText.push(encryptedChunk);
// absorb for the auth tag (two at a time for saving permutations)
if (i % 2 === 1) sponge.absorb(cipherText[i - 1]);
if (i % 2 === 1 || i === message.length - 1) sponge.absorb(cipherText[i]);
}
// authentication tag
let authenticationTag = sponge.squeeze();
cipherText.push(authenticationTag);
return { publicKey, cipherText };
}
/**
* Decrypts a {@link CipherText} using a {@link PrivateKey}.^
*/
function decrypt(
{ publicKey, cipherText }: CipherText,
privateKey: PrivateKey
) {
// key exchange
let sharedSecret = publicKey.scale(privateKey.s);
let sponge = new Poseidon.Sponge();
sponge.absorb(sharedSecret.x);
let authenticationTag = cipherText.pop();
// decryption
let message = [];
for (let i = 0; i < cipherText.length; i++) {
let keyStream = sponge.squeeze();
let messageChunk = cipherText[i].sub(keyStream);
message.push(messageChunk);
if (i % 2 === 1) sponge.absorb(cipherText[i - 1]);
if (i % 2 === 1 || i === cipherText.length - 1)
sponge.absorb(cipherText[i]);
}
// authentication tag
sponge.squeeze().assertEquals(authenticationTag!);
return message;
}