prototype IR and parser
[henge/webcc.git] / src / core / auth.c
1 /*!@file
2 \brief Password Encyption and Storing
3 \details hashes password using SHA256 and saves result in a file on VFS using
4 hashing algorithm provided by wolfcrypt(wc), a subsystem of wolfSSL
5 \author JEL
6 \date 2016
7 -----------------------------------------------------------------------------*/
8 #include <stddef.h>
9 #include <stdio.h>
10 #include <wolfssl/wolfcrypt/sha256.h>
11 #include <emscripten.h>
12
13 word32 str_len(const char*);
14 int auth_encrypt(int argc, char** argv);
15 void store_password(byte*);
16
17 /* Should come with wolfcrypt type.h */
18 /* typedef unsigned int word32; */
19
20 word32
21 str_len (const char* str)
22 {
23 const char* strl;
24
25 for (strl = str; *strl != '\0'; ++strl)
26 {
27 /* nothing to be done */;
28 }
29 return strl - str;
30 }
31
32
33 /* Takes a string and hashes it, returning
34 the encrypted string as a result */
35
36 int
37 auth_encrypt(int argc, char** argv)
38 {
39 /* Determine length of password */
40 word32 len = 0;
41 char* password;
42 byte hash[32]; /* 32bytes * 8 = 256, the # bits of hash */
43 const unsigned char c_password[32]; /* Passwords are between 8-32 chars */
44 Sha256 sha256[1]; /* Init a Sha256 type for wc */
45
46
47 password = argv[0];
48 len = str_len(password);
49
50 /* Converting password to unsigned const char* for wc_functions */
51 memcpy( (void*) c_password, (void*) password, len+1);
52
53 if (wc_InitSha256(sha256) != 0 )
54 {
55 printf("wc_InitSha256 failed\n");
56 }
57 else
58 {
59 wc_Sha256Update(sha256, c_password, len);
60 wc_Sha256Final(sha256, hash);
61 }
62
63 printf("password is: %s\n", c_password);
64 printf("password length is: %d\n", len);
65 for(len = 0; len < 32; len++){
66 printf("hash is %x\n",hash[len]);
67 }
68
69 store_password(hash);
70 free((void*) c_password);
71
72
73 return 0;
74 }
75
76 void
77 store_password(byte* hash)
78 {
79 byte b;
80 /* Save hash to a file on emscripten VFS */
81 FILE *fp;
82 int i;
83 byte buff[32] = {0};
84
85 printf("=====Storing Password in auth/password========\n");
86 /* for(i = 0; i < 32; i++){ */
87 /* printf("hash is %x\n",hash[i]); */
88 /* } */
89
90 fp = fopen("/auth/password", "w+");
91 if(!fp)
92 {
93 printf("cannot open file\n");
94 }
95 else
96 {
97 fwrite(hash, 1, 32, fp);
98 }
99
100 printf("========Stored Password=========\n");
101
102 fseek(fp, 0, SEEK_SET);
103
104 for(i = 0; i < 32; i++)
105 {
106 fread(buff, 1, 32, fp) ;
107 printf("buff is %x\n",buff[i]);
108 }
109
110 fclose(fp);
111 }