-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto-secretbox-open.c
68 lines (56 loc) · 1.65 KB
/
crypto-secretbox-open.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
/*
%use buffer_0;
%use buffer_1;
%use strerr_die;
%use strerr_sys;
%use openreadclose;
%use netstring_read;
%use buffer_put;
%use crypto_str_secretbox_open;
*/
/* Public Domain */
#include <nacl/crypto_secretbox.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-open: error: "
int main(int argc, char * argv[])
{
int r;
/* Check args */
if(argc!=2)
strerr_die1x(100,"crypto-secretbox-open: usage: crypto-secretbox-open secretkeyfile");
/* Read secret key */
if(openreadclose(argv[1],&key,crypto_secretbox_KEYBYTES)<=0)
strerr_die2sys(111,FATAL,"unable to read secret key: ");
/* Decrypt each chunk */
for (;;) {
/* Read nonce */
if((r=netstring_read(buffer_0,&n))!=0)
strerr_die2x(111,FATAL,"failed to read nonce");
if(n.len==0) break;
if(n.len!=crypto_secretbox_NONCEBYTES)
strerr_die2x(111,FATAL,"nonce was incorrect size");
/* Read cipher */
if(netstring_read(buffer_0,&c)!=0)
strerr_die2x(111,FATAL,"failed to read cipher");
/* Decrypt message */
if(crypto_str_secretbox_open(&m,&c,&n,&key)!=0)
strerr_die2x(111,FATAL,"decryption failed");
/* Write message */
if(buffer_put(buffer_1,m.s,m.len)!=0)
strerr_die2x(111,FATAL,"failed to output message: ");
}
buffer_flush(buffer_1);
return 0;
}