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