Created
April 3, 2023 14:54
-
-
Save Gagan5278/d99fc0ab5264ff60ae6c2dd19e8da353 to your computer and use it in GitHub Desktop.
Swift Obfuscator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Obfuscator { | |
// MARK: - Variables | |
/// The salt used to obfuscate and reveal the string. | |
private var salt: String | |
// MARK: - Initialization | |
init() { | |
self.salt = "\(String(describing: SceneDelegate.self))\(String(describing: NSString.self))" | |
} | |
init(with salt: String) { | |
self.salt = salt | |
} | |
// MARK: - Instance Methods | |
/** | |
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 | |
*/ | |
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]) | |
} | |
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 | |
*/ | |
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]) | |
} | |
return String(bytes: decrypted, encoding: .utf8)! | |
} | |
} | |
// EXAMPLE: | |
final class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let obfuscator = Obfuscator() | |
print(obfuscator.bytesByObfuscatingString(string: "your_secret_string_here")) | |
print(obfuscator.reveal(key: ObfuscatedConstants.obfuscatedString)) | |
} | |
} | |
enum ObfuscatedConstants { | |
static let obfuscatedString: [UInt8] = [34, 17, 93, 37, 21, 28, 72, 23, 20, 22, 72, 127, 98, 123, 87, 94, 92, 83, 76, 113] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment