让.NET中的SlowAES和RijndaelManaged类一起玩

时间:2009-07-19 10:17:25

标签: .net javascript aes rijndaelmanaged pbkdf2

我正在尝试使用.NET中的javascript库SlowAESRijndaelManaged类来设置AES加密/解密。

我在阅读this post之后选择了这种方法,其中Cheeso设法让这两种加密方法一起玩

  

“在我的测试中   COM-wrapped-SlowAEs,我使用CBC模式,   加密完全是   与RijndaelManaged兼容   .NET中的类“ - Cheeso

我从Cheeso的Windows Scripting Component,最新的slowaes库中获取了javascript代码,并使用以下javascript脚本进行测试:

var key = "12345678901234567890123456789012";
var message = "watson?";
var decrypted;

slowAES.aes.keySize.SIZE_256;
slowAES.modeOfOperation.CBC;
put_PassPhrase(key);
var result = EncryptString(message);
decrypted = DecryptCommaDelimitedStringToString(result)
document.write("Key:" + key + "<br />original:" + message + "<br />Cypher:" + result + "<br />Decrypted:" + decrypted + "<br />IV(): " + get_IV());

我得到以下输出:

Key:12345678901234567890123456789012
original:watson?
Cypher:245,159,1,1,168,1,1,143,1,1,146,1,1,239,117,1
Decrypted:watson? 
IV(): 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

我修改了以下示例找到on MSDN以尝试匹配C#中的加密:

