AES128加密在swift中

时间:2017-04-10 11:45:43

标签: ios swift encryption aes

我遇到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;
    }
}

4 个答案:

答案 0 :(得分:2)

创建android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } ... } 并使用库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
    }
}

对于此特定android代码的引用: 1)16个字符长度的密钥表示AES-128 2)代码没有iVector,这意味着ECB模式 3)在我的情况下,将padding用作pkcs5或pkcs7并没有任何区别

答案 1 :(得分:2)

创建字符串扩展名,并使用以下功能进行加密解密

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

答案 2 :(得分:1)

请对AES encryptiondecryption使用以下库。它也适用于iOS,Android和Web。

Reference URL

对于iOS

OS / Swift 3,4

添加桥接头。 Apple documentation

#import "CryptLib.h"

let plainText = "this is my plain text"
let key = "your key"

let cryptLib = CryptLib()

let cipherText = cryptLib.encryptPlainTextRandomIV(withPlainText: plainText, key: key)
print("cipherText \(cipherText! as String)")

let decryptedString = cryptLib.decryptCipherTextRandomIV(withCipherText: cipherText, key: key)
print("decryptedString \(decryptedString! as String)")

Android

val plainText = "this is my plain text"
val key = "your key"

val cryptLib = CryptLib()

val cipherText = cryptLib.encryptPlainTextWithRandomIV(plainText, key)
println("cipherText $cipherText")

val decryptedString = cryptLib.decryptCipherTextWithRandomIV(cipherText, key)
println("decryptedString $decryptedString")

avascript / NodeJS / Web

下载库

npm install @skavinvarnan/cryptlib --save

const plainText = "this is my plain text";
const key = "your key";

const cryptLib = require('@skavinvarnan/cryptlib');

const cipherText = cryptLib.encryptPlainTextWithRandomIV(plainText, key);
console.log('cipherText %s', cipherText);

const decryptedString = cryptLib.decryptCipherTextWithRandomIV(cipherText, key);
console.log('decryptedString %s', decryptedString);

对于所有平板ioS / Android / Web,您将获得相同的encryptiondecryption结果。

答案 3 :(得分:0)

尝试一下:

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
}