-
Notifications
You must be signed in to change notification settings - Fork 9
/
tweetnacl-encrypt.c
65 lines (54 loc) · 2.05 KB
/
tweetnacl-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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "randombytes.h"
#include "tools.h"
#include "tweetnacl.h"
int main(int argc, char *argv[]) {
if (argc != 5) error(2,
"Usage: tweetnacl-encrypt send-key.sec recv-key.pub text.txt text.enc");
// This will also erroneously fail if the file "-" exists
if (file_exists(argv[4])) errorf(1, "File <%s> exists", argv[4]);
// Alice is sending to Bob, not surprisingly
unsigned char a_secret_key[crypto_box_SECRETKEYBYTES];
unsigned char b_public_key[crypto_box_PUBLICKEYBYTES];
read_key(argv[1], a_secret_key, crypto_box_SECRETKEYBYTES);
read_key(argv[2], b_public_key, crypto_box_PUBLICKEYBYTES);
unsigned char nonce[crypto_box_NONCEBYTES];
randombytes(nonce, sizeof(nonce));
FILE *out;
if (strcmp(argv[4], "-") != 0) {
out = create_file(argv[4]);
fwrite(nonce, sizeof(nonce), 1, out);
} else {
out = stdout;
fwrite(bytes_to_hex(nonce, sizeof(nonce)), sizeof(nonce) * 2, 1, out);
fputs("\n", out);
}
// Input
// unsigned char *message = read_file(argv[3]);
Content c = read_file(argv[3]);
long psize = crypto_box_ZEROBYTES + c.size;
unsigned char *padded = malloc(psize);
if (padded == NULL) error(1, "Malloc failed!");
memset(padded, 0, crypto_box_ZEROBYTES);
memcpy(padded + crypto_box_ZEROBYTES, c.bytes, c.size);
free(c.bytes);
// Output
unsigned char *encrypted = calloc(psize, sizeof(unsigned char));
if (encrypted == NULL) error(1, "Calloc failed!");
// Encrypt
crypto_box(encrypted, padded, psize, nonce, b_public_key, a_secret_key);
free(padded);
if (out != stdout) {
fwrite(encrypted + crypto_box_BOXZEROBYTES,
psize - crypto_box_BOXZEROBYTES, 1, out);
} else {
fwrite(bytes_to_hex(encrypted + crypto_box_BOXZEROBYTES,
psize - crypto_box_BOXZEROBYTES),
(psize - crypto_box_BOXZEROBYTES) * 2, 1, out);
fputs("\n", out);
}
free(encrypted);
return 0;
}