public static void Main()
        {
            try
            {
                string original = "watson?";
                byte[] IV = new byte[16];   // match slowaes IV
                byte[] key = new System.Text.ASCIIEncoding().GetBytes("12345678901234567890123456789012");// match slowaes KEY

                RijndaelManaged myRijndael = new RijndaelManaged();
                myRijndael.BlockSize = 128;
                myRijndael.KeySize = 256;
                myRijndael.Mode = CipherMode.CBC;

                // Encrypt the string to an array of bytes.
                byte[] encrypted = encryptStringToBytes_AES(original, key, IV);

                // Decrypt the bytes to a string.
                string roundtrip = decryptStringFromBytes_AES(encrypted, key, IV);

                //Display the original data and the decrypted data.
                Console.WriteLine("Original:   {0}", original);
                Console.WriteLine("Round Trip: {0}", roundtrip);

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }

观察字节数组:

-  encrypted {byte[16]} byte[]
  [0] 139 byte
  [1] 104 byte
  [2] 166 byte
  [3] 35 byte
  [4] 8 byte
  [5] 42 byte
  [6] 216 byte
  [7] 160 byte
  [8] 235 byte
  [9] 153 byte
  [10] 23 byte
  [11] 143 byte
  [12] 105 byte
  [13] 3 byte
  [14] 24 byte
  [15] 255 byte

我已经尝试了托管.NET类的所有填充选项,但是我无法获得匹配的加密输出。任何人都可以帮助我吗?

谢谢,

鲍勃

1 个答案:

答案 0 :(得分:37)

也许我可以帮忙。

我拿了你的C#代码并稍加修改。我使用的C#代码完全是:

using System;
using System.Security.Cryptography;

public class Bob
{
    internal static string FormatByteArray(byte[] b)
    {
        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
        int i = 0;
        for (i = 0; i < b.Length; i++)
        {
            if (i != 0 && i % 16 == 0)
                sb1.Append("\n");
            sb1.Append(System.String.Format("{0:X2} ", b[i]));
        }
        return sb1.ToString();
    }

    public static void Main()
    {
        try
        {
            string original = "watson?";

            Console.WriteLine("Original:   {0}", original);

            byte[] IV = new byte[16];   // match slowaes IV
            var ascii = new System.Text.ASCIIEncoding();

            // match slowaes KEY
            string passPhrase = "12345678901234567890123456789012";
            byte[] key = ascii.GetBytes(passPhrase);

            RijndaelManaged myRijndael = new RijndaelManaged();
            myRijndael.BlockSize = 128;
            myRijndael.KeySize = 256;
            myRijndael.IV = IV;
            myRijndael.Padding   = PaddingMode.PKCS7;
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.Key = key;

            // Encrypt the string to an array of bytes.
            byte[] plainText = new System.Text.ASCIIEncoding().GetBytes(original);
            ICryptoTransform transform = myRijndael.CreateEncryptor();
            byte[] cipherText = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            Console.WriteLine("cipherText: {0}", FormatByteArray(cipherText));

            // Decrypt the bytes to a string.
            transform = myRijndael.CreateDecryptor();
            plainText = transform.TransformFinalBlock(cipherText, 0, cipherText.Length);


            string roundtrip = ascii.GetString(plainText);

            Console.WriteLine("Round Trip: {0}", roundtrip);

        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
    }

}

编译上面的内容
csc.exe /target:exe /out:Bob.exe Bob.cs

我使用你引用的其他帖子中的slowAES.wsc,有2个更改:我没有为EncryptString或DecryptString()方法中的键调用getPaddedBlock()。这真的需要一个PBKDF,但现在不要担心。这是修改后的EncryptString的样子:

function EncryptString(plainText)
{
  // this is really wrong - need a PBBKDF to get the key, instead
  // of just using the passphrase
  var key = cryptoHelpers.convertStringToByteArray(_passphrase);
  // var nkey = slowAES.getPaddedBlock(key, 0, _keysize, _mode);
  var bytesToEncrypt = cryptoHelpers.convertStringToByteArray(plainText);

  var result = slowAES.encrypt(bytesToEncrypt, 
      _mode,
      key,
      _keysize,
      _iv);
  return result['cipher'];
}

这意味着您必须使用完全密钥大小所需长度的passPhrase。如果使用AES256,则传递32个字符串(32 * 8 = 256位)。好像你已经想到了这一点。

WSC组件的客户端也是Javascript(尽管它可以是任何COM语言)。这是我用的。

function toHexString(a)
{
    var ret = '';
    for(var i = 0;i < a.length;i++)
        ret += (a[i] < 16 ? '0' : '') + a[i].toString(16) + ' ';
    return ret.toLowerCase();
}


//var plaintext = "Hello. This is a test. of the emergency broadcasting system.";
var plaintext = "watson?";

try
{
    WScript.echo( "plaintext: " + plaintext);
    WScript.echo( "plaintext.length: " + plaintext.length);

    WScript.echo( "instantiate ");
    var aes = new ActiveXObject("Ionic.Com.SlowAES");

    WScript.echo( "keysize ");
    aes.KeySize = 256;

    WScript.echo( "passphrase ");
    aes.PassPhrase= "12345678901234567890123456789012";  // 32 chars long

    WScript.echo( "mode ");
    aes.Mode = "CBC";

    WScript.echo( "encrypting... ");
    var result = aes.EncryptString(plaintext);

    WScript.echo( "Cryptotext: " + toHexString(result));

    WScript.echo( "decrypting... ");
    var decrypted = aes.DecryptBytesToString(result);

    WScript.echo( "decrypted: " + decrypted);
}
catch(e)
{
    WScript.echo("Exception: " + e); 
    //     WScript.echo(e.Number + ": " + e.Name);
    WScript.echo(e.Message);
}

如果我然后运行此代码,Javascript和C#使用AES256,密码为12345678901234567890123456789012,以及16字节零的IV,为“watson?”的明文生成相同的密文。生成的密文是:

8B 68 A6 23 08 2A D8 A0 EB 99 17 8F 69 03 18 FF

它在两种情况下都成功解密。

编辑:虽然我在一个WSC中打包了slowAES加密,但它也可以在COM环境之外运行。 WSC部分对于这个问题是不必要的,但是有必要证明先前问题的答案,即“how can I get VBScript and .NET AES to interoperate?

EDIT2 :演示Javascript或VBScript与.NET is available之间的AES互操作的源代码。我扩展了这里给出的基本示例,以3种语言生成测试应用程序:C#,Javascript和VBScript。他们都采取相同的论点。它们每个都使用符合RFC2898的密钥派生函数。您可以指定密码,salt,IV和纯文本,以及要在PBKDF2中使用的RFC2898迭代次数。您可以轻松验证每个测试程序的密文是否相同。也许这个例子对某人有用。

<强> EDIT3
好读:Javascript Cryptography considered harmful.