11.8 C
New York
Tuesday, November 5, 2024

ios – CoreData re-encrypt string property


I am utilizing Core Information in my iOS utility and I’ve one property that’s encrypted utilizing ValueTransformer:

class EncryptedStringTransformer: ValueTransformer {
non-public var encryptionKey: String

init(encryptionKey: String) {
    self.encryptionKey = encryptionKey
    tremendous.init()
}

override class func allowsReverseTransformation() -> Bool {
    return true
}

override class func transformedValueClass() -> AnyClass {
    return NSData.self
}

override func transformedValue(_ worth: Any?) -> Any? {
    guard let string = worth as? String,
          let information = string.information(utilizing: .utf8),
          let encryptedData = EncryptionUtils.aes256EncryptData(information, withKey: encryptionKey) else { return nil }
    return encryptedData
}

override func reverseTransformedValue(_ worth: Any?) -> Any? {
    guard let encryptedData = worth as? Information,
          let decryptedData = EncryptionUtils.aes256DecryptData(encryptedData, withKey: encryptionKey) else { return nil }
    return String(information: decryptedData, encoding: .utf8)
}

func updateEncryptionKey(newKey: String) {
    self.encryptionKey = newKey
}
}

The encrypted property is String:
@NSManaged public var message: String?

and it set within the CoreData mannequin as Transformable

the encryption is predicated on the person password that may be modified, if the person updates the password I wish to re-encrypt the property, I attempt to do it utilizing this operate:

func reEncryptDataWithNewPassword(oldPassword: String, newPassword: String) -> ReEncryptDBStatus {
let fetchRequest: NSFetchRequest = Message.fetchRequest()
guard let messages = strive? context.fetch(fetchRequest) else {
    return .failed
}

guard !messages.isEmpty else {
    return .success
}

for message in messages {
    if let _ = message.message {
        message.message = message.message
    }
}

ValueTransformer.setValueTransformer(EncryptedStringTransformer(encryptionKey: newPassword), forName: .encryptedStringTransformer)

do {
    strive context.save()
} catch {
    return .failed
}

return .success
}

The issue is that attempting context.save() doesn’t power the DB to replace the property, and transformedValue in EncryptedStringTransformer just isn’t referred to as once I name context.save().

Any concept what may be the issue?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles