Last active
April 4, 2019 12:58
-
-
Save YannisDC/2143f4897c10237392e2e83311a5a88c to your computer and use it in GitHub Desktop.
Playground that shows propertyLevel encryption for Blockstack (Byte option not included yet)
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
import Cocoa | |
protocol Identifiable { | |
var uuid: String { get set } | |
} | |
protocol Encryptable { | |
var encrypted: Bool { get } | |
func encrypt() | |
func decrypt() | |
} | |
public class EncryptableProperty<T: LosslessStringConvertible>: Encryptable { | |
var value: T | |
var encryptedValue: String | |
var encrypted: Bool | |
init(value: T, encrypted: Bool) { | |
self.value = value | |
self.encrypted = encrypted | |
self.encryptedValue = "" | |
} | |
func encrypt() { | |
self.encryptedValue = value.description | |
} | |
func decrypt() { | |
guard let convertedValue = T(self.encryptedValue) else { | |
return | |
} | |
self.value = convertedValue | |
} | |
} | |
protocol EncryptableObject { | |
func encryptObject() | |
func decryptObject() | |
} | |
struct Test: EncryptableObject, Identifiable { | |
public let testString: EncryptableProperty<String> | |
public let testInt: EncryptableProperty<Int> | |
var uuid: String | |
init(uuid: String = UUID().uuidString) { | |
self.testString = EncryptableProperty<String>(value: "Blockstack", encrypted: true) | |
self.testInt = EncryptableProperty<Int>(value: 5, encrypted: true) | |
self.uuid = uuid | |
} | |
func encryptObject() { | |
print("\nEncryption happens") | |
Mirror(reflecting: self) | |
.children | |
.forEach { (property) in | |
if let encryptableValue = property.value as? Encryptable { | |
encryptableValue.encrypt() | |
} | |
} | |
} | |
func decryptObject() { | |
print("\nDecryption happens") | |
Mirror(reflecting: self) | |
.children | |
.forEach { (property) in | |
if let encryptableValue = property.value as? Encryptable { | |
encryptableValue.decrypt() | |
} | |
} | |
} | |
} | |
let test = Test() | |
print("Value= \(test.testInt.value) EncryptedValue= \(test.testInt.encryptedValue)") | |
test.encryptObject() | |
print("Value= \(test.testInt.value) EncryptedValue= \(test.testInt.encryptedValue)") | |
print("\nDecrypted value gets updated") | |
test.testInt.encryptedValue = "6" | |
print("Value= \(test.testInt.value) EncryptedValue= \(test.testInt.encryptedValue)") | |
test.decryptObject() | |
print("Value= \(test.testInt.value) EncryptedValue= \(test.testInt.encryptedValue)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment