ios Swift?中的AES加密

xxb16uws  于 2022-11-19  发布在  iOS
关注(0)|答案(2)|浏览(249)

我在Swift中从事AES加密工作。

public static String encrypt1(String plaintext, String key, String IV) throws Exception {
   SecretKeySpec   secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(IV.getBytes("UTF-8")));
   byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF-8"));
   byte[] iv = cipher.getIV();
   String asd = Base64.encodeToString(ciphertext, Base64.NO_WRAP);
   return asd;
}

我没有找到iOS 13及以下版本的AES CBC PKCS 5 Padding加密。iOS 13有CryptoKit,这不是我所需要的。
我尝试过的快速转换://这里的操作是kCCEncrypt的默认值,即0

public func encrypt1(plainText : String, key: String, iv : String, operation : Int) -> String {
        let data = Data(plainText.utf8)
        let ivData = Data(iv.utf8)
        let keyData = Data(key.utf8)
        let cryptLength  = size_t(data.count + kCCBlockSizeAES128)
        var cryptData = Data(count:cryptLength)
    
        let keyLength = size_t(kCCKeySizeAES128)
        let options = CCOptions(kCCOptionPKCS7Padding)
        var numBytesEncrypted :size_t = 0
    
        let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
            data.withUnsafeBytes {dataBytes in
                ivData.withUnsafeBytes {ivBytes in
                    keyData.withUnsafeBytes {keyBytes in
                        CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES), options, keyBytes, keyLength, ivBytes, dataBytes, data.count,cryptBytes, cryptLength,&numBytesEncrypted)
                    }
                }
            }
        }
    
        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
            
        } else {
            print("Error: \(cryptStatus)")
        }
        print("My Encrypted Value: \(String(decoding: cryptData, as: UTF8.self))")
        return String(decoding: cryptData, as: UTF8.self);
    }

我从快速输出中得到的是:
我不明白我在做什么错误,我只遵循AES加密算法,仍然我得到垃圾输出。请帮助!!!

lp0sw83n

lp0sw83n1#

最后编写了解决方案:

import CommonCrypto
struct AES {

    // MARK: - Value
    // MARK: Private
    private let key: Data
    private let iv: Data

    // MARK: - Initialzier
    init?(key: String, iv: String) {
        guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
            debugPrint("Error: Failed to set a key.")
            return nil
        }

        guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
            debugPrint("Error: Failed to set an initial vector.")
            return nil
        }

        self.key = keyData
        self.iv  = ivData
    }

    // MARK: - Function
    // MARK: Public
    func encrypt(string: String) -> String {
        guard let cryptData =  crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt)) else { return "" }
        return cryptData.base64EncodedString()
    }

    func decrypt(data: Data?) -> String? {
        guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil }
        return String(bytes: decryptedData, encoding: .utf8)
    }

    func crypt(data: Data?, option: CCOperation) -> Data? {
        guard let data = data else { return nil }

        let cryptLength = data.count + kCCBlockSizeAES128
        var cryptData   = Data(count: cryptLength)

        let keyLength = key.count
        let options   = CCOptions(kCCOptionPKCS7Padding)

        var bytesLength = Int(0)

        let status = cryptData.withUnsafeMutableBytes { cryptBytes in
            data.withUnsafeBytes { dataBytes in
                iv.withUnsafeBytes { ivBytes in
                    key.withUnsafeBytes { keyBytes in
                    CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes.baseAddress, keyLength, ivBytes.baseAddress, dataBytes.baseAddress, data.count, cryptBytes.baseAddress, cryptLength, &bytesLength)
                    }
                }
            }
        }

        guard UInt32(status) == UInt32(kCCSuccess) else {
            debugPrint("Error: Failed to crypt data. Status \(status)")
            return nil
        }

        cryptData.removeSubrange(bytesLength..<cryptData.count)
        return cryptData
    }
}

要获取字符串形式的加密值,请执行以下操作:

let encryptedPassword128 = aes128?.encrypt(string: response1)
wswtfjt7

wswtfjt72#

我使用的是CryptoSwift(https://cryptoswift.io)。

func getEncryptedValue(value: String) -> String {
    let key = "someSecretKey"
    if let aes = try? AES(key: key.bytes, blockMode: ECB(), padding: .pkcs5),
        let aesE = try? aes.encrypt(Array(value.utf8)) {
        print("base64: \(Array(aesE).toBase64())")
        let result = Array(aesE).toBase64()
        return result
    }
    return ""
}

相关问题