File: base64.c

package info (click to toggle)
radare2 0.9.6-3.1%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 17,496 kB
  • ctags: 45,959
  • sloc: ansic: 240,999; sh: 3,645; makefile: 2,520; python: 1,212; asm: 312; ruby: 214; awk: 209; perl: 188; lisp: 169; java: 23; xml: 17; php: 6
file content (56 lines) | stat: -rw-r--r-- 1,510 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Original code from:
 * dmc - dynamic mail client -- author: pancake
 * See LICENSE file for copyright and license details.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <r_util.h>

#define SZ 1024
static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";

static void b64_encode(const ut8 in[3], ut8 out[4], int len) {
	out[0] = cb64[ in[0] >> 2 ];
	out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
	out[2] = (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
	out[3] = (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
}

static int b64_decode(const ut8 in[4], ut8 out[3]) {
	ut8 len = 3, i, v[4] = {0};
	for (i=0; i<4; i++) {
		if (in[i]<43||in[i]>122)
			return -1;
		v[i] = cd64[in[i]-43];
		if (v[i]=='$') {
			len = i-1;
			break;
		} else v[i]-=62;
	}
	out[0] = v[0] << 2 | v[1] >> 4;
	out[1] = v[1] << 4 | v[2] >> 2;
	out[2] = ((v[2] << 6) & 0xc0) | v[3];
	return len;
}

R_API int r_base64_decode(ut8 *bout, const ut8 *bin, int len) {
	int in, out, ret;
	for (in=out=0; in<len-1;in+=4) {
		ret = b64_decode (bin+in, bout+out);
		if (ret <1)
			break;
		out += 3;
	}
	bout[out-1] = 0;
	return (in != out);
}

R_API void r_base64_encode(ut8 *bout, const ut8 *bin, int len) {
	int in, out;
	for (in=out=0; in<len; in+=3,out+=4)
		b64_encode (bin+in, bout+out, len-in>3?3:len-in);
}