-2

我有array对象,每个对象都可能有这些

:[ "id", "start_long", "start_lat", "start_date", "type", "second_user_id", "end_long", "end_lat",
"end_date", "feedback"]

当我尝试解码 a 时based64String,我得到nil,我尝试使用CryptoSwiftRNCryptor

我想传递 64based 字符串 key ass method key

key : tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ=

在此处输入图像描述

4

2 回答 2

2

使用 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"}
于 2020-03-19T07:40:10.330 回答
0

我在我的项目中使用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)")

希望能帮助到你!

于 2020-03-19T04:17:28.620 回答