我一直在尝试在iOS和.NET上进行加密和解密,但并没有取得成功。我使用过this question,但出现错误:


  指定的初始化向量(IV)与该算法的块大小不匹配。


这是我使用CryptoSwift为Swift编写的加密代码:

let encrypt = try! "oauth_token".AES_encrypt("my key here (is 32 characters long)", iv: "1234567890123456")

func AES_encrypt(key: String, iv: String) throws -> String {
    let data = self.dataUsingEncoding(NSUTF8StringEncoding)
    let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data!.arrayOfBytes(), padding: PKCS7())
    let encData = NSData(bytes: enc, length: Int(enc.count))
    let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
    let result = String(base64String)
    return result
}



而我的.NET解密代码:

public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] key, byte[] iv)
    {
        byte[] decryptedBytes = null;

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;

                AES.Key = key;
                AES.IV = iv;

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                    cs.Close();
                }
                decryptedBytes = ms.ToArray();
            }
        }

        return decryptedBytes;
    }



byte[] encrypted_text = Convert.FromBase64String("secret token");
byte[] key = Convert.FromBase64String("32 character key");
byte[] iv = Convert.FromBase64String("0123456789012345");

string plaintext = Convert.ToBase64String(AES_Decrypt(encrypted_text, key, iv));

最佳答案

块大小为16个字节(AES.blockSize)。您正在使用旧版本,或者您的AES_encrypt()遇到了一些问题(AES_encrypt不是CryptoSwift的一部分)。

自述文件中的一个简单示例:

let input: NSData // data to encrypt
let encrypted = try? input.encrypt(AES(key: "secret0key000000", iv:"0123456789012345"))


或这个

// Encrypt string and get Base64 representation of result
let base64: String = try? "my secret string".encrypt(AES(key: "secret0key000000", iv: "0123456789012345"))

关于c# - AES 128跨平台Swift/C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35212647/

10-13 07:56