summaryrefslogtreecommitdiff
path: root/hbbp_keygen.c
blob: f464441231119b4138aab6ad25d1741fb467eb2d (plain)
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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "common.h"
#include "crypto.h"

#define pub_len  crypto_box_PUBLICKEYBYTES
#define priv_len crypto_box_SECRETKEYBYTES

const char *name[4] = {"recv.pub", "recv.priv", "send.pub", "send.priv"};

void error_cleanup(int num) {
    for (int i = 0; i < num; i++)
	unlink(name[i]);
    exit(1);
}

// used by nacl's crypto_box_keypair
void randombytes(byte *buf, unsigned long long len)
  __attribute__ ((externally_visible));

void randombytes(byte *buf, unsigned long long len) {
  int fd = open("/dev/urandom", O_RDONLY);
  if (fd == -1) goto error;

  while (len > 0) {
    int sz = read(fd, buf, len);
    if (sz < 1) goto error;
    buf += sz;
    len -= sz;
  }
  return;

 error:
  perror("failed accessing /dev/urandom");
  error_cleanup(4);
}

int main() {
  int fd[4], i;
  byte key_pub [2][pub_len],
       key_priv[2][priv_len];

  /* open files */
  for (i=0; i<4; i++) {
    if ((fd[i] = open(name[i], O_WRONLY|O_CREAT|O_EXCL,
		      (i%2) ? 0400 : 0444)) == -1) {
      fprintf(stderr, 
	      (errno == EEXIST)
	      ? "%s already exists\n" : "could not create file %s\n",
	      name[i]);
      error_cleanup(i);
    }
  }

  /* generate keys */
  for (i=0; i<2; i++) {
    crypto_box_keypair(key_pub[i], key_priv[i]);
    if ((write(fd[2*i  ], key_pub[i],  pub_len)  != pub_len)
     || (write(fd[2*i+1], key_priv[i], priv_len) != priv_len)
     || (close(fd[2*i  ]) == -1)
     || (close(fd[2*i+1]) == -1)) {
      error_cleanup(4);
    }
  }

  return 0;
}
contact: Jan Huwald // Impressum