-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObfuscator.swift
More file actions
81 lines (60 loc) · 2.07 KB
/
Obfuscator.swift
File metadata and controls
81 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// Obfuscator.swift
// SwiftObfuscatorExample
//
// Created by Mathieu White on 2016-07-03.
// Copyright © 2016 Mathieu White. All rights reserved.
//
import Foundation
class Obfuscator: AnyObject {
// MARK: - Variables
/// The salt used to obfuscate and reveal the string.
private var salt: String = ""
// MARK: - Initialization
init(withSalt 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]()
var count = 0
for t in text.enumerated() {
encrypted.append(t.element ^ cipher[count % length])
count += 1
}
#if DEVELOPMENT
print("Salt used: \(self.salt)\n")
print("Swift Code:\n************")
print("// Original \"\(string)\"")
print("let key: [UInt8] = \(encrypted)\n")
#endif
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]()
var count = 0
for k in key.enumerated() {
decrypted.append(k.element ^ cipher[count % length])
count += 1
}
return String(bytes: decrypted, encoding: String.Encoding.utf8)!
}
}