]> err.no Git - backuppcd/blob - backuppcd-passwd.c
Import gnulib stuff
[backuppcd] / backuppcd-passwd.c
1 #include "compat.h"
2 #include "lib/sha1.h"
3 #include <stdio.h>
4
5 static char * sha1sum(char *string) {
6         unsigned char digest[20];
7         static char ret[(sizeof(digest) * 2) + 1] = {0};
8         static char hexabet[] = "0123456789abcdef";
9         struct sha1_ctx ctx;
10         int retcnt = 0, i;
11
12         sha1_init_ctx(&ctx);
13
14         sha1_process_bytes(string, strlen(string), &ctx);
15
16         sha1_finish_ctx(&ctx, digest);
17
18         for (i = 0; i < sizeof(digest); i++) {
19                 ret[retcnt++] = hexabet[(digest[i] & 0xf0) >> 4];
20                 ret[retcnt++] = hexabet[digest[i] & 0xf];
21         }
22
23         ret[retcnt] = '\0';
24
25         return(ret);
26 }
27
28 int main(int argc, char **argv) {
29         char *plaintext;
30         char *fgets_ret;
31         int fail_cnt = 0;
32
33         if (argc == 1) {
34                 plaintext = malloc(1024);
35                 if (!plaintext) {
36                         perror("malloc");
37                         return(EXIT_FAILURE);
38                 }
39
40                 plaintext[0] = '\0';
41
42                 while (plaintext[0] == '\0' && fail_cnt < 3) {
43                         printf("Password: ");
44                         fflush(stdout);
45
46                         fgets_ret = fgets(plaintext, 1024, stdin);
47                         if (!fgets_ret) {
48                                 perror("fgets");
49                                 return(EXIT_FAILURE);
50                         }
51
52                         if (plaintext[strlen(plaintext) - 1] == '\n') {
53                                 plaintext[strlen(plaintext) - 1] = '\0';
54                         }
55
56                         fail_cnt++;
57                 }
58         } else if (argc > 1) {
59                 plaintext = argv[1];
60         } else {
61                 return(EXIT_FAILURE);
62         }
63
64         if (plaintext[0] == '\0') {
65                 printf("Invalid password specified, aborting.\n");
66                 exit(EXIT_FAILURE);
67         }
68
69         printf("%s\n", sha1sum(plaintext));
70
71         return(EXIT_SUCCESS);
72 }