-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto-secretbox.c
83 lines (70 loc) · 1.97 KB
/
crypto-secretbox.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
/*
%use buffer_put;
%use buffer_0;
%use buffer_1;
%use buffer_2;
%use openreadclose;
%use env;
%use strerr_die;
%use strerr_sys;
%use stralloc_ready;
%use surf;
%use crypto_str_box_beforenm;
%use crypto_str_box_afternm;
%use crypto_str_secretbox;
%use netstring_write;
%use readchunk;
%use stralloc_copys;
%use error_str;
*/
/* Public Domain */
#include <nacl/crypto_secretbox.h>
#include "surf.h"
#include "crypto_str.h"
#include "stralloc.h"
#include "buffer.h"
#include "strerr.h"
#include "open.h"
#include "openreadclose.h"
#include "readchunk.h"
#include "byte.h"
#include "netstring.h"
static stralloc key = {0};
static stralloc m = {0};
static stralloc c = {0};
static stralloc n = {0};
#define FATAL "crypto-secretbox: error: "
int main(int argc, char * argv[])
{
int r;
/* Check args */
if(argc!=2)
strerr_die1x(111,"crypto-secretbox: usage: crypto-secretbox secretkeyfile");
/* Read key */
if(openreadclose(argv[1],&key,crypto_secretbox_KEYBYTES)<=0)
strerr_die2sys(111,FATAL,"unable to read secret key: ");
/* Allocate space for nonce */
if(!stralloc_ready(&n,crypto_secretbox_NONCEBYTES)) return 111;
n.len = crypto_secretbox_NONCEBYTES;
/* Encrypt each chunk */
for (;;) {
/* Read message */
if((r=readchunk(&m,buffer_0))==-1)
strerr_die2sys(111,FATAL,"unable to read input: ");
else if(r==0)
break;
/* Create nonce */
surf_randombytes((unsigned char*)n.s,crypto_secretbox_NONCEBYTES);
/* Encrypt message */
if(crypto_str_secretbox(&c,&m,&n,&key)!=0)
strerr_die2x(111,FATAL,"encryption failed");
/* Write nonce */
if(netstring_write(buffer_1,n.s,n.len)!=0)
strerr_die2sys(111,FATAL,"failed to output nonce: ");
/* Write cipher */
if(netstring_write(buffer_1,c.s,c.len)!=0)
strerr_die2sys(111,FATAL,"failed to output cipher: ");
}
buffer_flush(buffer_1);
return 0;
}