comparison base64_encode.c @ 15:6362d3854bb4 libtomcrypt-orig

0.96 release of LibTomCrypt
author Matt Johnston <matt@ucc.asn.au>
date Tue, 15 Jun 2004 14:07:21 +0000
parents
children
comparison
equal deleted inserted replaced
3:7faae8f46238 15:6362d3854bb4
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 *
9 * Tom St Denis, [email protected], http://libtomcrypt.org
10 */
11 /* compliant base64 code donated by Wayne Scott ([email protected]) */
12 #include "mycrypt.h"
13
14 #ifdef BASE64
15
16 static const char *codes =
17 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18
19 int base64_encode(const unsigned char *in, unsigned long len,
20 unsigned char *out, unsigned long *outlen)
21 {
22 unsigned long i, len2, leven;
23 unsigned char *p;
24
25 _ARGCHK(in != NULL);
26 _ARGCHK(out != NULL);
27 _ARGCHK(outlen != NULL);
28
29 /* valid output size ? */
30 len2 = 4 * ((len + 2) / 3);
31 if (*outlen < len2 + 1) {
32 return CRYPT_BUFFER_OVERFLOW;
33 }
34 p = out;
35 leven = 3*(len / 3);
36 for (i = 0; i < leven; i += 3) {
37 *p++ = codes[(in[0] >> 2) & 0x3F];
38 *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
39 *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
40 *p++ = codes[in[2] & 0x3F];
41 in += 3;
42 }
43 /* Pad it if necessary... */
44 if (i < len) {
45 unsigned a = in[0];
46 unsigned b = (i+1 < len) ? in[1] : 0;
47
48 *p++ = codes[(a >> 2) & 0x3F];
49 *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
50 *p++ = (i+1 < len) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
51 *p++ = '=';
52 }
53
54 /* append a NULL byte */
55 *p = '\0';
56
57 /* return ok */
58 *outlen = p - out;
59 return CRYPT_OK;
60 }
61
62 #endif
63