NSData+Base64.m 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. //
  2. // NSData+Base64.m
  3. // base64
  4. //
  5. // Created by Matt Gallagher on 2009/06/03.
  6. // Copyright 2009 Matt Gallagher. All rights reserved.
  7. //
  8. // This software is provided 'as-is', without any express or implied
  9. // warranty. In no event will the authors be held liable for any damages
  10. // arising from the use of this software. Permission is granted to anyone to
  11. // use this software for any purpose, including commercial applications, and to
  12. // alter it and redistribute it freely, subject to the following restrictions:
  13. //
  14. // 1. The origin of this software must not be misrepresented; you must not
  15. // claim that you wrote the original software. If you use this software
  16. // in a product, an acknowledgment in the product documentation would be
  17. // appreciated but is not required.
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. // 3. This notice may not be removed or altered from any source
  21. // distribution.
  22. //
  23. #import "NSData+Base64.h"
  24. //
  25. // Mapping from 6 bit pattern to ASCII character.
  26. //
  27. static unsigned char base64EncodeLookup[65] =
  28. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  29. //
  30. // Definition for "masked-out" areas of the base64DecodeLookup mapping
  31. //
  32. #define xx 65
  33. //
  34. // Mapping from ASCII character to 6 bit pattern.
  35. //
  36. static unsigned char base64DecodeLookup[256] =
  37. {
  38. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  39. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  40. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, 62, xx, xx, xx, 63,
  41. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, xx, xx, xx, xx, xx, xx,
  42. xx, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  43. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, xx, xx, xx, xx, xx,
  44. xx, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  45. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, xx, xx, xx, xx, xx,
  46. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  47. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  48. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  49. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  50. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  51. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  52. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  53. xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
  54. };
  55. //
  56. // Fundamental sizes of the binary and base64 encode/decode units in bytes
  57. //
  58. #define BINARY_UNIT_SIZE 3
  59. #define BASE64_UNIT_SIZE 4
  60. //
  61. // NewBase64Decode
  62. //
  63. // Decodes the base64 ASCII string in the inputBuffer to a newly malloced
  64. // output buffer.
  65. //
  66. // inputBuffer - the source ASCII string for the decode
  67. // length - the length of the string or -1 (to specify strlen should be used)
  68. // outputLength - if not-NULL, on output will contain the decoded length
  69. //
  70. // returns the decoded buffer. Must be free'd by caller. Length is given by
  71. // outputLength.
  72. //
  73. void *NewBase64Decode(
  74. const char *inputBuffer,
  75. size_t length,
  76. size_t *outputLength)
  77. {
  78. if (length == -1)
  79. {
  80. length = strlen(inputBuffer);
  81. }
  82. size_t outputBufferSize =
  83. ((length+BASE64_UNIT_SIZE-1) / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE;
  84. unsigned char *outputBuffer = (unsigned char *)malloc(outputBufferSize);
  85. size_t i = 0;
  86. size_t j = 0;
  87. while (i < length)
  88. {
  89. //
  90. // Accumulate 4 valid characters (ignore everything else)
  91. //
  92. unsigned char accumulated[BASE64_UNIT_SIZE];
  93. size_t accumulateIndex = 0;
  94. while (i < length)
  95. {
  96. unsigned char decode = base64DecodeLookup[inputBuffer[i++]];
  97. if (decode != xx)
  98. {
  99. accumulated[accumulateIndex] = decode;
  100. accumulateIndex++;
  101. if (accumulateIndex == BASE64_UNIT_SIZE)
  102. {
  103. break;
  104. }
  105. }
  106. }
  107. //
  108. // Store the 6 bits from each of the 4 characters as 3 bytes
  109. //
  110. // (Uses improved bounds checking suggested by Alexandre Colucci)
  111. //
  112. if(accumulateIndex >= 2)
  113. outputBuffer[j] = (accumulated[0] << 2) | (accumulated[1] >> 4);
  114. if(accumulateIndex >= 3)
  115. outputBuffer[j + 1] = (accumulated[1] << 4) | (accumulated[2] >> 2);
  116. if(accumulateIndex >= 4)
  117. outputBuffer[j + 2] = (accumulated[2] << 6) | accumulated[3];
  118. j += accumulateIndex - 1;
  119. }
  120. if (outputLength)
  121. {
  122. *outputLength = j;
  123. }
  124. return outputBuffer;
  125. }
  126. //
  127. // NewBase64Encode
  128. //
  129. // Encodes the arbitrary data in the inputBuffer as base64 into a newly malloced
  130. // output buffer.
  131. //
  132. // inputBuffer - the source data for the encode
  133. // length - the length of the input in bytes
  134. // separateLines - if zero, no CR/LF characters will be added. Otherwise
  135. // a CR/LF pair will be added every 64 encoded chars.
  136. // outputLength - if not-NULL, on output will contain the encoded length
  137. // (not including terminating 0 char)
  138. //
  139. // returns the encoded buffer. Must be free'd by caller. Length is given by
  140. // outputLength.
  141. //
  142. char *NewBase64Encode(
  143. const void *buffer,
  144. size_t length,
  145. bool separateLines,
  146. size_t *outputLength)
  147. {
  148. const unsigned char *inputBuffer = (const unsigned char *)buffer;
  149. #define MAX_NUM_PADDING_CHARS 2
  150. #define OUTPUT_LINE_LENGTH 64
  151. #define INPUT_LINE_LENGTH ((OUTPUT_LINE_LENGTH / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE)
  152. #define CR_LF_SIZE 2
  153. //
  154. // Byte accurate calculation of final buffer size
  155. //
  156. size_t outputBufferSize =
  157. ((length / BINARY_UNIT_SIZE)
  158. + ((length % BINARY_UNIT_SIZE) ? 1 : 0))
  159. * BASE64_UNIT_SIZE;
  160. if (separateLines)
  161. {
  162. outputBufferSize +=
  163. (outputBufferSize / OUTPUT_LINE_LENGTH) * CR_LF_SIZE;
  164. }
  165. //
  166. // Include space for a terminating zero
  167. //
  168. outputBufferSize += 1;
  169. //
  170. // Allocate the output buffer
  171. //
  172. char *outputBuffer = (char *)malloc(outputBufferSize);
  173. if (!outputBuffer)
  174. {
  175. return NULL;
  176. }
  177. size_t i = 0;
  178. size_t j = 0;
  179. const size_t lineLength = separateLines ? INPUT_LINE_LENGTH : length;
  180. size_t lineEnd = lineLength;
  181. while (true)
  182. {
  183. if (lineEnd > length)
  184. {
  185. lineEnd = length;
  186. }
  187. for (; i + BINARY_UNIT_SIZE - 1 < lineEnd; i += BINARY_UNIT_SIZE)
  188. {
  189. //
  190. // Inner loop: turn 48 bytes into 64 base64 characters
  191. //
  192. outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
  193. outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4)
  194. | ((inputBuffer[i + 1] & 0xF0) >> 4)];
  195. outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i + 1] & 0x0F) << 2)
  196. | ((inputBuffer[i + 2] & 0xC0) >> 6)];
  197. outputBuffer[j++] = base64EncodeLookup[inputBuffer[i + 2] & 0x3F];
  198. }
  199. if (lineEnd == length)
  200. {
  201. break;
  202. }
  203. //
  204. // Add the newline
  205. //
  206. outputBuffer[j++] = '\r';
  207. outputBuffer[j++] = '\n';
  208. lineEnd += lineLength;
  209. }
  210. if (i + 1 < length)
  211. {
  212. //
  213. // Handle the single '=' case
  214. //
  215. outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
  216. outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4)
  217. | ((inputBuffer[i + 1] & 0xF0) >> 4)];
  218. outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i + 1] & 0x0F) << 2];
  219. outputBuffer[j++] = '=';
  220. }
  221. else if (i < length)
  222. {
  223. //
  224. // Handle the double '=' case
  225. //
  226. outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
  227. outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0x03) << 4];
  228. outputBuffer[j++] = '=';
  229. outputBuffer[j++] = '=';
  230. }
  231. outputBuffer[j] = 0;
  232. //
  233. // Set the output length and return the buffer
  234. //
  235. if (outputLength)
  236. {
  237. *outputLength = j;
  238. }
  239. return outputBuffer;
  240. }
  241. @implementation NSData (Base64)
  242. //
  243. // dataFromBase64String:
  244. //
  245. // Creates an NSData object containing the base64 decoded representation of
  246. // the base64 string 'aString'
  247. //
  248. // Parameters:
  249. // aString - the base64 string to decode
  250. //
  251. // returns the autoreleased NSData representation of the base64 string
  252. //
  253. + (NSData *)dataFromBase64String:(NSString *)aString
  254. {
  255. NSData *data = [aString dataUsingEncoding:NSASCIIStringEncoding];
  256. size_t outputLength;
  257. void *outputBuffer = NewBase64Decode([data bytes], [data length], &outputLength);
  258. NSData *result = [NSData dataWithBytes:outputBuffer length:outputLength];
  259. free(outputBuffer);
  260. return result;
  261. }
  262. //
  263. // base64EncodedString
  264. //
  265. // Creates an NSString object that contains the base 64 encoding of the
  266. // receiver's data. Lines are broken at 64 characters long.
  267. //
  268. // returns an autoreleased NSString being the base 64 representation of the
  269. // receiver.
  270. //
  271. - (NSString *)base64EncodedString
  272. {
  273. size_t outputLength;
  274. char *outputBuffer =
  275. NewBase64Encode([self bytes], [self length], true, &outputLength);
  276. NSString *result =
  277. [[NSString alloc]
  278. initWithBytes:outputBuffer
  279. length:outputLength
  280. encoding:NSASCIIStringEncoding];
  281. free(outputBuffer);
  282. return result;
  283. }
  284. // added by Hiroshi Hashiguchi
  285. - (NSString *)base64EncodedStringWithSeparateLines:(BOOL)separateLines
  286. {
  287. size_t outputLength;
  288. char *outputBuffer =
  289. NewBase64Encode([self bytes], [self length], separateLines, &outputLength);
  290. NSString *result =
  291. [[NSString alloc]
  292. initWithBytes:outputBuffer
  293. length:outputLength
  294. encoding:NSASCIIStringEncoding];
  295. free(outputBuffer);
  296. return result;
  297. }
  298. @end