Skip to content

Instantly share code, notes, and snippets.

@strzempa
Created October 11, 2019 05:28
Show Gist options
  • Save strzempa/8362d8f59c74cd74f9c7e138eee4ea9b to your computer and use it in GitHub Desktop.
Save strzempa/8362d8f59c74cd74f9c7e138eee4ea9b to your computer and use it in GitHub Desktop.
import Foundation
public final class Obfuscator {
/// The salt used to obfuscate and reveal the string.
static let salt: String = "\(String(describing: Obfuscator.self))\(String(describing: NSObject.self))"
/**
This method obfuscates the string passed in using the salt
that was used when the Obfuscator was initialized.
- parameter string: the string to obfuscate
- returns: the obfuscated string in a byte array
*/
public class func bytesByObfuscatingString(string: String) -> [UInt8] {
let text = [UInt8](string.utf8)
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var encrypted = [UInt8]()
for t in text.enumerated() {
encrypted.append(t.element ^ cipher[t.offset % length])
}
Logger.debug?.message("obfuscated: \(String(bytes: encrypted, encoding: .utf8) ?? "")")
return encrypted
}
/**
This method reveals the original string from the obfuscated
byte array passed in. The salt must be the same as the one
used to encrypt it in the first place.
- parameter key: the byte array to reveal
- returns: the original string
*/
public class func reveal(key: [UInt8]) -> String {
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var decrypted = [UInt8]()
for k in key.enumerated() {
decrypted.append(k.element ^ cipher[k.offset % length])
}
guard let string = String(bytes: decrypted, encoding: .utf8) else {
fatalError("Cannot reveal")
}
return string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment