Base32.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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>, var _ length: Int, _ table: [Int8]) -> String {
  137. if length == 0 {
  138. return ""
  139. }
  140. var bytes = UnsafePointer<UInt8>(data)
  141. let resultBufferSize = Int(ceil(Double(length) / 5)) * 8 + 1 // need null termination
  142. let resultBuffer = UnsafeMutablePointer<Int8>.alloc(resultBufferSize)
  143. var encoded = resultBuffer
  144. // encode regular blocks
  145. while length >= 5 {
  146. encoded[0] = table[Int(bytes[0] >> 3)]
  147. encoded[1] = table[Int((bytes[0] & 0b00000111) << 2 | bytes[1] >> 6)]
  148. encoded[2] = table[Int((bytes[1] & 0b00111110) >> 1)]
  149. encoded[3] = table[Int((bytes[1] & 0b00000001) << 4 | bytes[2] >> 4)]
  150. encoded[4] = table[Int((bytes[2] & 0b00001111) << 1 | bytes[3] >> 7)]
  151. encoded[5] = table[Int((bytes[3] & 0b01111100) >> 2)]
  152. encoded[6] = table[Int((bytes[3] & 0b00000011) << 3 | bytes[4] >> 5)]
  153. encoded[7] = table[Int((bytes[4] & 0b00011111))]
  154. length -= 5
  155. encoded = encoded.advancedBy(8)
  156. bytes = bytes.advancedBy(5)
  157. }
  158. // encode last block
  159. var byte0, byte1, byte2, byte3, byte4: UInt8
  160. (byte0, byte1, byte2, byte3, byte4) = (0,0,0,0,0)
  161. switch length {
  162. case 4:
  163. byte3 = bytes[3]
  164. encoded[6] = table[Int((byte3 & 0b00000011) << 3 | byte4 >> 5)]
  165. encoded[5] = table[Int((byte3 & 0b01111100) >> 2)]
  166. fallthrough
  167. case 3:
  168. byte2 = bytes[2]
  169. encoded[4] = table[Int((byte2 & 0b00001111) << 1 | byte3 >> 7)]
  170. fallthrough
  171. case 2:
  172. byte1 = bytes[1]
  173. encoded[3] = table[Int((byte1 & 0b00000001) << 4 | byte2 >> 4)]
  174. encoded[2] = table[Int((byte1 & 0b00111110) >> 1)]
  175. fallthrough
  176. case 1:
  177. byte0 = bytes[0]
  178. encoded[1] = table[Int((byte0 & 0b00000111) << 2 | byte1 >> 6)]
  179. encoded[0] = table[Int(byte0 >> 3)]
  180. default: break
  181. }
  182. // padding
  183. switch length {
  184. case 0:
  185. encoded[0] = 0
  186. case 1:
  187. encoded[2] = "="
  188. encoded[3] = "="
  189. fallthrough
  190. case 2:
  191. encoded[4] = "="
  192. fallthrough
  193. case 3:
  194. encoded[5] = "="
  195. encoded[6] = "="
  196. fallthrough
  197. case 4:
  198. encoded[7] = "="
  199. fallthrough
  200. default:
  201. encoded[8] = 0
  202. break
  203. }
  204. // return
  205. if let base32Encoded = String(UTF8String: resultBuffer) {
  206. resultBuffer.dealloc(resultBufferSize)
  207. return base32Encoded
  208. } else {
  209. resultBuffer.dealloc(resultBufferSize)
  210. fatalError("internal error")
  211. }
  212. }
  213. // MARK: decode
  214. let __: UInt8 = 255
  215. let alphabetDecodeTable: [UInt8] = [
  216. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  217. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  218. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  219. __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F
  220. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F
  221. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F
  222. __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F
  223. 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 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. let extendedHexAlphabetDecodeTable: [UInt8] = [
  234. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F
  235. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F
  236. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F
  237. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,__,__, __,__,__,__, // 0x30 - 0x3F
  238. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x40 - 0x4F
  239. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x50 - 0x5F
  240. __,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, // 0x60 - 0x6F
  241. 25,26,27,28, 29,30,31,__, __,__,__,__, __,__,__,__, // 0x70 - 0x7F
  242. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F
  243. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F
  244. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF
  245. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF
  246. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF
  247. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF
  248. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF
  249. __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF
  250. ]
  251. private func base32decode(string: String, _ table: [UInt8]) -> [UInt8]? {
  252. let length = string.unicodeScalars.count
  253. if length == 0 {
  254. return []
  255. }
  256. // calc padding length
  257. func getLeastPaddingLength(string: String) -> Int {
  258. if string.hasSuffix("======") {
  259. return 6
  260. } else if string.hasSuffix("====") {
  261. return 4
  262. } else if string.hasSuffix("===") {
  263. return 3
  264. } else if string.hasSuffix("=") {
  265. return 1
  266. } else {
  267. return 0
  268. }
  269. }
  270. // validate string
  271. let leastPaddingLength = getLeastPaddingLength(string)
  272. if let index = string.unicodeScalars.indexOf({$0.value > 0xff || table[Int($0.value)] > 31}) {
  273. // index points padding "=" or invalid character that table does not contain.
  274. let pos = string.unicodeScalars.startIndex.distanceTo(index)
  275. // if pos points padding "=", it's valid.
  276. if pos != length - leastPaddingLength {
  277. print("string contains some invalid characters.")
  278. return nil
  279. }
  280. }
  281. var remainEncodedLength = length - leastPaddingLength
  282. var additionalBytes = 0
  283. switch remainEncodedLength % 8 {
  284. // valid
  285. case 0: break
  286. case 2: additionalBytes = 1
  287. case 4: additionalBytes = 2
  288. case 5: additionalBytes = 3
  289. case 7: additionalBytes = 4
  290. default:
  291. print("string length is invalid.")
  292. return nil
  293. }
  294. // validated
  295. let dataSize = remainEncodedLength / 8 * 5 + additionalBytes
  296. // Use UnsafePointer<UInt8>
  297. return string.nulTerminatedUTF8.withUnsafeBufferPointer {
  298. (data: UnsafeBufferPointer<UInt8>) -> [UInt8] in
  299. var encoded = data.baseAddress
  300. let result = Array<UInt8>(count: dataSize, repeatedValue: 0)
  301. var decoded = UnsafeMutablePointer<UInt8>(result)
  302. // decode regular blocks
  303. var value0, value1, value2, value3, value4, value5, value6, value7: UInt8
  304. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  305. while remainEncodedLength >= 8 {
  306. value0 = table[Int(encoded[0])]
  307. value1 = table[Int(encoded[1])]
  308. value2 = table[Int(encoded[2])]
  309. value3 = table[Int(encoded[3])]
  310. value4 = table[Int(encoded[4])]
  311. value5 = table[Int(encoded[5])]
  312. value6 = table[Int(encoded[6])]
  313. value7 = table[Int(encoded[7])]
  314. decoded[0] = value0 << 3 | value1 >> 2
  315. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  316. decoded[2] = value3 << 4 | value4 >> 1
  317. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  318. decoded[4] = value6 << 5 | value7
  319. remainEncodedLength -= 8
  320. decoded = decoded.advancedBy(5)
  321. encoded = encoded.advancedBy(8)
  322. }
  323. // decode last block
  324. (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0)
  325. switch remainEncodedLength {
  326. case 7:
  327. value6 = table[Int(encoded[6])]
  328. value5 = table[Int(encoded[5])]
  329. decoded[4] = value6 << 5 | value7
  330. fallthrough
  331. case 5:
  332. value4 = table[Int(encoded[4])]
  333. decoded[3] = value4 << 7 | value5 << 2 | value6 >> 3
  334. fallthrough
  335. case 4:
  336. value3 = table[Int(encoded[3])]
  337. value2 = table[Int(encoded[2])]
  338. decoded[2] = value3 << 4 | value4 >> 1
  339. fallthrough
  340. case 2:
  341. value1 = table[Int(encoded[1])]
  342. value0 = table[Int(encoded[0])]
  343. decoded[1] = value1 << 6 | value2 << 1 | value3 >> 4
  344. decoded[0] = value0 << 3 | value1 >> 2
  345. default: break
  346. }
  347. return result
  348. }
  349. }