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