I am trying to reimplement C# code in Ruby. The following code (with different secrets) works to decrypt the file:
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());
}
}
I know that CBC
is the correct cipher mode because System.Console.WriteLine(rijndaelEncryption.Mode)
returns CBC
. I know the input and output block size is 256 bits because decryptor.OutputBlockSize
and decryptor.InputBlockSize
both return 16 32. (I realize the key size also enters in and indeed defines the distinction between AES and Rijndael as discussed here—but I'm not sure exactly how that works.)
Anyway, I get a in 'key=': key length too short (OpenSSL::Cipher::CipherError)
when I run the following Ruby code (I have also tried the 128-bit and 192-bit versions of AES/CBC, though that shouldn't make the difference here):
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)
So, I think, three questions:
- How does C# pad a 56-bit key to make it work with an algorithm requiring at least a 128-bit key?
- Are the differences between Rijndael and AES fatal to my trying to use Ruby's OpenSSL library for this task?
- Once/if I get the key working, am I going to need to worry about character encoding as described here?
Thank you.