你好,我有一个用C#编写的加密算法,需要将其移植到Ruby。
private string Encrypt(string clearText)
{
string EncryptionKey = "ENC_KEY";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream()) {
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length); cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray()); }
}
return clearText;
}
据我理解,该算法生成AES密钥和iv并进行加密,返回base 64字符串。
我没有找到Rfc2898DeriveBytes的确切替代方法,我使用了PBKDF2 Gem。这是我的Ruby方法:
def self.encrypt clear_text
iterations = 1000
encryption_key = 'EncryptionKey'
clearBytes = clear_text.encode( 'UTF-16LE' ).bytes.to_a
enc_bytes = [0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11]
salt = enc_bytes.pack('C*')
derived_a = PBKDF2.new do |p|
p.password = encryption_key
p.salt = salt
p.iterations = iterations
p.key_length = 32
end
derived_b = PBKDF2.new do |p|
p.password = encryption_key
p.salt = salt
p.iterations = iterations
p.key_length = 16
end
key = derived_a.bin_string
# iV = derived_b.bin_string
iV_a = iV_a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] # Static iV
iV = iV_a.pack('C*')
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.key = key
cipher.iv = iV
encrypted = cipher.update(clear_text) + cipher.final
Base64.encode64(encrypted)
end
我的代码中有两个问题。我无法在iv和使用它作为静态值时获取相同的值,而且返回值不匹配。
我没有太多的C#经验。我漏掉了什么?