base64_enc.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* base64_enc.c */
  2. /*
  3. * This file is part of the ARM-Crypto-Lib.
  4. * Copyright (C) 2006-2010 Daniel Otte (daniel.otte@rub.de)
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * base64 encoder (RFC3548)
  21. * Author: Daniel Otte
  22. * License: GPLv3
  23. *
  24. *
  25. */
  26. #include <stdint.h>
  27. #include <crypto/base64_enc.h>
  28. const char base64_alphabet[64] = {
  29. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  30. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  31. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  32. 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  33. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  34. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  35. 'w', 'x', 'y', 'z', '0', '1', '2', '3',
  36. '4', '5', '6', '7', '8', '9', '+', '/' };
  37. static
  38. char bit6toAscii(uint8_t a){
  39. a &= (uint8_t)0x3F;
  40. return base64_alphabet[a];
  41. }
  42. void base64enc(char* dest,const void* src, uint16_t length){
  43. uint16_t i,j;
  44. uint8_t a[4];
  45. for(i=0; i<length/3; ++i){
  46. a[0]= (((uint8_t*)src)[i*3+0])>>2;
  47. a[1]= (((((uint8_t*)src)[i*3+0])<<4) | ((((uint8_t*)src)[i*3+1])>>4)) & 0x3F;
  48. a[2]= (((((uint8_t*)src)[i*3+1])<<2) | ((((uint8_t*)src)[i*3+2])>>6)) & 0x3F;
  49. a[3]= (((uint8_t*)src)[i*3+2]) & 0x3F;
  50. for(j=0; j<4; ++j){
  51. *dest++=bit6toAscii(a[j]);
  52. }
  53. }
  54. /* now we do the rest */
  55. switch(length%3){
  56. case 0:
  57. break;
  58. case 1:
  59. a[0]=(((uint8_t*)src)[i*3+0])>>2;
  60. a[1]=((((uint8_t*)src)[i*3+0])<<4)&0x3F;
  61. *dest++ = bit6toAscii(a[0]);
  62. *dest++ = bit6toAscii(a[1]);
  63. *dest++ = '=';
  64. *dest++ = '=';
  65. break;
  66. case 2:
  67. a[0]= (((uint8_t*)src)[i*3+0])>>2;
  68. a[1]= (((((uint8_t*)src)[i*3+0])<<4) | ((((uint8_t*)src)[i*3+1])>>4)) & 0x3F;
  69. a[2]= ((((uint8_t*)src)[i*3+1])<<2) & 0x3F;
  70. *dest++ = bit6toAscii(a[0]);
  71. *dest++ = bit6toAscii(a[1]);
  72. *dest++ = bit6toAscii(a[2]);
  73. *dest++ = '=';
  74. break;
  75. default: /* this will not happen! */
  76. break;
  77. }
  78. /* finalize: */
  79. *dest='\0';
  80. }