-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.c
66 lines (48 loc) · 1.34 KB
/
encrypt.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
#include <stdio.h>
#include <string.h>
#include <gmp.h>
extern int readPublicKey(mpz_t e, mpz_t n);
extern int readPlainText(mpz_t pt);
// Function computing ciphertext
//
// Parameter:
// ct: ciphertext
// pt: plaintext
// e
// n
void computeCiphertext(mpz_t ct, mpz_t pt, mpz_t e, mpz_t n) {
mpz_powm(ct, pt, e, n);
}
// Function saving ciphertext
//
// Parameter:
// pt: plaintext
// ct: ciphertext
void saveCiphertext(mpz_t pt, mpz_t ct) {
FILE *ciphertext_file;
// Save ciphertext
ciphertext_file = fopen("./text/ciphertext", "wt");
gmp_fprintf(ciphertext_file, "%Zd", ct);
fclose(ciphertext_file);
// Print descriptions
printf("\nPlaintext\n");
gmp_printf(" : %Zd\n\n", pt);
printf("Encrypted ciphertext\n");
gmp_printf(" : %Zd\n\n", ct);
printf("The encrypted ciphertext is stored in ./text/ciphertext.\n\n");
}
// Encrypting function
void encrypt() {
mpz_t e, n;
mpz_t pt, ct;
mpz_inits(e, n, pt, ct, NULL);
// 1. Read public key
if (readPublicKey(e, n) == -1) { return; }
// 2. Read plaintext
if (readPlainText(pt) == -1) { return; }
// 3. Compute ciphertext
computeCiphertext(ct, pt, e, n);
// 4. Save ciphertext
saveCiphertext(pt, ct);
mpz_clears(e, n, pt, ct, NULL);
}