feat: add ProtectedString with XOR obfuscation
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import Foundation
|
||||
|
||||
public struct ProtectedString: Equatable {
|
||||
private let obfuscated: [UInt8]
|
||||
private let key: [UInt8]
|
||||
public let isProtected: Bool
|
||||
|
||||
public init(_ value: String, isProtected: Bool = true) {
|
||||
self.isProtected = isProtected
|
||||
let bytes = Array(value.utf8)
|
||||
let k = (0 ..< bytes.count).map { _ in UInt8.random(in: 0 ... 255) }
|
||||
self.key = k
|
||||
self.obfuscated = zip(bytes, k).map { $0 ^ $1 }
|
||||
}
|
||||
|
||||
public func reveal() -> String {
|
||||
let bytes = zip(obfuscated, key).map { $0 ^ $1 }
|
||||
return String(bytes: bytes, encoding: .utf8) ?? ""
|
||||
}
|
||||
|
||||
public static func == (lhs: ProtectedString, rhs: ProtectedString) -> Bool {
|
||||
lhs.reveal() == rhs.reveal() && lhs.isProtected == rhs.isProtected
|
||||
}
|
||||
}
|
||||
|
||||
extension ProtectedString: CustomStringConvertible {
|
||||
public var description: String { isProtected ? "***" : reveal() }
|
||||
}
|
||||
|
||||
extension ProtectedString: CustomDebugStringConvertible {
|
||||
public var debugDescription: String { "ProtectedString(isProtected: \(isProtected))" }
|
||||
}
|
||||
Reference in New Issue
Block a user