C#Rijndael在Ruby中太短了

时间:2016-10-13 14:08:44

标签: c# ruby encryption aes rijndaelmanaged

我正在尝试在Ruby中重新实现C#代码。以下代码(具有不同的秘密)用于解密文件:

using System.IO;
using System.Security.Cryptography;
using System.Text;

public static class Decrypt {
  private const string KEY = "FOOBARB";

  private static readonly byte[] IV = {
    126, 36, 216, 236, 247, 79, 205, 111, 240, 119, 197, 10, 19, 216, 139, 91
  };

  public static Stream ReadEncryptedFile(string filePath) {
    var fs = new FileStream(
      filePath,
      FileMode.OpenOrCreate,
      FileAccess.ReadWrite
    );

    byte[] key = new UnicodeEncoding().GetBytes(KEY);
    byte[] vector = IV;

    using (var rijndaelEncryption = new RijndaelManaged()) {
      var decryptor = rijndaelEncryption.CreateDecryptor(key, vector);
      return new CryptoStream(fs, decryptor, CryptoStreamMode.Read);
    }
  }

  public static void Main() {
    var crReader = ReadEncryptedFile(
      "/path/to/file"
    );
    StreamReader reader = new StreamReader(crReader);
    System.Console.WriteLine(reader.ReadToEnd());
  }
}

我知道CBC是正确的密码模式,因为System.Console.WriteLine(rijndaelEncryption.Mode)会返回CBC。我知道输入和输出块大小是256位,因为decryptor.OutputBlockSizedecryptor.InputBlockSize都返回 16 32.(我意识到密钥大小也进入并确实定义了区别正如所讨论的AES和Rijndael here - 但我不确定它是如何工作的。)

无论如何,当我运行以下Ruby代码时,我得到in 'key=': key length too short (OpenSSL::Cipher::CipherError)(我也尝试过128位和192位版本的AES / CBC,尽管这不应该在这里产生影响):

require 'openssl'

f = File.read(
  'path/to/file'
)

key = 'FOOBARB'

iv = [126, 36, 216, 236, 247, 79, 205, 111, 240, 119, 197, 10, 19, 216, 139, 91]
     .pack('c*')

cipher = OpenSSL::Cipher.new('AES-256-CBC')

cipher.decrypt

cipher.key = key
cipher.iv = iv

puts cipher.update(f)

所以,我想,有三个问题:

  1. C#如何填充56位密钥以使其与需要至少128位密钥的算法一起使用?
  2. 我尝试使用Ruby的OpenSSL库来完成此任务,Rijndael和AES之间的区别是否致命?
  3. 一旦/如果我让密钥正常工作,我是否需要担心here所描述的字符编码?
  4. 谢谢。

1 个答案:

答案 0 :(得分:0)

如果您尝试将AES与Rijndael一起使用,则需要将块大小设置为128位(16字节),这是AES支持的唯一块大小。许多Rijndael实现调用约定指定块大小,密钥大小确定购买提供的密钥。

AES密钥大小为128,192或256位,最好提供完全正确的大小,不要依赖于实现依赖密钥填充。

相关问题