Base32.swift 13 KB

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