comparison src/misc/base64/base64_encode.c @ 192:9cc34777b479 libtomcrypt

propagate from branch 'au.asn.ucc.matt.ltc-orig' (head 9ba8f01f44320e9cb9f19881105ae84f84a43ea9) to branch 'au.asn.ucc.matt.dropbear.ltc' (head dbf51c569bc34956ad948e4cc87a0eeb2170b768)
author Matt Johnston <matt@ucc.asn.au>
date Sun, 08 May 2005 06:36:47 +0000
parents 1c15b283127b
children 39d5d58461d6
comparison
equal deleted inserted replaced
164:cd1143579f00 192:9cc34777b479
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 #include "tomcrypt.h"
12
13 /**
14 @file base64_encode.c
15 Compliant base64 encoder donated by Wayne Scott ([email protected])
16 */
17
18
19 #ifdef BASE64
20
21 static const char *codes =
22 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23
24 /**
25 base64 Encode a buffer (NUL terminated)
26 @param in The input buffer to encode
27 @param inlen The length of the input buffer
28 @param out [out] The destination of the base64 encoded data
29 @param outlen [in/out] The max size and resulting size
30 @return CRYPT_OK if successful
31 */
32 int base64_encode(const unsigned char *in, unsigned long inlen,
33 unsigned char *out, unsigned long *outlen)
34 {
35 unsigned long i, len2, leven;
36 unsigned char *p;
37
38 LTC_ARGCHK(in != NULL);
39 LTC_ARGCHK(out != NULL);
40 LTC_ARGCHK(outlen != NULL);
41
42 /* valid output size ? */
43 len2 = 4 * ((inlen + 2) / 3);
44 if (*outlen < len2 + 1) {
45 return CRYPT_BUFFER_OVERFLOW;
46 }
47 p = out;
48 leven = 3*(inlen / 3);
49 for (i = 0; i < leven; i += 3) {
50 *p++ = codes[(in[0] >> 2) & 0x3F];
51 *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
52 *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
53 *p++ = codes[in[2] & 0x3F];
54 in += 3;
55 }
56 /* Pad it if necessary... */
57 if (i < inlen) {
58 unsigned a = in[0];
59 unsigned b = (i+1 < inlen) ? in[1] : 0;
60
61 *p++ = codes[(a >> 2) & 0x3F];
62 *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
63 *p++ = (i+1 < inlen) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
64 *p++ = '=';
65 }
66
67 /* append a NULL byte */
68 *p = '\0';
69
70 /* return ok */
71 *outlen = p - out;
72 return CRYPT_OK;
73 }
74
75 #endif
76