base64_encode.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #ifdef BASE64
  14. static const char *codes =
  15. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  16. int base64_encode(const unsigned char *in, unsigned long len,
  17. unsigned char *out, unsigned long *outlen)
  18. {
  19. unsigned long i, len2, leven;
  20. unsigned char *p;
  21. _ARGCHK(in != NULL);
  22. _ARGCHK(out != NULL);
  23. _ARGCHK(outlen != NULL);
  24. /* valid output size ? */
  25. len2 = 4 * ((len + 2) / 3);
  26. if (*outlen < len2 + 1) {
  27. return CRYPT_BUFFER_OVERFLOW;
  28. }
  29. p = out;
  30. leven = 3*(len / 3);
  31. for (i = 0; i < leven; i += 3) {
  32. *p++ = codes[(in[0] >> 2) & 0x3F];
  33. *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
  34. *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
  35. *p++ = codes[in[2] & 0x3F];
  36. in += 3;
  37. }
  38. /* Pad it if necessary... */
  39. if (i < len) {
  40. unsigned a = in[0];
  41. unsigned b = (i+1 < len) ? in[1] : 0;
  42. *p++ = codes[(a >> 2) & 0x3F];
  43. *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
  44. *p++ = (i+1 < len) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
  45. *p++ = '=';
  46. }
  47. /* append a NULL byte */
  48. *p = '\0';
  49. /* return ok */
  50. *outlen = p - out;
  51. return CRYPT_OK;
  52. }
  53. #endif