Base32.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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($0.baseAddress!, $0.count, alphabetEncodeTable)
  32. }
  33. }
  34. public func base32HexEncode(_ data: Data) -> String {
  35. return data.withUnsafeBytes {
  36. base32encode($0.baseAddress!, $0.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. resultBuffer.deallocate()
  192. return base32Encoded
  193. } else {
  194. resultBuffer.deallocate()
  195. fatalError("internal error")
  196. }
  197. }
  198. // MARK: decode
  199. let __: UInt8 = 255
  200. let alphabetDecodeTable: [UInt8] = [
  201. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  202. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  203. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  204. __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F
  205. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F
  206. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F
  207. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F
  208. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x70 - 0x7F
  209. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  210. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  211. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  212. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  213. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  214. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  215. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  216. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  217. ]
  218. let extendedHexAlphabetDecodeTable: [UInt8] = [
  219. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  220. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  221. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  222. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,__,__, __,__,__,__, // 0x30 - 0x3F
  223. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x40 - 0x4F
  224. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x50 - 0x5F
  225. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x60 - 0x6F
  226. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x70 - 0x7F
  227. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  228. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  229. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  230. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  231. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  232. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  233. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  234. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  235. ]
  236. private func base32decode(_ string: String, _ table: [UInt8]) -> [UInt8]? {
  237. let length = string.unicodeScalars.count
  238. if length == 0 {
  239. return []
  240. }
  241. // calc padding length
  242. func getLeastPaddingLength(_ string: String) -> Int {
  243. if string.hasSuffix("======") {
  244. return 6
  245. } else if string.hasSuffix("====") {
  246. return 4
  247. } else if string.hasSuffix("===") {
  248. return 3
  249. } else if string.hasSuffix("=") {
  250. return 1
  251. } else {
  252. return 0
  253. }
  254. }
  255. // validate string
  256. let leastPaddingLength = getLeastPaddingLength(string)
  257. if let index = string.unicodeScalars.firstIndex(where: {$0.value > 0xff || table[Int($0.value)] > 31}) {
  258. // index points padding "=" or invalid character that table does not contain.
  259. let pos = string.unicodeScalars.distance(from: string.unicodeScalars.startIndex, to: index)
  260. // if pos points padding "=", it's valid.
  261. if pos != length - leastPaddingLength {
  262. print("string contains some invalid characters.")
  263. return nil
  264. }
  265. }
  266. var remainEncodedLength = length - leastPaddingLength
  267. var additionalBytes = 0
  268. switch remainEncodedLength % 8 {
  269. // valid
  270. case 0: break
  271. case 2: additionalBytes = 1
  272. case 4: additionalBytes = 2
  273. case 5: additionalBytes = 3
  274. case 7: additionalBytes = 4
  275. default:
  276. print("string length is invalid.")
  277. return nil
  278. }
  279. // validated
  280. let dataSize = remainEncodedLength / 8 * 5 + additionalBytes
  281. // Use UnsafePointer<UInt8>
  282. return string.utf8CString.withUnsafeBufferPointer {
  283. (data: UnsafeBufferPointer<CChar>) -> [UInt8] in
  284. var encoded = data.baseAddress!
  285. let result = Array<UInt8>(repeating: 0, count: dataSize)
  286. var decoded = UnsafeMutablePointer<UInt8>(mutating: result)
  287. // decode regular blocks
  288. var value0, value1, value2, value3, value4, value5, value6, value7: UInt8
  289. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  290. while remainEncodedLength >= 8 {
  291. value0 = table[Int(encoded[0])]
  292. value1 = table[Int(encoded[1])]
  293. value2 = table[Int(encoded[2])]
  294. value3 = table[Int(encoded[3])]
  295. value4 = table[Int(encoded[4])]
  296. value5 = table[Int(encoded[5])]
  297. value6 = table[Int(encoded[6])]
  298. value7 = table[Int(encoded[7])]
  299. decoded[0] = value0 << 3 | value1 >> 2
  300. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  301. decoded[2] = value3 << 4 | value4 >> 1
  302. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  303. decoded[4] = value6 << 5 | value7
  304. remainEncodedLength -= 8
  305. decoded = decoded.advanced(by: 5)
  306. encoded = encoded.advanced(by: 8)
  307. }
  308. // decode last block
  309. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  310. switch remainEncodedLength {
  311. case 7:
  312. value6 = table[Int(encoded[6])]
  313. value5 = table[Int(encoded[5])]
  314. fallthrough
  315. case 5:
  316. value4 = table[Int(encoded[4])]
  317. fallthrough
  318. case 4:
  319. value3 = table[Int(encoded[3])]
  320. value2 = table[Int(encoded[2])]
  321. fallthrough
  322. case 2:
  323. value1 = table[Int(encoded[1])]
  324. value0 = table[Int(encoded[0])]
  325. default: break
  326. }
  327. switch remainEncodedLength {
  328. case 7:
  329. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  330. fallthrough
  331. case 5:
  332. decoded[2] = value3 << 4 | value4 >> 1
  333. fallthrough
  334. case 4:
  335. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  336. fallthrough
  337. case 2:
  338. decoded[0] = value0 << 3 | value1 >> 2
  339. default: break
  340. }
  341. return result
  342. }
  343. }