Obfuscator.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Obfuscator.swift
  3. //
  4. // Created by Dejan Atanasov on 2017-05-31.
  5. //
  6. import Foundation
  7. class Obfuscator: NSObject{
  8. // MARK: - Variables
  9. /// The salt used to obfuscate and reveal the string.
  10. private var salt: String = ""
  11. // MARK: - Initialization
  12. init(withSalt salt: [AnyObject]) {
  13. self.salt = salt.description
  14. }
  15. // MARK: - Instance Methods
  16. /**
  17. This method obfuscates the string passed in using the salt
  18. that was used when the Obfuscator was initialized.
  19. - parameter string: the string to obfuscate
  20. - returns: the obfuscated string in a byte array
  21. */
  22. func bytesByObfuscatingString(string: String) -> [UInt8] {
  23. let text = [UInt8](string.utf8)
  24. let cipher = [UInt8](self.salt.utf8)
  25. let length = cipher.count
  26. var encrypted = [UInt8]()
  27. for t in text.enumerated() {
  28. encrypted.append(t.element ^ cipher[t.offset % length])
  29. }
  30. #if DEVELOPMENT
  31. print("Salt used: \(self.salt)\n")
  32. print("Swift Code:\n************")
  33. print("// Original \"\(string)\"")
  34. print("let key: [UInt8] = \(encrypted)\n")
  35. #endif
  36. return encrypted
  37. }
  38. /**
  39. This method reveals the original string from the obfuscated
  40. byte array passed in. The salt must be the same as the one
  41. used to encrypt it in the first place.
  42. - parameter key: the byte array to reveal
  43. - returns: the original string
  44. */
  45. func reveal(key: [UInt8]) -> String {
  46. let cipher = [UInt8](self.salt.utf8)
  47. let length = cipher.count
  48. var decrypted = [UInt8]()
  49. for k in key.enumerated() {
  50. decrypted.append(k.element ^ cipher[k.offset % length])
  51. }
  52. return String(bytes: decrypted, encoding: .utf8)!
  53. }
  54. }