Base32.swift 14 KB

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