cdecode.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. cdecoder.c - c source to a base64 decoding algorithm implementation
  3. This is part of the libb64 project, and has been placed in the public domain.
  4. For details, see http://sourceforge.net/projects/libb64
  5. */
  6. #include "cdecode.h"
  7. int base64_decode_value(char value_in)
  8. {
  9. static const char decoding[] = {62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-2,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51};
  10. static const char decoding_size = sizeof(decoding);
  11. value_in -= 43;
  12. if (value_in < 0 || value_in > decoding_size) return -1;
  13. return decoding[(int)value_in];
  14. }
  15. void base64_init_decodestate(base64_decodestate* state_in)
  16. {
  17. state_in->step = step_a;
  18. state_in->plainchar = 0;
  19. }
  20. int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in)
  21. {
  22. const char* codechar = code_in;
  23. char* plainchar = plaintext_out;
  24. char fragment;
  25. *plainchar = state_in->plainchar;
  26. switch (state_in->step)
  27. {
  28. while (1)
  29. {
  30. case step_a:
  31. do {
  32. if (codechar == code_in+length_in)
  33. {
  34. state_in->step = step_a;
  35. state_in->plainchar = *plainchar;
  36. return plainchar - plaintext_out;
  37. }
  38. fragment = (char)base64_decode_value(*codechar++);
  39. } while (fragment < 0);
  40. *plainchar = (fragment & 0x03f) << 2;
  41. case step_b:
  42. do {
  43. if (codechar == code_in+length_in)
  44. {
  45. state_in->step = step_b;
  46. state_in->plainchar = *plainchar;
  47. return plainchar - plaintext_out;
  48. }
  49. fragment = (char)base64_decode_value(*codechar++);
  50. } while (fragment < 0);
  51. *plainchar++ |= (fragment & 0x030) >> 4;
  52. *plainchar = (fragment & 0x00f) << 4;
  53. case step_c:
  54. do {
  55. if (codechar == code_in+length_in)
  56. {
  57. state_in->step = step_c;
  58. state_in->plainchar = *plainchar;
  59. return plainchar - plaintext_out;
  60. }
  61. fragment = (char)base64_decode_value(*codechar++);
  62. } while (fragment < 0);
  63. *plainchar++ |= (fragment & 0x03c) >> 2;
  64. *plainchar = (fragment & 0x003) << 6;
  65. case step_d:
  66. do {
  67. if (codechar == code_in+length_in)
  68. {
  69. state_in->step = step_d;
  70. state_in->plainchar = *plainchar;
  71. return plainchar - plaintext_out;
  72. }
  73. fragment = (char)base64_decode_value(*codechar++);
  74. } while (fragment < 0);
  75. *plainchar++ |= (fragment & 0x03f);
  76. }
  77. }
  78. /* control should not reach here */
  79. return plainchar - plaintext_out;
  80. }