ios SWIFT中的AES128加密

tsm1rwdh  于 2022-11-19  发布在  iOS
关注(0)|答案(3)|浏览(332)

我遇到了AES-128加密的问题。iOS中的加密字符串与Android中的不同。
下面是android代码:

public class Encryption {
    private static final String ALGORITHM = "AES";
    private static final String UNICODE_FORMAT = "UTF8";

    public static String encryptValue(String valueToEnc) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes());
            String encryptedValue = new Base64().encode(encValue);
            String urlEncodeddata = URLEncoder.encode(encryptedValue, "UTF-8");
            return urlEncodeddata;
        } catch (Exception e) {

        }
        return valueToEnc;
    }

    private static Key generateKey() throws Exception {
        byte[] keyAsBytes;
        keyAsBytes = "MySixteenCharKey".getBytes(UNICODE_FORMAT);
        Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
        return key;
    }
}
j5fpnvbx

j5fpnvbx1#

创建string extension并使用库CryptoSwift

//  String+Addition.swift
import CryptoSwift
extension String {
func aesEncrypt(key: String) throws -> String {
        
        var result = ""
        
        do {
            
            let key: [UInt8] = Array(key.utf8) as [UInt8]
            
            let aes = try! AES(key: key, blockMode: ECB() , padding:.pkcs5) // AES128 .ECB pkcs7
            
            let encrypted = try aes.encrypt(Array(self.utf8))
            
            result = encrypted.toBase64()!
            
            
            print("AES Encryption Result: \(result)")
            
        } catch {
            
            print("Error: \(error)")
        }
        
        return result
    }

func aesDecrypt(key: String) throws -> String {
    
    var result = ""
    
    do {
        
        let encrypted = self
        let key: [UInt8] = Array(key.utf8) as [UInt8]
        let aes = try! AES(key: key, blockMode: ECB(), padding: .pkcs5) // AES128 .ECB pkcs7
        let decrypted = try aes.decrypt(Array(base64: encrypted))
        
        result = String(data: Data(decrypted), encoding: .utf8) ?? ""
        
        print("AES Decryption Result: \(result)")
        
    } catch {
        
        print("Error: \(error)")
    }
    
    return result
}

}

并使用了

@IBAction func onBtnClicked(_ sender: Any) { 
        let value = "My value to be encrypted"
        let key = "MySixteenCharKey"
        
        print(key!)
        let encryptedValue = try! value.aesEncrypt(key: key!)

        print(encryptedValue)
        
    }

对于此特定加密代码的引用:
1.长度为16个字符的密钥表示AES-128
1.代码没有iVector,这意味着ECB模式
1.使用padding作为pkcs 5或pkcs 7在我的情况下没有任何区别

83qze16e

83qze16e2#

创建String扩展,并使用以下函数进行加密解密

extension String {

//MARK: - Encrypt AES Method
/// This method will encrypt and return Cipher string

func aesEncrypt(key: String = "fqJfdzGDvfwbedsKSUGty3VZ9taXxMVw", iv: String = "1234567890123456") -> String {
    if let data = self.data(using: String.Encoding.utf8) {
        do {
            let enc = try AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7()).encrypt(data.bytes)
            let encData = Data(bytes: enc, count: Int(enc.count))
            let base64String: String = encData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0));
            return base64String
        }
        catch let error {
            print(error.localizedDescription)
            return ""
        }
    }
    return ""
}

//MARK: - Decrypt AES Method
/// This method will decrypt the Cipher string

func aesDecrypt(key: String = "fqJfdzGDvfwbedsKSUGty3VZ9taXxMVw", iv: String = "1234567890123456") -> String {
    if let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions.init(rawValue: 0)) {
        do {
            let dec = try AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7()).decrypt(data.bytes)
            let decData = Data(bytes: dec, count: Int(dec.count))
            let result = String(data: decData, encoding: .utf8)
            return result ?? ""
        }
        catch let error {
            print(error.localizedDescription)
            return ""
        }
    }

    return ""
    }
}
qzlgjiam

qzlgjiam3#

试试看:

func encryptValue(stringToEncrypt:String) -> String{

    var encryptedString: String = ""

    let value = "MySixteenCharKey"
    let input: Array<UInt8> = Array(stringToEncrypt.utf8)
    let key: Array<UInt8> = Array("MySixteenCharKey".utf8)

    do {
        let encrypted = try AES(key: key, blockMode: .ECB, padding: PKCS7()).encrypt(input)
        let base64 = encrypted.toBase64()
        encryptedString = base64
    } catch {
        print(error)
    }

    return encryptedString
}

相关问题