NSData+Base64.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. //
  2. // NSData+Base64.h
  3. // Gurpartap Singh
  4. //
  5. // Created by Gurpartap Singh on 06/05/12.
  6. // Copyright (c) 2012 Gurpartap Singh. All rights reserved.
  7. //
  8. #import "NSData+Base64.h"
  9. @implementation NSData (Base64Additions)
  10. + (NSData *)base64DataFromString:(NSString *)string {
  11. unsigned long ixtext, lentext;
  12. unsigned char ch, inbuf[4], outbuf[3];
  13. short i, ixinbuf;
  14. Boolean flignore, flendtext = false;
  15. const unsigned char *tempcstring;
  16. NSMutableData *theData;
  17. if (string == nil) {
  18. return [NSData data];
  19. }
  20. ixtext = 0;
  21. tempcstring = (const unsigned char *)[string UTF8String];
  22. lentext = [string length];
  23. theData = [NSMutableData dataWithCapacity: lentext];
  24. ixinbuf = 0;
  25. while (true) {
  26. if (ixtext >= lentext) {
  27. break;
  28. }
  29. ch = tempcstring [ixtext++];
  30. flignore = false;
  31. if ((ch >= 'A') && (ch <= 'Z')) {
  32. ch = ch - 'A';
  33. }
  34. else if ((ch >= 'a') && (ch <= 'z')) {
  35. ch = ch - 'a' + 26;
  36. }
  37. else if ((ch >= '0') && (ch <= '9')) {
  38. ch = ch - '0' + 52;
  39. }
  40. else if (ch == '+') {
  41. ch = 62;
  42. }
  43. else if (ch == '=') {
  44. flendtext = true;
  45. }
  46. else if (ch == '/') {
  47. ch = 63;
  48. }
  49. else {
  50. flignore = true;
  51. }
  52. if (!flignore) {
  53. short ctcharsinbuf = 3;
  54. Boolean flbreak = false;
  55. if (flendtext) {
  56. if (ixinbuf == 0) {
  57. break;
  58. }
  59. if ((ixinbuf == 1) || (ixinbuf == 2)) {
  60. ctcharsinbuf = 1;
  61. }
  62. else {
  63. ctcharsinbuf = 2;
  64. }
  65. ixinbuf = 3;
  66. flbreak = true;
  67. }
  68. inbuf [ixinbuf++] = ch;
  69. if (ixinbuf == 4) {
  70. ixinbuf = 0;
  71. outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
  72. outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
  73. outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
  74. for (i = 0; i < ctcharsinbuf; i++) {
  75. [theData appendBytes: &outbuf[i] length: 1];
  76. }
  77. }
  78. if (flbreak) {
  79. break;
  80. }
  81. }
  82. }
  83. return theData;
  84. }
  85. @end