swift ASE 加密解密
时间: 2023-07-24 21:41:55 浏览: 214
Swift中提供了ASE加密解密的功能,可以使用CommonCrypto库来实现。下面是一个简单的示例代码:
```swift
import CommonCrypto
// 加密函数
func encryptAES(data: Data, key: Data, iv: Data) throws -> Data {
let cryptLength = size_t(data.count + kCCBlockSizeAES128)
var cryptData = Data(count: cryptLength)
var numBytesEncrypted: size_t = 0
let cryptStatus = cryptData.withUnsafeMutableBytes { cryptBytes in
data.withUnsafeBytes { dataBytes in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes, key.count,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
guard cryptStatus == kCCSuccess else {
throw NSError(domain: "Encryption Error", code: Int(cryptStatus), userInfo: nil)
}
cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
return cryptData
}
// 解密函数
func decryptAES(data: Data, key: Data, iv: Data) throws -> Data {
let cryptLength = size_t(data.count + kCCBlockSizeAES128)
var cryptData = Data(count: cryptLength)
var numBytesDecrypted: size_t = 0
let cryptStatus = cryptData.withUnsafeMutableBytes { cryptBytes in
data.withUnsafeBytes { dataBytes in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes, key.count,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesDecrypted)
}
}
}
}
guard cryptStatus == kCCSuccess else {
throw NSError(domain: "Decryption Error", code: Int(cryptStatus), userInfo: nil)
}
cryptData.removeSubrange(numBytesDecrypted..<cryptData.count)
return cryptData
}
// 使用示例
let plaintext = "Hello, World!"
let key = Data("01234567890123456789012345678901".utf8)
let iv = Data("abcdefghijklmnop".utf8)
let encryptedData = try encryptAES(data: Data(plaintext.utf8), key: key, iv: iv)
print("Encrypted: \(encryptedData.base64EncodedString())")
let decryptedData = try decryptAES(data: encryptedData, key: key, iv: iv)
let decryptedText = String(data: decryptedData, encoding: .utf8)
print("Decrypted: \(decryptedText ?? "")")
```
上述代码中的`key`和`iv`需要根据实际情况来设置,其中`key`必须是16、24或32字节长度的数据。
阅读全文