base64.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "base64.h"
  2. const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3. char *base64_encode( const unsigned char * bindata, char * base64, int binlength )
  4. {
  5. int i, j;
  6. unsigned char current;
  7. for ( i = 0, j = 0 ; i < binlength ; i += 3 )
  8. {
  9. current = (bindata[i] >> 2) ;
  10. current &= (unsigned char)0x3F;
  11. base64[j++] = base64char[(int)current];
  12. current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
  13. if ( i + 1 >= binlength )
  14. {
  15. base64[j++] = base64char[(int)current];
  16. base64[j++] = '=';
  17. base64[j++] = '=';
  18. break;
  19. }
  20. current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
  21. base64[j++] = base64char[(int)current];
  22. current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
  23. if ( i + 2 >= binlength )
  24. {
  25. base64[j++] = base64char[(int)current];
  26. base64[j++] = '=';
  27. break;
  28. }
  29. current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
  30. base64[j++] = base64char[(int)current];
  31. current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
  32. base64[j++] = base64char[(int)current];
  33. }
  34. base64[j] = '\0';
  35. return base64;
  36. }
  37. int base64_decode( const char * base64, unsigned char * bindata )
  38. {
  39. int i, j;
  40. unsigned char k;
  41. unsigned char temp[4];
  42. for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )
  43. {
  44. memset( temp, 0xFF, sizeof(temp) );
  45. for ( k = 0 ; k < 64 ; k ++ )
  46. {
  47. if ( base64char[k] == base64[i] )
  48. temp[0]= k;
  49. }
  50. for ( k = 0 ; k < 64 ; k ++ )
  51. {
  52. if ( base64char[k] == base64[i+1] )
  53. temp[1]= k;
  54. }
  55. for ( k = 0 ; k < 64 ; k ++ )
  56. {
  57. if ( base64char[k] == base64[i+2] )
  58. temp[2]= k;
  59. }
  60. for ( k = 0 ; k < 64 ; k ++ )
  61. {
  62. if ( base64char[k] == base64[i+3] )
  63. temp[3]= k;
  64. }
  65. bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |
  66. ((unsigned char)((unsigned char)(temp[1]>>4)&0x03));
  67. if ( base64[i+2] == '=' )
  68. break;
  69. bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) |
  70. ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));
  71. if ( base64[i+3] == '=' )
  72. break;
  73. bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |
  74. ((unsigned char)(temp[3]&0x3F));
  75. }
  76. return j;
  77. }