Skip to content

Instantly share code, notes, and snippets.

@MarcoSignoretto
Created May 9, 2023 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcoSignoretto/738a9d6c617abb92f94a8aa346a56ee3 to your computer and use it in GitHub Desktop.
Save MarcoSignoretto/738a9d6c617abb92f94a8aa346a56ee3 to your computer and use it in GitHub Desktop.
import Security
import CryptoKit
import shared
final class TextCipherImpl: StringCipher {
func decrypt(securityKey secretKey: SecurityKey, encryptedData: BinaryData) -> String {
let key = secretKey.key()
guard let sealedBox = try? AES.GCM.SealedBox(combined: (encryptedData as! BinaryDataImpl).data),
let decryptedData = try? AES.GCM.open(sealedBox, using: key),
let decryptedString = String(data: decryptedData, encoding: .utf8) else { fatalError("Decryption failed") }
return decryptedString
}
func encrypt(securityKey secretKey: SecurityKey, plainData: String) -> BinaryData {
let key = secretKey.key()
guard let data = plainData.data(using: .utf8) else { fatalError("Encryption failed") }
let sealedBox = try! AES.GCM.seal(data, using: key)
return sealedBox.combined!.toBinaryData()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment