如何在iOS Swift 3中加密AES 256 CBC,如laravel encrypt()方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在iOS Swift 3中加密AES 256 CBC,如laravel encrypt()方法相关的知识,希望对你有一定的参考价值。

我想在ios Swift 3中进行Laravel加密。

Crypt::encrypt('123456'); 

我试过这样的东西,但它不起作用。我认为这段代码有问题:

func generateRandomBytes() -> String? {

        var keyData = Data(count: 10)
        let result = keyData.withUnsafeMutableBytes {
            (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
            SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
        }
        if result == errSecSuccess {
            return keyData.base64EncodedString()
        } else {
            print("Problem generating random bytes")
            return nil
        }
    }

override func viewDidLoad() {
        super.viewDidLoad()
let ivString:String = generateRandomBytes()!
let ivDecodedData : Data = ivString.data(using: .utf8)!
        print("iv : ",ivString ,ivString.characters.count)
let purePasswordString:String = "123456"
        let serialString = String(format:"s:%lu:"%@";",purePasswordString.characters.count,purePasswordString)

let keyString        = "u6KuXJLIUwEUl7noY8J8H1ffDRwLC/5gjaWW1qTQ3hE="
        let encryptedStrKEYData = NSData(base64Encoded: keyString, options: .init(rawValue: 0))!
        let encryptedStrKEYDataString:String = NSString(data: encryptedStrKEYData as Data, encoding: String.Encoding.ascii.rawValue)! as String
let keyData: Data = Data(base64Encoded: keyString)!
let message       = serialString
        let data: NSData! = (message as NSString).data(using: String.Encoding.ascii.rawValue) as NSData!
let cryptData    = NSMutableData(length: Int(data.length) + kCCBlockSizeAES128)!

let keyLength              = size_t(kCCKeySizeAES256)
        let operation: CCOperation = UInt32(kCCEncrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0

let cryptStatus = CCCrypt(operation,
                                  algoritm,
                                  options,
                                  keyData.bytes,
                                  keyLength,
                                  ivDecodedData.bytes,
                                  data.bytes,
                                  data.length,
                                  cryptData.mutableBytes,
                                  cryptData.length,
                                  &numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            print("cryptLength = (numBytesEncrypted), cryptData = (cryptData)")
let base64cryptString = cryptData.base64EncodedString(options: [.lineLength64Characters])

let mix:String =  String(format:"%@%@",ivString,base64cryptString)
let cKey = encryptedStrKEYDataString.cString(using: String.Encoding.utf8)
            let cData = mix.cString(using: String.Encoding.utf8)
            let algorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
            let size = Int(CC_SHA256_DIGEST_LENGTH)
            var result = [CUnsignedChar](repeating: 0, count: size )
            CCHmac(algorithm, cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
            let hmacData:NSData = NSData(bytes: result, length: size)
            let hmacBase64 = hmacData.base64EncodedString(options: [])

let dict:Dictionary = ["iv":ivString,"value":base64cryptString,"mac":hmacBase64]
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .init(rawValue: 0))
let j:String = jsonData.base64EncodedString()

                print("done: ", j , j.characters.count)
} catch {
                print(error.localizedDescription)
            }
} else {
            print("Error: (cryptStatus)")
        }
}  

看到这个可以帮助你: https://github.com/reza-khalafi/LaravelCrypt/blob/master/laravelEncrypt.php

这是我的最后一次尝试:

import UIKit

class Enc2ViewController: UIViewController {


    func generateRandomBytes() -> String? {

        var keyData = Data(count: 10)
        let result = keyData.withUnsafeMutableBytes {
            (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
            SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
        }
        if result == errSecSuccess {
            return keyData.base64EncodedString()
        } else {
            print("Problem generating random bytes")
            return nil
        }
    }



    override func viewDidLoad() {
        super.viewDidLoad()

        let iv = generateRandomBytes()! // fixed 16 chars.
        print("iv String: (iv)")
        let cryptoKeyString = "u6KuXJLIUwEUl7noY8J8H1ffDRwLC/5gjaWW1qTQ3hE="
        let pureMessageString:String = "123456"
        let originalString = String(format:"s:%lu:"%@";",pureMessageString.characters.count,pureMessageString)
        print("Original String: (originalString)")

        let key:String = cryptoKeyString

        if let keyData = key.data(using: String.Encoding.utf8),
            let data = originalString.data(using: String.Encoding.utf8),
            let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {


            let keyLength              = size_t(kCCKeySizeAES256)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)



            var numBytesEncrypted :size_t = 0

            let base64cryptStringOut = keyData.withUnsafeBytes {(keyBytes: UnsafePointer<CChar>)->String? in
                return data.withUnsafeBytes {(dataBytes: UnsafePointer<CChar>)->String? in

                    let cryptStatus = CCCrypt(operation,
                                              algoritm,
                                              options,
                                              keyBytes, keyLength,
                                              iv,
                                              dataBytes, 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
                    }
                }
            }

            print("base64cryptStringOut: (String(describing: base64cryptStringOut)) ")

            let bIv:String = Data(iv.utf8).base64EncodedString()
            print("bIv",bIv,bIv.characters.count)

            let mixStr:String =  String(format:"%@%@",bIv,base64cryptStringOut!)
            print("mix: ",mixStr,mixStr.characters.count)






            var result: [CUnsignedChar]
            if let cKey = key.cString(using: String.Encoding.utf8),
                let cData = mixStr.cString(using: String.Encoding.utf8)
            {
                let algo  = CCHmacAlgorithm(kCCHmacAlgSHA256)
                result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))

                CCHmac(algo, cKey, cKey.count, cData, cData.count, &result)
            }
            else {

                fatalError("Nil returned when processing input strings as UTF8")
            }



            var hexString = ""
            for byte in result {
                hexString += String(format:"%2hhx", UInt8(byte))
            }





            print("hmac-string: (hexString) (hexString.characters.count)")


            let dict:Dictionary = ["iv":bIv,"value":base64cryptStringOut,"mac":hexString]
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .init(rawValue: 0))
                // here "jsonData" is the dictionary encoded in JSON data
                print(jsonData)


                let j:String = jsonData.base64EncodedString()

                print("done: ", j , j.characters.count)

            } catch {
                print(error.localizedDescription)
            }



        }




    }//didload

}
答案

解决了: 最后我们经过太多时间研究Laravel加密,决定自己创建。 LaraCrypt解决了这个问题。试试这个:

pod 'LaraCrypt'

Laravel Encryption with Swift language

请享用。

以上是关于如何在iOS Swift 3中加密AES 256 CBC,如laravel encrypt()方法的主要内容,如果未能解决你的问题,请参考以下文章

iOS 中的 AES256 NSString 加密

如何在 Android 中使用自己的密钥进行 AES-256 加密?

iOS AES256 解密

在目标 c 中,如何使用 md5 作为密钥进行 AES256 加密?

如何在 PHP 中进行 AES256 解密?

PHP 中的 AES-256 加密