2
0

base64_decode.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 unsigned char map[256] = {
  15. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  16. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  17. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  18. 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
  19. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
  20. 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
  21. 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  22. 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
  23. 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  24. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  25. 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  26. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  27. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  28. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  29. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  30. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  31. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  32. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  33. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  34. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  35. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  36. 255, 255, 255, 255 };
  37. int base64_decode(const unsigned char *in, unsigned long len,
  38. unsigned char *out, unsigned long *outlen)
  39. {
  40. unsigned long t, x, y, z;
  41. unsigned char c;
  42. int g;
  43. _ARGCHK(in != NULL);
  44. _ARGCHK(out != NULL);
  45. _ARGCHK(outlen != NULL);
  46. g = 3;
  47. for (x = y = z = t = 0; x < len; x++) {
  48. c = map[in[x]&0xFF];
  49. if (c == 255) continue;
  50. if (c == 254) { c = 0; g--; }
  51. t = (t<<6)|c;
  52. if (++y == 4) {
  53. if (z + g > *outlen) {
  54. return CRYPT_BUFFER_OVERFLOW;
  55. }
  56. out[z++] = (unsigned char)((t>>16)&255);
  57. if (g > 1) out[z++] = (unsigned char)((t>>8)&255);
  58. if (g > 2) out[z++] = (unsigned char)(t&255);
  59. y = t = 0;
  60. }
  61. }
  62. if (y != 0) {
  63. return CRYPT_INVALID_PACKET;
  64. }
  65. *outlen = z;
  66. return CRYPT_OK;
  67. }
  68. #endif