]> git.proxmox.com Git - libpve-u2f-server-perl.git/blob - base64.h
bump version to 1.2.0
[libpve-u2f-server-perl.git] / base64.h
1 /*
2
3 Slightly altered base64 part, derived from William Sherif, original notice
4 below.
5 Altered by: Thomas Lamprecht <t.lamprecht@proxmox.com>
6
7 Original Notice:
8
9 https://github.com/superwills/NibbleAndAHalf
10 base64explained.h -- Fast base64 encoding and decoding.
11 version 1.0.0, April 17, 2013 143a
12
13 EXPLAINS how the functions in base64.h work. You don't need this file,
14 only base64.h is needed.
15 Copyright (C) 2013 William Sherif
16 This software is provided 'as-is', without any express or implied
17 warranty. In no event will the authors be held liable for any damages
18 arising from the use of this software.
19 Permission is granted to anyone to use this software for any purpose,
20 including commercial applications, and to alter it and redistribute it
21 freely, subject to the following restrictions:
22 1. The origin of this software must not be misrepresented; you must not
23 claim that you wrote the original software. If you use this software
24 in a product, an acknowledgment in the product documentation would be
25 appreciated but is not required.
26 2. Altered source versions must be plainly marked as such, and must not be
27 misrepresented as being the original software.
28 3. This notice may not be removed or altered from any source distribution.
29 William Sherif
30 will.sherif@gmail.com
31 YWxsIHlvdXIgYmFzZSBhcmUgYmVsb25nIHRvIHVz
32 */
33
34 const static char* b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
35 // Converts binary data of length=len to base64 characters.
36 char* base64( const void* binaryData, int len)
37 {
38 const unsigned char *bin = (const unsigned char*) binaryData;
39
40 int modulusLen = len % 3;
41 // 2 gives 1 and 1 gives 2, but 0 gives 0, padding
42 int pad = ((modulusLen & 1) << 1) + ((modulusLen & 2) >> 1);
43
44 int res_len = 4 * (len + pad) / 3;
45 char *res = (char *) malloc(res_len + 1); // and one for the null
46 if (!res) return 0; // really shouldn't happen on Linux
47
48 int byteNo; // needed for padding after the loop
49 int rc = 0; // result counter
50 for (byteNo = 0; byteNo <= len - 3; byteNo += 3) {
51 unsigned char BYTE0 = bin[byteNo + 0];
52 unsigned char BYTE1 = bin[byteNo + 1];
53 unsigned char BYTE2 = bin[byteNo + 2];
54 res[rc++] = b64[BYTE0 >> 2];
55 res[rc++] = b64[((0x3 & BYTE0)<<4) + (BYTE1 >> 4)];
56 res[rc++] = b64[((0x0f & BYTE1)<<2) + (BYTE2>>6)];
57 res[rc++] = b64[0x3f & BYTE2];
58 }
59
60 if (pad == 2) {
61 res[rc++] = b64[bin[byteNo] >> 2];
62 res[rc++] = b64[(0x3 & bin[byteNo]) << 4];
63 res[rc++] = '=';
64 res[rc++] = '=';
65 } else if (pad == 1) {
66 res[rc++] = b64[bin[byteNo] >> 2 ];
67 res[rc++] = b64[((0x3 & bin[byteNo]) << 4) + (bin[byteNo + 1] >> 4)];
68 res[rc++] = b64[(0x0f & bin[byteNo+1]) << 2];
69 res[rc++] = '=';
70 }
71
72 res[rc] = 0;
73 return res;
74 }