快速的AES128加密 [英] AES128 encryption in swift

查看:446
本文介绍了快速的AES128加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到AES-128加密问题。 iOS中的加密字符串与Android不同。

I’ve an issue with AES-128 encryption. The encrypted string in iOS is different as compared to Android.

下面是android代码:

Below is android code :

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;
    }
}


推荐答案

创建字符串扩展名并使用库 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
    }
}

并使用

@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)

    }

此特定的android代码的引用:
1)16个字符长度的键表示AES-128
2)该代码没有iVector,这表示ECB模式
3)在我的案例中,将padding用作pkcs5或pkcs7并没有任何区别

For citation of this particular android code: 1) The 16 char length key implies AES-128 2) The code is without iVector, This implies ECB mode 3) Using padding as pkcs5 or pkcs7 did not made any difference in my case

这篇关于快速的AES128加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