some meshgen and map rendering updates
[voxelands-alt.git] / src / lib / crypto.c
blob186881fb7c469dc7c4622d3d9da7c75181a54fb3
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 /* basic hashpjw used by lots of things, including mo files */
30 uint32_t hash(char* str)
32 uint32_t hval = 0;
33 uint32_t g;
34 const char *s = str;
36 while (*s) {
37 hval <<= 4;
38 hval += (unsigned char) *s++;
39 g = hval & ((uint32_t) 0xf << 28);
40 if (g != 0) {
41 hval ^= g >> 24;
42 hval ^= g;
46 return hval;
49 /* base64 encode a string */
50 char* base64_encode(char* str)
52 int sl;
53 int tl;
54 char* ret;
55 int el;
56 if (!str)
57 return NULL;
59 sl = strlen(str);
60 tl = ((sl+2)/3*4)+5;
62 ret = malloc(tl);
63 if (!ret)
64 return NULL;
66 el = base64_lencode(str, sl, ret, tl);
67 if (!el) {
68 free(ret);
69 return NULL;
72 return ret;
75 /* decode a base64 string */
76 char* base64_decode(char* str)
78 int sl;
79 int tl;
80 char* ret;
81 int dl;
82 if (!str)
83 return NULL;
85 sl = strlen(str);
86 tl = (sl/4*3)+5;
87 ret = malloc(tl);
88 if (!ret)
89 return NULL;
91 dl = base64_ldecode(str, ret, tl);
92 if (!dl) {
93 free(ret);
94 return NULL;
96 ret[dl] = 0;
98 return ret;