base64.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* base64.c: base64 encoding/decoding
  2. *
  3. */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include "base64.h"
  7. static const char base64[64] = ".\\0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  8. static const char base64r[256] = {
  9. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  10. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  12. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0,
  13. 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  14. 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 0, 1, 0, 0, 0,
  15. 0, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  16. 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0,
  17. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  18. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  19. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  21. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  24. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  25. };
  26. char *
  27. b64enc(const unsigned char *data, int len)
  28. {
  29. char *dest = NULL;
  30. dest = calloc(1, (len * 4) / 3 + 4 + 1);
  31. b64enc_buf(data, len, dest);
  32. return (dest);
  33. }
  34. void
  35. b64enc_buf(const unsigned char *data, int len, char *dest)
  36. {
  37. int i, t;
  38. #define DB(x) ((unsigned char) (x + i < len ? data[x + i] : 0))
  39. for (i = 0, t = 0; i < len; i += 3, t += 4) {
  40. dest[t] = base64[DB(0) >> 2];
  41. dest[t + 1] = base64[((DB(0) & 3) << 4) | (DB(1) >> 4)];
  42. dest[t + 2] = base64[((DB(1) & 0x0F) << 2) | (DB(2) >> 6)];
  43. dest[t + 3] = base64[(DB(2) & 0x3F)];
  44. }
  45. #undef DB
  46. dest[t] = 0;
  47. }
  48. char *
  49. b64dec(const unsigned char *data, int *len)
  50. {
  51. char *dest = NULL;
  52. dest = calloc(1, ((*len * 3) / 4) + 6 + 1);
  53. b64dec_buf(data, len, dest);
  54. return (dest);
  55. }
  56. void
  57. b64dec_buf(const unsigned char *data, int *len, char *dest)
  58. {
  59. int t, i;
  60. #define DB(x) ((unsigned char) (x + i < *len ? base64r[(unsigned char) data[x + i]] : 0))
  61. for (i = 0, t = 0; i < *len; i += 4, t += 3) {
  62. dest[t] = (DB(0) << 2) + (DB(1) >> 4);
  63. dest[t + 1] = ((DB(1) & 0x0F) << 4) + (DB(2) >> 2);
  64. dest[t + 2] = ((DB(2) & 3) << 6) + DB(3);
  65. };
  66. #undef DB
  67. t += 3;
  68. t -= (t % 4);
  69. //printf("t: %d len: %d strlen: %d : %s\n", t, *len, strlen(dest), dest);
  70. dest[t] = 0;
  71. *len = t;
  72. }