Base32.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //
  2. // Base32.swift
  3. // TOTP
  4. //
  5. // Created by 野村 憲男 on 1/24/15.
  6. //
  7. // Copyright (c) 2015 Norio Nomura
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. // https://tools.ietf.org/html/rfc4648
  28. // MARK: - Base32 NSData <-> String
  29. public func base32Encode(data: NSData) -> String {
  30. return base32encode(data.bytes, data.length, alphabetEncodeTable)
  31. }
  32. public func base32HexEncode(data: NSData) -> String {
  33. return base32encode(data.bytes, data.length, extendedHexAlphabetEncodeTable)
  34. }
  35. public func base32DecodeToData(string: String) -> NSData? {
  36. if let array = base32decode(string, alphabetDecodeTable) {
  37. return NSData(bytes: array, length: array.count)
  38. } else {
  39. return nil
  40. }
  41. }
  42. public func base32HexDecodeToData(string: String) -> NSData? {
  43. if let array = base32decode(string, extendedHexAlphabetDecodeTable) {
  44. return NSData(bytes: array, length: array.count)
  45. } else {
  46. return nil
  47. }
  48. }
  49. // MARK: - Base32 [UInt8] <-> String
  50. public func base32Encode(array: [UInt8]) -> String {
  51. return base32encode(array, array.count, alphabetEncodeTable)
  52. }
  53. public func base32HexEncode(array: [UInt8]) -> String {
  54. return base32encode(array, array.count, extendedHexAlphabetEncodeTable)
  55. }
  56. public func base32Decode(string: String) -> [UInt8]? {
  57. return base32decode(string, alphabetDecodeTable)
  58. }
  59. public func base32HexDecode(string: String) -> [UInt8]? {
  60. return base32decode(string, extendedHexAlphabetDecodeTable)
  61. }
  62. // MARK: extensions
  63. extension String {
  64. // base32
  65. public var base32DecodedData: NSData? {
  66. return base32DecodeToData(self)
  67. }
  68. public var base32EncodedString: String {
  69. return nulTerminatedUTF8.withUnsafeBufferPointer {
  70. return base32encode($0.baseAddress, $0.count - 1, alphabetEncodeTable)
  71. }
  72. }
  73. public func base32DecodedString(encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
  74. if let data = self.base32DecodedData {
  75. return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
  76. } else {
  77. return nil
  78. }
  79. }
  80. // base32Hex
  81. public var base32HexDecodedData: NSData? {
  82. return base32HexDecodeToData(self)
  83. }
  84. public var base32HexEncodedString: String {
  85. return nulTerminatedUTF8.withUnsafeBufferPointer {
  86. return base32encode($0.baseAddress, $0.count - 1, extendedHexAlphabetEncodeTable)
  87. }
  88. }
  89. public func base32HexDecodedString(encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
  90. if let data = self.base32HexDecodedData {
  91. return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
  92. } else {
  93. return nil
  94. }
  95. }
  96. }
  97. extension NSData {
  98. // base32
  99. public var base32EncodedString: String {
  100. return base32Encode(self)
  101. }
  102. public var base32EncodedData: NSData {
  103. return base32EncodedString.dataUsingUTF8StringEncoding
  104. }
  105. public var base32DecodedData: NSData? {
  106. if let string = NSString(data: self, encoding: NSUTF8StringEncoding) as? String {
  107. return base32DecodeToData(string)
  108. } else {
  109. return nil
  110. }
  111. }
  112. // base32Hex
  113. public var base32HexEncodedString: String {
  114. return base32HexEncode(self)
  115. }
  116. public var base32HexEncodedData: NSData {
  117. return base32HexEncodedString.dataUsingUTF8StringEncoding
  118. }
  119. public var base32HexDecodedData: NSData? {
  120. if let string = NSString(data: self, encoding: NSUTF8StringEncoding) as? String {
  121. return base32HexDecodeToData(string)
  122. } else {
  123. return nil
  124. }
  125. }
  126. }
  127. // MARK: - private
  128. // MARK: encode
  129. extension Int8: UnicodeScalarLiteralConvertible {
  130. public init(unicodeScalarLiteral value: UnicodeScalar) {
  131. self.init(value.value)
  132. }
  133. }
  134. 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"]
  135. 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"]
  136. private func base32encode(data: UnsafePointer<Void>, _ length: Int, _ table: [Int8]) -> String {
  137. if length == 0 {
  138. return ""
  139. }
  140. var length = length
  141. var bytes = UnsafePointer<UInt8>(data)
  142. let resultBufferSize = Int(ceil(Double(length) / 5)) * 8 + 1 // need null termination
  143. let resultBuffer = UnsafeMutablePointer<Int8>.alloc(resultBufferSize)
  144. var encoded = resultBuffer
  145. // encode regular blocks
  146. while length >= 5 {
  147. encoded[0] = table[Int(bytes[0] >> 3)]
  148. encoded[1] = table[Int((bytes[0] & 0b00000111) << 2 | bytes[1] >> 6)]
  149. encoded[2] = table[Int((bytes[1] & 0b00111110) >> 1)]
  150. encoded[3] = table[Int((bytes[1] & 0b00000001) << 4 | bytes[2] >> 4)]
  151. encoded[4] = table[Int((bytes[2] & 0b00001111) << 1 | bytes[3] >> 7)]
  152. encoded[5] = table[Int((bytes[3] & 0b01111100) >> 2)]
  153. encoded[6] = table[Int((bytes[3] & 0b00000011) << 3 | bytes[4] >> 5)]
  154. encoded[7] = table[Int((bytes[4] & 0b00011111))]
  155. length -= 5
  156. encoded = encoded.advancedBy(8)
  157. bytes = bytes.advancedBy(5)
  158. }
  159. // encode last block
  160. var byte0, byte1, byte2, byte3, byte4: UInt8
  161. (byte0, byte1, byte2, byte3, byte4) = (0,0,0,0,0)
  162. switch length {
  163. case 4:
  164. byte3 = bytes[3]
  165. encoded[6] = table[Int((byte3 & 0b00000011) << 3 | byte4 >> 5)]
  166. encoded[5] = table[Int((byte3 & 0b01111100) >> 2)]
  167. fallthrough
  168. case 3:
  169. byte2 = bytes[2]
  170. encoded[4] = table[Int((byte2 & 0b00001111) << 1 | byte3 >> 7)]
  171. fallthrough
  172. case 2:
  173. byte1 = bytes[1]
  174. encoded[3] = table[Int((byte1 & 0b00000001) << 4 | byte2 >> 4)]
  175. encoded[2] = table[Int((byte1 & 0b00111110) >> 1)]
  176. fallthrough
  177. case 1:
  178. byte0 = bytes[0]
  179. encoded[1] = table[Int((byte0 & 0b00000111) << 2 | byte1 >> 6)]
  180. encoded[0] = table[Int(byte0 >> 3)]
  181. default: break
  182. }
  183. // padding
  184. switch length {
  185. case 0:
  186. encoded[0] = 0
  187. case 1:
  188. encoded[2] = "="
  189. encoded[3] = "="
  190. fallthrough
  191. case 2:
  192. encoded[4] = "="
  193. fallthrough
  194. case 3:
  195. encoded[5] = "="
  196. encoded[6] = "="
  197. fallthrough
  198. case 4:
  199. encoded[7] = "="
  200. fallthrough
  201. default:
  202. encoded[8] = 0
  203. break
  204. }
  205. // return
  206. if let base32Encoded = String(UTF8String: resultBuffer) {
  207. resultBuffer.dealloc(resultBufferSize)
  208. return base32Encoded
  209. } else {
  210. resultBuffer.dealloc(resultBufferSize)
  211. fatalError("internal error")
  212. }
  213. }
  214. // MARK: decode
  215. let __: UInt8 = 255
  216. let alphabetDecodeTable: [UInt8] = [
  217. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  218. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  219. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  220. __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F
  221. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F
  222. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F
  223. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F
  224. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x70 - 0x7F
  225. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  226. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  227. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  228. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  229. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  230. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  231. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  232. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  233. ]
  234. let extendedHexAlphabetDecodeTable: [UInt8] = [
  235. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  236. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  237. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  238. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,__,__, __,__,__,__, // 0x30 - 0x3F
  239. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x40 - 0x4F
  240. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x50 - 0x5F
  241. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x60 - 0x6F
  242. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x70 - 0x7F
  243. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  244. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  245. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  246. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  247. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  248. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  249. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  250. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  251. ]
  252. private func base32decode(string: String, _ table: [UInt8]) -> [UInt8]? {
  253. let length = string.unicodeScalars.count
  254. if length == 0 {
  255. return []
  256. }
  257. // calc padding length
  258. func getLeastPaddingLength(string: String) -> Int {
  259. if string.hasSuffix("======") {
  260. return 6
  261. } else if string.hasSuffix("====") {
  262. return 4
  263. } else if string.hasSuffix("===") {
  264. return 3
  265. } else if string.hasSuffix("=") {
  266. return 1
  267. } else {
  268. return 0
  269. }
  270. }
  271. // validate string
  272. let leastPaddingLength = getLeastPaddingLength(string)
  273. if let index = string.unicodeScalars.indexOf({$0.value > 0xff || table[Int($0.value)] > 31}) {
  274. // index points padding "=" or invalid character that table does not contain.
  275. let pos = string.unicodeScalars.startIndex.distanceTo(index)
  276. // if pos points padding "=", it's valid.
  277. if pos != length - leastPaddingLength {
  278. print("string contains some invalid characters.")
  279. return nil
  280. }
  281. }
  282. var remainEncodedLength = length - leastPaddingLength
  283. var additionalBytes = 0
  284. switch remainEncodedLength % 8 {
  285. // valid
  286. case 0: break
  287. case 2: additionalBytes = 1
  288. case 4: additionalBytes = 2
  289. case 5: additionalBytes = 3
  290. case 7: additionalBytes = 4
  291. default:
  292. print("string length is invalid.")
  293. return nil
  294. }
  295. // validated
  296. let dataSize = remainEncodedLength / 8 * 5 + additionalBytes
  297. // Use UnsafePointer<UInt8>
  298. return string.nulTerminatedUTF8.withUnsafeBufferPointer {
  299. (data: UnsafeBufferPointer<UInt8>) -> [UInt8] in
  300. var encoded = data.baseAddress
  301. let result = Array<UInt8>(count: dataSize, repeatedValue: 0)
  302. var decoded = UnsafeMutablePointer<UInt8>(result)
  303. // decode regular blocks
  304. var value0, value1, value2, value3, value4, value5, value6, value7: UInt8
  305. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  306. while remainEncodedLength >= 8 {
  307. value0 = table[Int(encoded[0])]
  308. value1 = table[Int(encoded[1])]
  309. value2 = table[Int(encoded[2])]
  310. value3 = table[Int(encoded[3])]
  311. value4 = table[Int(encoded[4])]
  312. value5 = table[Int(encoded[5])]
  313. value6 = table[Int(encoded[6])]
  314. value7 = table[Int(encoded[7])]
  315. decoded[0] = value0 << 3 | value1 >> 2
  316. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  317. decoded[2] = value3 << 4 | value4 >> 1
  318. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  319. decoded[4] = value6 << 5 | value7
  320. remainEncodedLength -= 8
  321. decoded = decoded.advancedBy(5)
  322. encoded = encoded.advancedBy(8)
  323. }
  324. // decode last block
  325. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  326. switch remainEncodedLength {
  327. case 7:
  328. value6 = table[Int(encoded[6])]
  329. value5 = table[Int(encoded[5])]
  330. decoded[4] = value6 << 5 | value7
  331. fallthrough
  332. case 5:
  333. value4 = table[Int(encoded[4])]
  334. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  335. fallthrough
  336. case 4:
  337. value3 = table[Int(encoded[3])]
  338. value2 = table[Int(encoded[2])]
  339. decoded[2] = value3 << 4 | value4 >> 1
  340. fallthrough
  341. case 2:
  342. value1 = table[Int(encoded[1])]
  343. value0 = table[Int(encoded[0])]
  344. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  345. decoded[0] = value0 << 3 | value1 >> 2
  346. default: break
  347. }
  348. return result
  349. }
  350. }