AES 128跨平台Swift / C#

时间:2016-02-04 22:11:51

标签: c# swift aes rijndaelmanaged

我一直在尝试在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));

1 个答案:

答案 0 :(得分:1)

块大小为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"))