initial commit
[voxelands-alt.git] / src / crypto.c
blob3e9d5f0e8b7bdd784370b44da18106ab33ee1d40
1 /************************************************************************
2 * crypto.c
3 * voxelands - 3d voxel world sandbox game
4 * Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 * See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>
18 ************************************************************************/
20 #include "crypto.h"
22 #include <stdlib.h>
23 #include <string.h>
25 /* defined in base64.c */
26 int base64_lencode(char *source, size_t sourcelen, char *target, size_t targetlen);
27 size_t base64_ldecode(char *source, char *target, size_t targetlen);
29 /* an XOR hash sum */
30 uint32_t sum(char* str)
32 uint32_t hash = 0xAAAAAAAA;
33 uint32_t i;
35 for (i=0; *str; str++, i++) {
36 hash ^= ((i & 1) == 0) ? ((hash << 7) ^ (*str) * (hash >> 3)) : (~((hash << 11) + ((*str) ^ (hash >> 5))));
39 return hash;
42 /* basic string hash */
43 uint32_t hash(char* str)
45 uint32_t hash = 5381;
46 int c;
47 int i;
49 for (i=0; str[i]; i++) {
50 c = str[i];
51 hash = ((hash << 5)+hash)+c;
54 return hash;
57 /* base64 encode a string */
58 char* base64_encode(char* str)
60 int sl;
61 int tl;
62 char* ret;
63 int el;
64 if (!str)
65 return NULL;
67 sl = strlen(str);
68 tl = ((sl+2)/3*4)+5;
70 ret = malloc(tl);
71 if (!ret)
72 return NULL;
74 el = base64_lencode(str, sl, ret, tl);
75 if (!el) {
76 free(ret);
77 return NULL;
80 return ret;
83 /* decode a base64 string */
84 char* base64_decode(char* str)
86 int sl;
87 int tl;
88 char* ret;
89 int dl;
90 if (!str)
91 return NULL;
93 sl = strlen(str);
94 tl = (sl/4*3)+5;
95 ret = malloc(tl);
96 if (!ret)
97 return NULL;
99 dl = base64_ldecode(str, ret, tl);
100 if (!dl) {
101 free(ret);
102 return NULL;
104 ret[dl] = 0;
106 return ret;