Swift AES128加密解密
使用第三方框架:
pod 'CryptoSwift' #AES加密解密
需要的时候调用以下两个方法
// AES加密
classfuncaes_encrypt(_ str:String, aes_key:String) -> String{
var encryptedStr = ""
do {// AES encrypt
let encrypted = tryAES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).encrypt(str.bytes);
let data = Data(base64Encoded: Data(encrypted), options: .ignoreUnknownCharacters)
//加密结果从data转成string 转换失败 返回""
encryptedStr = String(bytes: data!.bytes, encoding: .utf8) ?? ""
} catch {
print(error.localizedDescription)
}
return encryptedStr
}
// AES解密
classfuncaes_decrypt(_ str:String , aes_key:String) -> String{
//decode base64
let data = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
var decrypted: [UInt8] = []
do {
// decode AES
decrypted = tryAES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).decrypt(data.bytes);
} catch {
print(error.localizedDescription)
}
//解密结果从data转成string 转换失败 返回""
returnString(bytes: Data(decrypted).bytes, encoding: .utf8) ?? ""
}
比如:
let decrptDataStr = self.aes_decrypt(dict["data"] as? String ?? "", aes_key: "解密密钥")
print("解密结果=" + decrptDataStr)
posted on 2022-06-27 15:00 yucaijiang 阅读(1255) 评论(0) 编辑 收藏 举报