import Foundation
import Security
// 生成RSA密钥对
func generateRSAKeyPair() throws -> SecKey {
let parameters: [String: Any] = [
kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits as String: 2048
]
var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
return privateKey
}
// 使用公钥RSA加密文件
func encryptFile(withPublicKey publicKey: SecKey, inputFile: URL, outputFile: URL) throws {
let inputData = try Data(contentsOf: inputFile)
let encryptedData = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionOAEPSHA512, inputData as CFData, nil)!
try encryptedData.write(to: outputFile)
}
// 使用私钥RSA解密文件
func decryptFile(withPrivateKey privateKey: SecKey, inputFile: URL, outputFile: URL) throws {
let encryptedData = try Data(contentsOf: inputFile)
let decryptedData = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionOAEPSHA512, encryptedData as CFData, nil)!
try decryptedData.write(to: outputFile)
}
// 生成RSA密钥对
let privateKey = try generateRSAKeyPair()
let publicKey = SecKeyCopyPublicKey(privateKey)!
// 指定输入和输出文件路径
let inputURL = URL(fileURLWithPath: "elements.data")
let encryptedOutputURL = URL(fileURLWithPath: "encrypted_elements.data")
let decryptedOutputURL = URL(fileURLWithPath: "decrypted_elements.data")
// 使用公钥RSA加密文件
do {
try encryptFile(withPublicKey: publicKey, inputFile: inputURL, outputFile: encryptedOutputURL)
print("文件已成功加密!")
} catch {
print("加密文件时发生错误:\(error.localizedDescription)")
}
// 使用私钥RSA解密文件
do {
try decryptFile(withPrivateKey: privateKey, inputFile: encryptedOutputURL, outputFile: decryptedOutputURL)
print("文件已成功解密!")
} catch {
print("解密文件时发生错误:\(error.localizedDescription)")
}