使用 base64 密钥、盐和 iv(初始化向量)的 AES 加密/解密。
1) 导入 CommonCrypto。这是 Apple 的开源密码库。
import CommonCrypto
2)用盐创建密钥。
extension Data {
func createKey(salt: Data) -> Data {
let length = kCCKeySizeAES256
var status = Int32(0)
var derivedBytes = [UInt8](repeating: 0, count: length)
self.withUnsafeBytes { (passwordBytes: UnsafePointer<Int8>!) in
salt.withUnsafeBytes { (saltBytes: UnsafePointer<UInt8>!) in
status = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), // algorithm
passwordBytes, // password
self.count, // password length
saltBytes, // salt
salt.count, // salt length
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1), // prf
10000, // rounds
&derivedBytes, // derived key
derivedBytes.count) // derived key length
}
}
if(status != kCCSuccess){
return Data.init(count: 0)
}
return Data(bytes: UnsafePointer<UInt8>(derivedBytes), count: length)
}
}
3) 加密/解密扩展
extension String {
func aesEncrypt(key:String, salt:String, iv:String) -> String? {
if let keyData = key.data(using: String.Encoding.utf8)?.createKey(salt: Data.init(base64Encoded: salt, options: .ignoreUnknownCharacters)!),
let data = self.data(using: String.Encoding.utf8),
let ivData = Data.init(base64Encoded: iv, options: .ignoreUnknownCharacters),
let cryptData = NSMutableData(length: Int((data.count)) + kCCKeySizeAES256) {
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
var cryptStatus: CCCryptorStatus = CCCryptorStatus(kCCSuccess)
ivData.withUnsafeBytes { (ivBytes: UnsafePointer<UInt8>!) -> () in
cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyData.count,
ivBytes,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
}
else {
return nil
}
}
return nil
}
func aesDecrypt(key:String, salt:String, iv:String) -> String? {
if let keyData = key.data(using: String.Encoding.utf8)?.createKey(salt: Data.init(base64Encoded: salt, options: .ignoreUnknownCharacters)!),
let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
let ivData = Data.init(base64Encoded: iv, options: .ignoreUnknownCharacters),
let cryptData = NSMutableData(length: Int((data.length)) + kCCKeySizeAES256) {
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
var cryptStatus: CCCryptorStatus = CCCryptorStatus(kCCSuccess)
ivData.withUnsafeBytes { (ivBytes: UnsafePointer<UInt8>!) -> () in
cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyData.count,
ivBytes,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}
4)字典到json字符串
extension Dictionary {
func toJsonString() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString ?? ""
} catch {
print(error.localizedDescription)
return ""
}
}
}
5) 样品
let param: [String: AnyObject] = [
"test": "aes Encrypt_Decrypt"
] as [String: AnyObject]
let jsonString = param.toJsonString()
print("Json String : " + jsonString)
let key = "tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ="
let salt = "QWlGNHNhMTJTQWZ2bGhpV3U=" // base64 decode => AiF4sa12SAfvlhiWu
let iv = "bVQzNFNhRkQ1Njc4UUFaWA==" // base64 decode => mT34SaFD5678QAZX
let encrypt = (jsonString.aesEncrypt(key: key, salt: salt, iv: iv))
print("Encrypt String : " + (encrypt ?? ""))
print("Decrypt String : " + (encrypt?.aesDecrypt(key: key, salt: salt, iv: iv) ?? ""))
6) 输出
Json String : {"test":"aes Encrypt_Decrypt"}
Encrypt String : PdT9Gxy6nz5/b4n7/wbj+6svYD06DokH7PbSWi+Pfmw=
Decrypt String : {"test":"aes Encrypt_Decrypt"}