QN_GTM_Base64.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. //
  2. // GTMBase64.m
  3. //
  4. // Copyright 2006-2008 Google Inc.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. // use this file except in compliance with the License. You may obtain a copy
  8. // of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. // License for the specific language governing permissions and limitations under
  16. // the License.
  17. //
  18. #import "QN_GTM_Base64.h"
  19. static const char *kBase64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  20. static const char *kWebSafeBase64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  21. static const char kBase64PaddingChar = '=';
  22. static const char kBase64InvalidChar = 99;
  23. static const char kBase64DecodeChars[] = {
  24. // This array was generated by the following code:
  25. // #include <sys/time.h>
  26. // #include <stdlib.h>
  27. // #include <string.h>
  28. // main()
  29. // {
  30. // static const char Base64[] =
  31. // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  32. // char *pos;
  33. // int idx, i, j;
  34. // printf(" ");
  35. // for (i = 0; i < 255; i += 8) {
  36. // for (j = i; j < i + 8; j++) {
  37. // pos = strchr(Base64, j);
  38. // if ((pos == NULL) || (j == 0))
  39. // idx = 99;
  40. // else
  41. // idx = pos - Base64;
  42. // if (idx == 99)
  43. // printf(" %2d, ", idx);
  44. // else
  45. // printf(" %2d/*%c*/,", idx, j);
  46. // }
  47. // printf("\n ");
  48. // }
  49. // }
  50. 99, 99, 99, 99, 99, 99, 99, 99,
  51. 99, 99, 99, 99, 99, 99, 99, 99,
  52. 99, 99, 99, 99, 99, 99, 99, 99,
  53. 99, 99, 99, 99, 99, 99, 99, 99,
  54. 99, 99, 99, 99, 99, 99, 99, 99,
  55. 99, 99, 99, 62 /*+*/, 99, 99, 99, 63 /*/ */,
  56. 52 /*0*/, 53 /*1*/, 54 /*2*/, 55 /*3*/, 56 /*4*/, 57 /*5*/, 58 /*6*/, 59 /*7*/,
  57. 60 /*8*/, 61 /*9*/, 99, 99, 99, 99, 99, 99,
  58. 99, 0 /*A*/, 1 /*B*/, 2 /*C*/, 3 /*D*/, 4 /*E*/, 5 /*F*/, 6 /*G*/,
  59. 7 /*H*/, 8 /*I*/, 9 /*J*/, 10 /*K*/, 11 /*L*/, 12 /*M*/, 13 /*N*/, 14 /*O*/,
  60. 15 /*P*/, 16 /*Q*/, 17 /*R*/, 18 /*S*/, 19 /*T*/, 20 /*U*/, 21 /*V*/, 22 /*W*/,
  61. 23 /*X*/, 24 /*Y*/, 25 /*Z*/, 99, 99, 99, 99, 99,
  62. 99, 26 /*a*/, 27 /*b*/, 28 /*c*/, 29 /*d*/, 30 /*e*/, 31 /*f*/, 32 /*g*/,
  63. 33 /*h*/, 34 /*i*/, 35 /*j*/, 36 /*k*/, 37 /*l*/, 38 /*m*/, 39 /*n*/, 40 /*o*/,
  64. 41 /*p*/, 42 /*q*/, 43 /*r*/, 44 /*s*/, 45 /*t*/, 46 /*u*/, 47 /*v*/, 48 /*w*/,
  65. 49 /*x*/, 50 /*y*/, 51 /*z*/, 99, 99, 99, 99, 99,
  66. 99, 99, 99, 99, 99, 99, 99, 99,
  67. 99, 99, 99, 99, 99, 99, 99, 99,
  68. 99, 99, 99, 99, 99, 99, 99, 99,
  69. 99, 99, 99, 99, 99, 99, 99, 99,
  70. 99, 99, 99, 99, 99, 99, 99, 99,
  71. 99, 99, 99, 99, 99, 99, 99, 99,
  72. 99, 99, 99, 99, 99, 99, 99, 99,
  73. 99, 99, 99, 99, 99, 99, 99, 99,
  74. 99, 99, 99, 99, 99, 99, 99, 99,
  75. 99, 99, 99, 99, 99, 99, 99, 99,
  76. 99, 99, 99, 99, 99, 99, 99, 99,
  77. 99, 99, 99, 99, 99, 99, 99, 99,
  78. 99, 99, 99, 99, 99, 99, 99, 99,
  79. 99, 99, 99, 99, 99, 99, 99, 99,
  80. 99, 99, 99, 99, 99, 99, 99, 99,
  81. 99, 99, 99, 99, 99, 99, 99, 99};
  82. static const char kWebSafeBase64DecodeChars[] = {
  83. // This array was generated by the following code:
  84. // #include <sys/time.h>
  85. // #include <stdlib.h>
  86. // #include <string.h>
  87. // main()
  88. // {
  89. // static const char Base64[] =
  90. // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  91. // char *pos;
  92. // int idx, i, j;
  93. // printf(" ");
  94. // for (i = 0; i < 255; i += 8) {
  95. // for (j = i; j < i + 8; j++) {
  96. // pos = strchr(Base64, j);
  97. // if ((pos == NULL) || (j == 0))
  98. // idx = 99;
  99. // else
  100. // idx = pos - Base64;
  101. // if (idx == 99)
  102. // printf(" %2d, ", idx);
  103. // else
  104. // printf(" %2d/*%c*/,", idx, j);
  105. // }
  106. // printf("\n ");
  107. // }
  108. // }
  109. 99, 99, 99, 99, 99, 99, 99, 99,
  110. 99, 99, 99, 99, 99, 99, 99, 99,
  111. 99, 99, 99, 99, 99, 99, 99, 99,
  112. 99, 99, 99, 99, 99, 99, 99, 99,
  113. 99, 99, 99, 99, 99, 99, 99, 99,
  114. 99, 99, 99, 99, 99, 62 /*-*/, 99, 99,
  115. 52 /*0*/, 53 /*1*/, 54 /*2*/, 55 /*3*/, 56 /*4*/, 57 /*5*/, 58 /*6*/, 59 /*7*/,
  116. 60 /*8*/, 61 /*9*/, 99, 99, 99, 99, 99, 99,
  117. 99, 0 /*A*/, 1 /*B*/, 2 /*C*/, 3 /*D*/, 4 /*E*/, 5 /*F*/, 6 /*G*/,
  118. 7 /*H*/, 8 /*I*/, 9 /*J*/, 10 /*K*/, 11 /*L*/, 12 /*M*/, 13 /*N*/, 14 /*O*/,
  119. 15 /*P*/, 16 /*Q*/, 17 /*R*/, 18 /*S*/, 19 /*T*/, 20 /*U*/, 21 /*V*/, 22 /*W*/,
  120. 23 /*X*/, 24 /*Y*/, 25 /*Z*/, 99, 99, 99, 99, 63 /*_*/,
  121. 99, 26 /*a*/, 27 /*b*/, 28 /*c*/, 29 /*d*/, 30 /*e*/, 31 /*f*/, 32 /*g*/,
  122. 33 /*h*/, 34 /*i*/, 35 /*j*/, 36 /*k*/, 37 /*l*/, 38 /*m*/, 39 /*n*/, 40 /*o*/,
  123. 41 /*p*/, 42 /*q*/, 43 /*r*/, 44 /*s*/, 45 /*t*/, 46 /*u*/, 47 /*v*/, 48 /*w*/,
  124. 49 /*x*/, 50 /*y*/, 51 /*z*/, 99, 99, 99, 99, 99,
  125. 99, 99, 99, 99, 99, 99, 99, 99,
  126. 99, 99, 99, 99, 99, 99, 99, 99,
  127. 99, 99, 99, 99, 99, 99, 99, 99,
  128. 99, 99, 99, 99, 99, 99, 99, 99,
  129. 99, 99, 99, 99, 99, 99, 99, 99,
  130. 99, 99, 99, 99, 99, 99, 99, 99,
  131. 99, 99, 99, 99, 99, 99, 99, 99,
  132. 99, 99, 99, 99, 99, 99, 99, 99,
  133. 99, 99, 99, 99, 99, 99, 99, 99,
  134. 99, 99, 99, 99, 99, 99, 99, 99,
  135. 99, 99, 99, 99, 99, 99, 99, 99,
  136. 99, 99, 99, 99, 99, 99, 99, 99,
  137. 99, 99, 99, 99, 99, 99, 99, 99,
  138. 99, 99, 99, 99, 99, 99, 99, 99,
  139. 99, 99, 99, 99, 99, 99, 99, 99,
  140. 99, 99, 99, 99, 99, 99, 99, 99};
  141. // Tests a character to see if it's a whitespace character.
  142. //
  143. // Returns:
  144. // YES if the character is a whitespace character.
  145. // NO if the character is not a whitespace character.
  146. //
  147. BOOL QN_IsSpace(unsigned char c) {
  148. // we use our own mapping here because we don't want anything w/ locale
  149. // support.
  150. static BOOL kSpaces[256] = {
  151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // 0-9
  152. 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 10-19
  153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20-29
  154. 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, // 30-39
  155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40-49
  156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 50-59
  157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60-69
  158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 70-79
  159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80-89
  160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90-99
  161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100-109
  162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 110-119
  163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 120-129
  164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130-139
  165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140-149
  166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150-159
  167. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-169
  168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170-179
  169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180-189
  170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190-199
  171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200-209
  172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210-219
  173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220-229
  174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230-239
  175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240-249
  176. 0, 0, 0, 0, 0, 1, // 250-255
  177. };
  178. return kSpaces[c];
  179. }
  180. // Calculate how long the data will be once it's base64 encoded.
  181. //
  182. // Returns:
  183. // The guessed encoded length for a source length
  184. //
  185. NSUInteger QN_CalcEncodedLength(NSUInteger srcLen, BOOL padded) {
  186. NSUInteger intermediate_result = 8 * srcLen + 5;
  187. NSUInteger len = intermediate_result / 6;
  188. if (padded) {
  189. len = ((len + 3) / 4) * 4;
  190. }
  191. return len;
  192. }
  193. // Tries to calculate how long the data will be once it's base64 decoded.
  194. // Unlike the above, this is always an upperbound, since the source data
  195. // could have spaces and might end with the padding characters on them.
  196. //
  197. // Returns:
  198. // The guessed decoded length for a source length
  199. //
  200. NSUInteger QN_GuessDecodedLength(NSUInteger srcLen) {
  201. return (srcLen + 3) / 4 * 3;
  202. }
  203. @interface QN_GTM_Base64 (PrivateMethods)
  204. + (NSData *)baseEncode:(const void *)bytes
  205. length:(NSUInteger)length
  206. charset:(const char *)charset
  207. padded:(BOOL)padded;
  208. + (NSData *)baseDecode:(const void *)bytes
  209. length:(NSUInteger)length
  210. charset:(const char *)charset
  211. requirePadding:(BOOL)requirePadding;
  212. + (NSUInteger)baseEncode:(const char *)srcBytes
  213. srcLen:(NSUInteger)srcLen
  214. destBytes:(char *)destBytes
  215. destLen:(NSUInteger)destLen
  216. charset:(const char *)charset
  217. padded:(BOOL)padded;
  218. + (NSUInteger)baseDecode:(const char *)srcBytes
  219. srcLen:(NSUInteger)srcLen
  220. destBytes:(char *)destBytes
  221. destLen:(NSUInteger)destLen
  222. charset:(const char *)charset
  223. requirePadding:(BOOL)requirePadding;
  224. @end
  225. @implementation QN_GTM_Base64
  226. //
  227. // Standard Base64 (RFC) handling
  228. //
  229. + (NSData *)encodeData:(NSData *)data {
  230. return [self baseEncode:[data bytes]
  231. length:[data length]
  232. charset:kBase64EncodeChars
  233. padded:YES];
  234. }
  235. + (NSData *)decodeData:(NSData *)data {
  236. return [self baseDecode:[data bytes]
  237. length:[data length]
  238. charset:kBase64DecodeChars
  239. requirePadding:YES];
  240. }
  241. + (NSData *)encodeBytes:(const void *)bytes length:(NSUInteger)length {
  242. return [self baseEncode:bytes
  243. length:length
  244. charset:kBase64EncodeChars
  245. padded:YES];
  246. }
  247. + (NSData *)decodeBytes:(const void *)bytes length:(NSUInteger)length {
  248. return [self baseDecode:bytes
  249. length:length
  250. charset:kBase64DecodeChars
  251. requirePadding:YES];
  252. }
  253. + (NSString *)stringByEncodingData:(NSData *)data {
  254. NSString *result = nil;
  255. NSData *converted = [self baseEncode:[data bytes]
  256. length:[data length]
  257. charset:kBase64EncodeChars
  258. padded:YES];
  259. if (converted) {
  260. result = [[NSString alloc] initWithData:converted
  261. encoding:NSASCIIStringEncoding];
  262. }
  263. return result;
  264. }
  265. + (NSString *)stringByEncodingBytes:(const void *)bytes length:(NSUInteger)length {
  266. NSString *result = nil;
  267. NSData *converted = [self baseEncode:bytes
  268. length:length
  269. charset:kBase64EncodeChars
  270. padded:YES];
  271. if (converted) {
  272. result = [[NSString alloc] initWithData:converted
  273. encoding:NSASCIIStringEncoding];
  274. }
  275. return result;
  276. }
  277. + (NSData *)decodeString:(NSString *)string {
  278. NSData *result = nil;
  279. NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
  280. if (data) {
  281. result = [self baseDecode:[data bytes]
  282. length:[data length]
  283. charset:kBase64DecodeChars
  284. requirePadding:YES];
  285. }
  286. return result;
  287. }
  288. //
  289. // Modified Base64 encoding so the results can go onto urls.
  290. //
  291. // The changes are in the characters generated and also the result isn't
  292. // padded to a multiple of 4.
  293. // Must use the matching call to encode/decode, won't interop with the
  294. // RFC versions.
  295. //
  296. + (NSData *)webSafeEncodeData:(NSData *)data
  297. padded:(BOOL)padded {
  298. return [self baseEncode:[data bytes]
  299. length:[data length]
  300. charset:kWebSafeBase64EncodeChars
  301. padded:padded];
  302. }
  303. + (NSData *)webSafeDecodeData:(NSData *)data {
  304. return [self baseDecode:[data bytes]
  305. length:[data length]
  306. charset:kWebSafeBase64DecodeChars
  307. requirePadding:NO];
  308. }
  309. + (NSData *)webSafeEncodeBytes:(const void *)bytes
  310. length:(NSUInteger)length
  311. padded:(BOOL)padded {
  312. return [self baseEncode:bytes
  313. length:length
  314. charset:kWebSafeBase64EncodeChars
  315. padded:padded];
  316. }
  317. + (NSData *)webSafeDecodeBytes:(const void *)bytes length:(NSUInteger)length {
  318. return [self baseDecode:bytes
  319. length:length
  320. charset:kWebSafeBase64DecodeChars
  321. requirePadding:NO];
  322. }
  323. + (NSString *)stringByWebSafeEncodingData:(NSData *)data
  324. padded:(BOOL)padded {
  325. NSString *result = nil;
  326. NSData *converted = [self baseEncode:[data bytes]
  327. length:[data length]
  328. charset:kWebSafeBase64EncodeChars
  329. padded:padded];
  330. if (converted) {
  331. result = [[NSString alloc] initWithData:converted
  332. encoding:NSASCIIStringEncoding];
  333. }
  334. return result;
  335. }
  336. + (NSString *)stringByWebSafeEncodingBytes:(const void *)bytes
  337. length:(NSUInteger)length
  338. padded:(BOOL)padded {
  339. NSString *result = nil;
  340. NSData *converted = [self baseEncode:bytes
  341. length:length
  342. charset:kWebSafeBase64EncodeChars
  343. padded:padded];
  344. if (converted) {
  345. result = [[NSString alloc] initWithData:converted
  346. encoding:NSASCIIStringEncoding];
  347. }
  348. return result;
  349. }
  350. + (NSData *)webSafeDecodeString:(NSString *)string {
  351. NSData *result = nil;
  352. NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
  353. if (data) {
  354. result = [self baseDecode:[data bytes]
  355. length:[data length]
  356. charset:kWebSafeBase64DecodeChars
  357. requirePadding:NO];
  358. }
  359. return result;
  360. }
  361. @end
  362. @implementation QN_GTM_Base64 (PrivateMethods)
  363. //
  364. // baseEncode:length:charset:padded:
  365. //
  366. // Does the common lifting of creating the dest NSData. it creates & sizes the
  367. // data for the results. |charset| is the characters to use for the encoding
  368. // of the data. |padding| controls if the encoded data should be padded to a
  369. // multiple of 4.
  370. //
  371. // Returns:
  372. // an autorelease NSData with the encoded data, nil if any error.
  373. //
  374. + (NSData *)baseEncode:(const void *)bytes
  375. length:(NSUInteger)length
  376. charset:(const char *)charset
  377. padded:(BOOL)padded {
  378. // how big could it be?
  379. NSUInteger maxLength = QN_CalcEncodedLength(length, padded);
  380. // make space
  381. NSMutableData *result = [NSMutableData data];
  382. [result setLength:maxLength];
  383. // do it
  384. NSUInteger finalLength = [self baseEncode:bytes
  385. srcLen:length
  386. destBytes:[result mutableBytes]
  387. destLen:[result length]
  388. charset:charset
  389. padded:padded];
  390. if (finalLength) {
  391. // _GTMDevAssert(finalLength == maxLength, @"how did we calc the length wrong?");
  392. } else {
  393. // shouldn't happen, this means we ran out of space
  394. result = nil;
  395. }
  396. return result;
  397. }
  398. //
  399. // baseDecode:length:charset:requirePadding:
  400. //
  401. // Does the common lifting of creating the dest NSData. it creates & sizes the
  402. // data for the results. |charset| is the characters to use for the decoding
  403. // of the data.
  404. //
  405. // Returns:
  406. // an autorelease NSData with the decoded data, nil if any error.
  407. //
  408. //
  409. + (NSData *)baseDecode:(const void *)bytes
  410. length:(NSUInteger)length
  411. charset:(const char *)charset
  412. requirePadding:(BOOL)requirePadding {
  413. // could try to calculate what it will end up as
  414. NSUInteger maxLength = QN_GuessDecodedLength(length);
  415. // make space
  416. NSMutableData *result = [NSMutableData data];
  417. [result setLength:maxLength];
  418. // do it
  419. NSUInteger finalLength = [self baseDecode:bytes
  420. srcLen:length
  421. destBytes:[result mutableBytes]
  422. destLen:[result length]
  423. charset:charset
  424. requirePadding:requirePadding];
  425. if (finalLength) {
  426. if (finalLength != maxLength) {
  427. // resize down to how big it was
  428. [result setLength:finalLength];
  429. }
  430. } else {
  431. // either an error in the args, or we ran out of space
  432. result = nil;
  433. }
  434. return result;
  435. }
  436. //
  437. // baseEncode:srcLen:destBytes:destLen:charset:padded:
  438. //
  439. // Encodes the buffer into the larger. returns the length of the encoded
  440. // data, or zero for an error.
  441. // |charset| is the characters to use for the encoding
  442. // |padded| tells if the result should be padded to a multiple of 4.
  443. //
  444. // Returns:
  445. // the length of the encoded data. zero if any error.
  446. //
  447. + (NSUInteger)baseEncode:(const char *)srcBytes
  448. srcLen:(NSUInteger)srcLen
  449. destBytes:(char *)destBytes
  450. destLen:(NSUInteger)destLen
  451. charset:(const char *)charset
  452. padded:(BOOL)padded {
  453. if (!srcLen || !destLen || !srcBytes || !destBytes) {
  454. return 0;
  455. }
  456. char *curDest = destBytes;
  457. const unsigned char *curSrc = (const unsigned char *)(srcBytes);
  458. // Three bytes of data encodes to four characters of cyphertext.
  459. // So we can pump through three-byte chunks atomically.
  460. while (srcLen > 2) {
  461. // space?
  462. // _GTMDevAssert(destLen >= 4, @"our calc for encoded length was wrong");
  463. curDest[0] = charset[curSrc[0] >> 2];
  464. curDest[1] = charset[((curSrc[0] & 0x03) << 4) + (curSrc[1] >> 4)];
  465. curDest[2] = charset[((curSrc[1] & 0x0f) << 2) + (curSrc[2] >> 6)];
  466. curDest[3] = charset[curSrc[2] & 0x3f];
  467. curDest += 4;
  468. curSrc += 3;
  469. srcLen -= 3;
  470. destLen -= 4;
  471. }
  472. // now deal with the tail (<=2 bytes)
  473. switch (srcLen) {
  474. case 0:
  475. // Nothing left; nothing more to do.
  476. break;
  477. case 1:
  478. // One byte left: this encodes to two characters, and (optionally)
  479. // two pad characters to round out the four-character cypherblock.
  480. // _GTMDevAssert(destLen >= 2, @"our calc for encoded length was wrong");
  481. curDest[0] = charset[curSrc[0] >> 2];
  482. curDest[1] = charset[(curSrc[0] & 0x03) << 4];
  483. curDest += 2;
  484. destLen -= 2;
  485. if (padded) {
  486. // _GTMDevAssert(destLen >= 2, @"our calc for encoded length was wrong");
  487. curDest[0] = kBase64PaddingChar;
  488. curDest[1] = kBase64PaddingChar;
  489. curDest += 2;
  490. }
  491. break;
  492. case 2:
  493. // Two bytes left: this encodes to three characters, and (optionally)
  494. // one pad character to round out the four-character cypherblock.
  495. // _GTMDevAssert(destLen >= 3, @"our calc for encoded length was wrong");
  496. curDest[0] = charset[curSrc[0] >> 2];
  497. curDest[1] = charset[((curSrc[0] & 0x03) << 4) + (curSrc[1] >> 4)];
  498. curDest[2] = charset[(curSrc[1] & 0x0f) << 2];
  499. curDest += 3;
  500. destLen -= 3;
  501. if (padded) {
  502. // _GTMDevAssert(destLen >= 1, @"our calc for encoded length was wrong");
  503. curDest[0] = kBase64PaddingChar;
  504. curDest += 1;
  505. }
  506. break;
  507. }
  508. // return the length
  509. return (curDest - destBytes);
  510. }
  511. //
  512. // baseDecode:srcLen:destBytes:destLen:charset:requirePadding:
  513. //
  514. // Decodes the buffer into the larger. returns the length of the decoded
  515. // data, or zero for an error.
  516. // |charset| is the character decoding buffer to use
  517. //
  518. // Returns:
  519. // the length of the encoded data. zero if any error.
  520. //
  521. + (NSUInteger)baseDecode:(const char *)srcBytes
  522. srcLen:(NSUInteger)srcLen
  523. destBytes:(char *)destBytes
  524. destLen:(NSUInteger)destLen
  525. charset:(const char *)charset
  526. requirePadding:(BOOL)requirePadding {
  527. if (!srcLen || !destLen || !srcBytes || !destBytes) {
  528. return 0;
  529. }
  530. int decode;
  531. NSUInteger destIndex = 0;
  532. int state = 0;
  533. char ch = 0;
  534. while (srcLen-- && (ch = *srcBytes++) != 0) {
  535. if (QN_IsSpace(ch)) // Skip whitespace
  536. continue;
  537. if (ch == kBase64PaddingChar)
  538. break;
  539. decode = charset[(unsigned int)ch];
  540. if (decode == kBase64InvalidChar)
  541. return 0;
  542. // Four cyphertext characters decode to three bytes.
  543. // Therefore we can be in one of four states.
  544. switch (state) {
  545. case 0:
  546. // We're at the beginning of a four-character cyphertext block.
  547. // This sets the high six bits of the first byte of the
  548. // plaintext block.
  549. // _GTMDevAssert(destIndex < destLen, @"our calc for decoded length was wrong");
  550. destBytes[destIndex] = decode << 2;
  551. state = 1;
  552. break;
  553. case 1:
  554. // We're one character into a four-character cyphertext block.
  555. // This sets the low two bits of the first plaintext byte,
  556. // and the high four bits of the second plaintext byte.
  557. // _GTMDevAssert((destIndex+1) < destLen, @"our calc for decoded length was wrong");
  558. destBytes[destIndex] |= decode >> 4;
  559. destBytes[destIndex + 1] = (decode & 0x0f) << 4;
  560. destIndex++;
  561. state = 2;
  562. break;
  563. case 2:
  564. // We're two characters into a four-character cyphertext block.
  565. // This sets the low four bits of the second plaintext
  566. // byte, and the high two bits of the third plaintext byte.
  567. // However, if this is the end of data, and those two
  568. // bits are zero, it could be that those two bits are
  569. // leftovers from the encoding of data that had a length
  570. // of two mod three.
  571. // _GTMDevAssert((destIndex+1) < destLen, @"our calc for decoded length was wrong");
  572. destBytes[destIndex] |= decode >> 2;
  573. destBytes[destIndex + 1] = (decode & 0x03) << 6;
  574. destIndex++;
  575. state = 3;
  576. break;
  577. case 3:
  578. // We're at the last character of a four-character cyphertext block.
  579. // This sets the low six bits of the third plaintext byte.
  580. // _GTMDevAssert(destIndex < destLen, @"our calc for decoded length was wrong");
  581. destBytes[destIndex] |= decode;
  582. destIndex++;
  583. state = 0;
  584. break;
  585. }
  586. }
  587. // We are done decoding Base-64 chars. Let's see if we ended
  588. // on a byte boundary, and/or with erroneous trailing characters.
  589. if (ch == kBase64PaddingChar) { // We got a pad char
  590. if ((state == 0) || (state == 1)) {
  591. return 0; // Invalid '=' in first or second position
  592. }
  593. if (srcLen == 0) {
  594. if (state == 2) { // We run out of input but we still need another '='
  595. return 0;
  596. }
  597. // Otherwise, we are in state 3 and only need this '='
  598. } else {
  599. if (state == 2) { // need another '='
  600. while ((ch = *srcBytes++) && (srcLen-- > 0)) {
  601. if (!QN_IsSpace(ch))
  602. break;
  603. }
  604. if (ch != kBase64PaddingChar) {
  605. return 0;
  606. }
  607. }
  608. // state = 1 or 2, check if all remain padding is space
  609. while ((ch = *srcBytes++) && (srcLen-- > 0)) {
  610. if (!QN_IsSpace(ch)) {
  611. return 0;
  612. }
  613. }
  614. }
  615. } else {
  616. // We ended by seeing the end of the string.
  617. if (requirePadding) {
  618. // If we require padding, then anything but state 0 is an error.
  619. if (state != 0) {
  620. return 0;
  621. }
  622. } else {
  623. // Make sure we have no partial bytes lying around. Note that we do not
  624. // require trailing '=', so states 2 and 3 are okay too.
  625. if (state == 1) {
  626. return 0;
  627. }
  628. }
  629. }
  630. // If then next piece of output was valid and got written to it means we got a
  631. // very carefully crafted input that appeared valid but contains some trailing
  632. // bits past the real length, so just toss the thing.
  633. if ((destIndex < destLen) &&
  634. (destBytes[destIndex] != 0)) {
  635. return 0;
  636. }
  637. return destIndex;
  638. }
  639. @end