Skip to content

Instantly share code, notes, and snippets.

@NSEGeorge
Created April 20, 2020 14:05
Show Gist options
  • Save NSEGeorge/daebe914c001065223a98b1731c3faee to your computer and use it in GitHub Desktop.
Save NSEGeorge/daebe914c001065223a98b1731c3faee to your computer and use it in GitHub Desktop.
import Foundation
import RNCryptor
import CryptoKit
public enum MLCryptor {
case cryptoKit
case rnCryptor
public func encrypt(data: Data, withPassword password: String) throws -> Data? {
switch self {
case .cryptoKit:
let encryptionKey = try SymmetricKey(string: password)
return try encryptByCryptoKit(data, withKey: encryptionKey)
case .rnCryptor:
return RNCryptor.encrypt(data: data, withPassword: password)
}
}
public func decrypt(data: Data, withPassword password: String) throws -> Data? {
switch self {
case .cryptoKit:
let decryptionKey = try SymmetricKey(string: password)
return try decryptByCryptoKit(data, withKey: decryptionKey)
case .rnCryptor:
return try RNCryptor.decrypt(data: data, withPassword: password)
}
}
}
private extension CXMLCryptor {
func encryptByCryptoKit(_ data: Data, withKey key: SymmetricKey) throws -> Data? {
let sealedBox = try AES.GCM.seal(data, using: key)
let encryptedData = sealedBox.combined
return encryptedData
}
func decryptByCryptoKit(_ data: Data, withKey key: SymmetricKey) throws -> Data? {
let sealedBox = try AES.GCM.SealedBox(combined: data)
let decryptedData = try AES.GCM.open(sealedBox, using: key)
return decryptedData
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment