我有array
个对象,每个对象可能都有这些
:[ "id", "start_long", "start_lat", "start_date", "type", "second_user_id", "end_long", "end_lat",
"end_date", "feedback"]
[当我尝试解码based64String
时,我得到nil
,我尝试使用CryptoSwift
,RNCryptor
我想通过基于64位的字符串作为密钥的屁股方法密钥
key : tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ=
使用base64密钥,salt和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+2WQAY7x/xL4Ov3sH9EGfVA=
Decrypt String : {"test":"aes Encrypt_Decrypt"}
我在项目中使用CryptoSwift进行AES加密解密,
i)首先我导入了CryptoSwift库
ii)创建的字符串扩展名
iii)添加的加密和解密方法
import CryptoSwift
extension String {
func aesEncrypt() -> String? {
do {
let encrypted = try AES(key: Array(AES_KEY.utf8), blockMode:CBC(iv: Array(AES_IV.utf8)), padding: .pkcs5).encrypt([UInt8](self.data(using: .utf8)!))
return Data(encrypted).base64EncodedString()
} catch {
return nil
}
}
func aesDecrypt() -> String? {
guard let data = Data(base64Encoded: self) else { return "" }
do {
let decrypted = try AES(key: Array(AES_KEY.utf8), blockMode:CBC(iv: Array(AES_IV.utf8)), padding: .pkcs5).decrypt([UInt8](data))
return String(bytes: decrypted, encoding: .utf8) ?? self
} catch {
return nil
}
}
}
iv)我创建了字典扩展,以将我的参数([String:Any])转换为JsonString
extension Dictionary {
func convertToJson() -> String{
var Json : String!
let dictionary = self
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: []) {
let theJSONText = String(data: theJSONData,encoding: .utf8)
Json = theJSONText
}
return Json
}
}
用法:
//MARK:- AES Encryption-Decryption Code
//Convert parameters to JSON String
let jsonString = parameters.convertToJson()
print("Json String : \(jsonString)")
//Encrypted Json String
let encriptionData = jsonString.aesEncrypt()
print("Encription String : \(encriptionData ?? "empty")")
//Decrypt your encrypted Data - This optional if you want to cross verify that your encryption data are correct
let decriptionData = encriptionData?.aesDecrypt()
print("DecriptionData String : \(decriptionData ?? "empty")")
//Pass the encrypted String inside one key to your API Request parameters. In my case it is "data" key
let param:[String:Any] = ["data":encriptionData ?? ""]
print("Encripted param String : \(param)")
希望有帮助!