Base32.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //
  2. // Base32.swift
  3. // TOTP
  4. //
  5. // Created by 野村 憲男 on 1/24/15.
  6. // Copyright (c) 2015 Norio Nomura. All rights reserved.
  7. //
  8. import Foundation
  9. // https://tools.ietf.org/html/rfc4648
  10. // MARK: - Base32 NSData <-> String
  11. public func base32Encode(data: NSData) -> String {
  12. return base32encode(data.bytes, data.length, alphabetEncodeTable)
  13. }
  14. public func base32HexEncode(data: NSData) -> String {
  15. return base32encode(data.bytes, data.length, extendedHexAlphabetEncodeTable)
  16. }
  17. public func base32DecodeToData(string: String) -> NSData? {
  18. if let array = base32decode(string, alphabetDecodeTable) {
  19. return NSData(bytes: array, length: array.count)
  20. } else {
  21. return nil
  22. }
  23. }
  24. public func base32HexDecodeToData(string: String) -> NSData? {
  25. if let array = base32decode(string, extendedHexAlphabetDecodeTable) {
  26. return NSData(bytes: array, length: array.count)
  27. } else {
  28. return nil
  29. }
  30. }
  31. // MARK: - Base32 [UInt8] <-> String
  32. public func base32Encode(array: [UInt8]) -> String {
  33. return base32encode(array, array.count, alphabetEncodeTable)
  34. }
  35. public func base32HexEncode(array: [UInt8]) -> String {
  36. return base32encode(array, array.count, extendedHexAlphabetEncodeTable)
  37. }
  38. public func base32Decode(string: String) -> [UInt8]? {
  39. return base32decode(string, alphabetDecodeTable)
  40. }
  41. public func base32HexDecode(string: String) -> [UInt8]? {
  42. return base32decode(string, extendedHexAlphabetDecodeTable)
  43. }
  44. // MARK: extensions
  45. extension String {
  46. // base32
  47. public var base32DecodedData: NSData? {
  48. return base32DecodeToData(self)
  49. }
  50. public var base32EncodedString: String {
  51. let length = lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
  52. return nulTerminatedUTF8.withUnsafeBufferPointer {
  53. (p: UnsafeBufferPointer<UInt8>) -> String in
  54. return base32encode(p.baseAddress, length, alphabetEncodeTable)
  55. }
  56. }
  57. public func base32DecodedString(encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
  58. if let data = self.base32DecodedData {
  59. return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
  60. } else {
  61. return nil
  62. }
  63. }
  64. // base32Hex
  65. public var base32HexDecodedData: NSData? {
  66. return base32HexDecodeToData(self)
  67. }
  68. public var base32HexEncodedString: String {
  69. let length = lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
  70. return nulTerminatedUTF8.withUnsafeBufferPointer {
  71. (p: UnsafeBufferPointer<UInt8>) -> String in
  72. return base32encode(p.baseAddress, length, extendedHexAlphabetEncodeTable)
  73. }
  74. }
  75. public func base32HexDecodedString(encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
  76. if let data = self.base32HexDecodedData {
  77. return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
  78. } else {
  79. return nil
  80. }
  81. }
  82. }
  83. extension NSData {
  84. // base32
  85. public var base32EncodedString: String {
  86. return base32Encode(self)
  87. }
  88. public var base32EncodedData: NSData? {
  89. return base32EncodedString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  90. }
  91. public var base32DecodedData: NSData? {
  92. if let string = NSString(data: self, encoding: NSUTF8StringEncoding) as? String {
  93. return base32DecodeToData(string)
  94. } else {
  95. return nil
  96. }
  97. }
  98. // base32Hex
  99. public var base32HexEncodedString: String {
  100. return base32HexEncode(self)
  101. }
  102. public var base32HexEncodedData: NSData? {
  103. return base32HexEncodedString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  104. }
  105. public var base32HexDecodedData: NSData? {
  106. if let string = NSString(data: self, encoding: NSUTF8StringEncoding) as? String {
  107. return base32HexDecodeToData(string)
  108. } else {
  109. return nil
  110. }
  111. }
  112. }
  113. // MARK: - private
  114. // MARK: encode
  115. extension Int8: UnicodeScalarLiteralConvertible {
  116. public init(unicodeScalarLiteral value: UnicodeScalar) {
  117. self.init(value.value)
  118. }
  119. }
  120. let alphabetEncodeTable: [Int8] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","2","3","4","5","6","7"]
  121. let extendedHexAlphabetEncodeTable: [Int8] = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V"]
  122. private func base32encode(data: UnsafePointer<Void>, var length: Int, table: [Int8]) -> String {
  123. if length == 0 {
  124. return ""
  125. }
  126. var bytes = UnsafePointer<UInt8>(data)
  127. let resultBufferSize = Int(ceil(Double(length) / 5)) * 8 + 1 // need null termination
  128. let resultBuffer = UnsafeMutablePointer<Int8>.alloc(resultBufferSize)
  129. var encoded = resultBuffer
  130. // encode regular blocks
  131. while length >= 5 {
  132. encoded[0] = table[Int(bytes[0] >> 3)]
  133. encoded[1] = table[Int((bytes[0] & 0b00000111) << 2 | bytes[1] >> 6)]
  134. encoded[2] = table[Int((bytes[1] & 0b00111110) >> 1)]
  135. encoded[3] = table[Int((bytes[1] & 0b00000001) << 4 | bytes[2] >> 4)]
  136. encoded[4] = table[Int((bytes[2] & 0b00001111) << 1 | bytes[3] >> 7)]
  137. encoded[5] = table[Int((bytes[3] & 0b01111100) >> 2)]
  138. encoded[6] = table[Int((bytes[3] & 0b00000011) << 3 | bytes[4] >> 5)]
  139. encoded[7] = table[Int((bytes[4] & 0b00011111))]
  140. length -= 5
  141. encoded = encoded.advancedBy(8)
  142. bytes = bytes.advancedBy(5)
  143. }
  144. // encode last block
  145. var byte0, byte1, byte2, byte3, byte4: UInt8
  146. (byte0, byte1, byte2, byte3, byte4) = (0,0,0,0,0)
  147. switch length {
  148. case 4:
  149. byte3 = bytes[3]
  150. encoded[6] = table[Int((byte3 & 0b00000011) << 3 | byte4 >> 5)]
  151. encoded[5] = table[Int((byte3 & 0b01111100) >> 2)]
  152. fallthrough
  153. case 3:
  154. byte2 = bytes[2]
  155. encoded[4] = table[Int((byte2 & 0b00001111) << 1 | byte3 >> 7)]
  156. fallthrough
  157. case 2:
  158. byte1 = bytes[1]
  159. encoded[3] = table[Int((byte1 & 0b00000001) << 4 | byte2 >> 4)]
  160. encoded[2] = table[Int((byte1 & 0b00111110) >> 1)]
  161. fallthrough
  162. case 1:
  163. byte0 = bytes[0]
  164. encoded[1] = table[Int((byte0 & 0b00000111) << 2 | byte1 >> 6)]
  165. encoded[0] = table[Int(byte0 >> 3)]
  166. default: break
  167. }
  168. // padding
  169. switch length {
  170. case 0:
  171. encoded[0] = 0
  172. case 1:
  173. encoded[2] = "="
  174. encoded[3] = "="
  175. fallthrough
  176. case 2:
  177. encoded[4] = "="
  178. fallthrough
  179. case 3:
  180. encoded[5] = "="
  181. encoded[6] = "="
  182. fallthrough
  183. case 4:
  184. encoded[7] = "="
  185. fallthrough
  186. default:
  187. encoded[8] = 0
  188. break
  189. }
  190. // return
  191. if let base32Encoded = String(UTF8String: resultBuffer) {
  192. resultBuffer.dealloc(resultBufferSize)
  193. return base32Encoded
  194. } else {
  195. resultBuffer.dealloc(resultBufferSize)
  196. fatalError("internal error")
  197. }
  198. }
  199. // MARK: decode
  200. let __: UInt8 = 255
  201. let alphabetDecodeTable: [UInt8] = [
  202. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  203. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  204. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  205. __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F
  206. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F
  207. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F
  208. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F
  209. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x70 - 0x7F
  210. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  211. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  212. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  213. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  214. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  215. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  216. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  217. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  218. ]
  219. let extendedHexAlphabetDecodeTable: [UInt8] = [
  220. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  221. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  222. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  223. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,__,__, __,__,__,__, // 0x30 - 0x3F
  224. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x40 - 0x4F
  225. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x50 - 0x5F
  226. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x60 - 0x6F
  227. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x70 - 0x7F
  228. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  229. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  230. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  231. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  232. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  233. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  234. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  235. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  236. ]
  237. private func base32decode(string: String, table: [UInt8]) -> [UInt8]? {
  238. let length = countElements(string.unicodeScalars)
  239. if length == 0 {
  240. return []
  241. }
  242. // search element index that condition is true.
  243. func index_of<C : CollectionType where C.Generator.Element : Equatable>(domain: C, condition: C.Generator.Element -> Bool) -> C.Index? {
  244. return find(lazy(domain).map(condition), true)
  245. }
  246. // calc padding length
  247. func getLeastPaddingLength(string: String) -> Int {
  248. if string.hasSuffix("======") {
  249. return 6
  250. } else if string.hasSuffix("====") {
  251. return 4
  252. } else if string.hasSuffix("===") {
  253. return 3
  254. } else if string.hasSuffix("=") {
  255. return 1
  256. } else {
  257. return 0
  258. }
  259. }
  260. // calc padded bytes
  261. func paddedBytes(paddingLength: Int) -> Int {
  262. switch paddingLength {
  263. case 6: return 4
  264. case 4: return 3
  265. case 3: return 2
  266. case 1: return 1
  267. default: /* case 0:*/ return 0
  268. }
  269. }
  270. // validate string
  271. let leastPaddingLength = getLeastPaddingLength(string)
  272. if length % 8 != 0 {
  273. println("string length is invalid.")
  274. return nil
  275. } else if let index = index_of(string.unicodeScalars, {$0.value > 0xff || table[Int($0.value)] > 31}) {
  276. // index points padding "=" or invalid character that table does not contain.
  277. let pos = distance(string.unicodeScalars.startIndex, index)
  278. // if pos points padding "=", it's valid.
  279. if pos != length - leastPaddingLength {
  280. println("string contains some invalid characters.")
  281. return nil
  282. }
  283. }
  284. // validated
  285. let dataSize = length / 8 * 5 - paddedBytes(leastPaddingLength)
  286. var remainEncodedLength = length - leastPaddingLength
  287. // Use UnsafePointer<UInt8>
  288. return string.nulTerminatedUTF8.withUnsafeBufferPointer {
  289. (data: UnsafeBufferPointer<UInt8>) -> [UInt8] in
  290. var encoded = data.baseAddress
  291. let result = Array<UInt8>(count: dataSize, repeatedValue: 0)
  292. var decoded = UnsafeMutablePointer<UInt8>(result)
  293. // decode regular blocks
  294. var value0, value1, value2, value3, value4, value5, value6, value7: UInt8
  295. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  296. while remainEncodedLength >= 8 {
  297. value0 = table[Int(encoded[0])]
  298. value1 = table[Int(encoded[1])]
  299. value2 = table[Int(encoded[2])]
  300. value3 = table[Int(encoded[3])]
  301. value4 = table[Int(encoded[4])]
  302. value5 = table[Int(encoded[5])]
  303. value6 = table[Int(encoded[6])]
  304. value7 = table[Int(encoded[7])]
  305. decoded[0] = value0 << 3 | value1 >> 2
  306. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  307. decoded[2] = value3 << 4 | value4 >> 1
  308. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  309. decoded[4] = value6 << 5 | value7
  310. remainEncodedLength -= 8
  311. decoded = decoded.advancedBy(5)
  312. encoded = encoded.advancedBy(8)
  313. }
  314. // decode last block
  315. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  316. switch remainEncodedLength {
  317. case 7:
  318. value6 = table[Int(encoded[6])]
  319. value5 = table[Int(encoded[5])]
  320. decoded[4] = value6 << 5 | value7
  321. fallthrough
  322. case 5:
  323. value4 = table[Int(encoded[4])]
  324. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  325. fallthrough
  326. case 4:
  327. value3 = table[Int(encoded[3])]
  328. value2 = table[Int(encoded[2])]
  329. decoded[2] = value3 << 4 | value4 >> 1
  330. fallthrough
  331. case 2:
  332. value1 = table[Int(encoded[1])]
  333. value0 = table[Int(encoded[0])]
  334. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  335. decoded[0] = value0 << 3 | value1 >> 2
  336. default: break
  337. }
  338. return result
  339. }
  340. }