AES加密在Swift中怎么做?

huangapple go评论74阅读模式
英文:

AES Encryption in Swift?

问题

我正在Swift中进行AES加密。

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加密算法,但我得到了垃圾输出。请帮忙解决!

英文:

I am working AES Encryption in Swift.

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

I dont find Encryption with AES CBC PKCS5Padding for iOS 13 and below . iOS 13 has CryptoKit which is not what I require.

Swift Conversion that I tried:
//here operation is default value of kCCEncrypt that is 0

public func encrypt1(plainText : String, key: String, iv : String, operation : Int) -&gt; 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,&amp;numBytesEncrypted)
                    }
                }
            }
        }
    
        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.removeSubrange(numBytesEncrypted..&lt;cryptData.count)
            
        } else {
            print(&quot;Error: \(cryptStatus)&quot;)
        }
        print(&quot;My Encrypted Value: \(String(decoding: cryptData, as: UTF8.self))&quot;)
        return String(decoding: cryptData, as: UTF8.self);
    }

What I get from swift output is
�4 ��ɚ�-���.�'��kZU����Xm�E��X��S��^������I�WW�>a�bo)K����pS��=�>��he�-�}ͮQrqZha�d�i��
*U�����y���a�m0H������.)˶X�#t�6�C��w5@����Q����V�.w�!��� qyjH$S C�,�u��ܻ��L�ȧ�����_V�ym�R~RG���\o�S&amp;
kdx|�m�L��x�t� �d��&lt;�� _���,/��ͺ9�=��X.��а��ft�3�Ф�G�V�QH=?����:jc�
��Ԫ��������
[��
!�ϝ5}��V�PA
��<jt��,�����e��4E�!I�Pd�x���U�

I am not understanding what error am I doing I followed AES Encryption algorithm only still I get garbage output. Please help!!!

答案1

得分: 1

最终编写出解决方案:

import CommonCrypto
struct AES {

    // MARK: - 值
    // MARK: 私有
    private let key: Data
    private let iv: Data


    // MARK: - 初始化
    init?(key: String, iv: String) {
        guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
            debugPrint("错误:无法设置密钥。")
            return nil
        }

        guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
            debugPrint("错误:无法设置初始向量。")
            return nil
        }


        self.key = keyData
        self.iv  = ivData
    }


    // MARK: - 函数
    // MARK: 公开
    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("错误:无法加密/解密数据。状态 \(status)")
            return nil
        }

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

要将加密后的值作为字符串获取:

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

Finally coded up the solution :

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(&quot;Error: Failed to set a key.&quot;)
return nil
}
guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
debugPrint(&quot;Error: Failed to set an initial vector.&quot;)
return nil
}
self.key = keyData
self.iv  = ivData
}
// MARK: - Function
// MARK: Public
func encrypt(string: String) -&gt; String {
guard let cryptData =  crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt)) else { return &quot;&quot; }
return cryptData.base64EncodedString()
}
func decrypt(data: Data?) -&gt; 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) -&gt; 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, &amp;bytesLength)
}
}
}
}
guard UInt32(status) == UInt32(kCCSuccess) else {
debugPrint(&quot;Error: Failed to crypt data. Status \(status)&quot;)
return nil
}
cryptData.removeSubrange(bytesLength..&lt;cryptData.count)
return cryptData
}
}

To get the encrypted value as string:

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

答案2

得分: 0

我使用了 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 ""
}
英文:

I used CryptoSwift (https://cryptoswift.io).

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

huangapple
  • 本文由 发表于 2020年9月29日 21:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64120650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定