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, tomstdenis@gmail.com, http://libtomcrypt.com
10 */
11#include "tomcrypt.h"
12
13/**
14  @file base64_encode.c
15  Compliant base64 encoder donated by Wayne Scott (wscott@bitmover.com)
16*/
17
18
19#ifdef BASE64
20
21static 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*/
32int 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      *outlen = len2 + 1;
46      return CRYPT_BUFFER_OVERFLOW;
47   }
48   p = out;
49   leven = 3*(inlen / 3);
50   for (i = 0; i < leven; i += 3) {
51       *p++ = codes[(in[0] >> 2) & 0x3F];
52       *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
53       *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
54       *p++ = codes[in[2] & 0x3F];
55       in += 3;
56   }
57   /* Pad it if necessary...  */
58   if (i < inlen) {
59       unsigned a = in[0];
60       unsigned b = (i+1 < inlen) ? in[1] : 0;
61
62       *p++ = codes[(a >> 2) & 0x3F];
63       *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
64       *p++ = (i+1 < inlen) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
65       *p++ = '=';
66   }
67
68   /* append a NULL byte */
69   *p = '\0';
70
71   /* return ok */
72   *outlen = p - out;
73   return CRYPT_OK;
74}
75
76#endif
77
78
79/* $Source: /cvs/libtom/libtomcrypt/src/misc/base64/base64_encode.c,v $ */
80/* $Revision: 1.5 $ */
81/* $Date: 2006/06/16 21:53:41 $ */
82