forked from pq-crystals/kyber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_kyber.c
107 lines (82 loc) · 2.51 KB
/
test_kyber.c
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
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include "api.h"
#include "randombytes.h"
#define NTESTS 1000
static int test_keys()
{
unsigned int i;
unsigned char pk[CRYPTO_PUBLICKEYBYTES];
unsigned char sk[CRYPTO_SECRETKEYBYTES];
unsigned char ct[CRYPTO_CIPHERTEXTBYTES];
unsigned char key_a[CRYPTO_BYTES];
unsigned char key_b[CRYPTO_BYTES];
for(i=0;i<NTESTS;i++) {
//Alice generates a public key
crypto_kem_keypair(pk, sk);
//Bob derives a secret key and creates a response
crypto_kem_enc(ct, key_b, pk);
//Alice uses Bobs response to get her shared key
crypto_kem_dec(key_a, ct, sk);
if(memcmp(key_a, key_b, CRYPTO_BYTES))
printf("ERROR keys\n");
}
return 0;
}
static int test_invalid_sk_a()
{
unsigned int i;
unsigned char pk[CRYPTO_PUBLICKEYBYTES];
unsigned char sk[CRYPTO_SECRETKEYBYTES];
unsigned char ct[CRYPTO_CIPHERTEXTBYTES];
unsigned char key_a[CRYPTO_BYTES];
unsigned char key_b[CRYPTO_BYTES];
for(i=0;i<NTESTS;i++) {
//Alice generates a public key
crypto_kem_keypair(pk, sk);
//Bob derives a secret key and creates a response
crypto_kem_enc(ct, key_b, pk);
//Replace secret key with random values
randombytes(sk, CRYPTO_SECRETKEYBYTES);
//Alice uses Bobs response to get her shared key
crypto_kem_dec(key_a, ct, sk);
if(!memcmp(key_a, key_b, CRYPTO_BYTES))
printf("ERROR invalid sk\n");
}
return 0;
}
static int test_invalid_ciphertext()
{
unsigned int i;
unsigned char pk[CRYPTO_PUBLICKEYBYTES];
unsigned char sk[CRYPTO_SECRETKEYBYTES];
unsigned char ct[CRYPTO_CIPHERTEXTBYTES];
unsigned char key_a[CRYPTO_BYTES];
unsigned char key_b[CRYPTO_BYTES];
size_t pos;
for(i=0;i<NTESTS;i++) {
randombytes((unsigned char *)&pos, sizeof(size_t));
//Alice generates a public key
crypto_kem_keypair(pk, sk);
//Bob derives a secret key and creates a response
crypto_kem_enc(ct, key_b, pk);
//Change some byte in the ciphertext (i.e., encapsulated key)
ct[pos % CRYPTO_CIPHERTEXTBYTES] ^= 23;
//Alice uses Bobs response to get her shared key
crypto_kem_dec(key_a, ct, sk);
if(!memcmp(key_a, key_b, CRYPTO_BYTES))
printf("ERROR invalid ciphertext\n");
}
return 0;
}
int main(void)
{
test_keys();
test_invalid_sk_a();
test_invalid_ciphertext();
printf("CRYPTO_SECRETKEYBYTES: %d\n",CRYPTO_SECRETKEYBYTES);
printf("CRYPTO_PUBLICKEYBYTES: %d\n",CRYPTO_PUBLICKEYBYTES);
printf("CRYPTO_CIPHERTEXTBYTES: %d\n",CRYPTO_CIPHERTEXTBYTES);
return 0;
}