嗨,我在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;
}
据我了解,alghorithm会生成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
我的代码中有2个问题.我无法在iv上获得相同的值,如果我将其用作静态值,则返回值不匹配.
我没有太多的C#经验.我想念什么?
解决方法:
看起来您的PBKDF2生成算法具有固定的输入,因此生成的Key和IV应该始终相同.
我只是在修改后的机器上运行了C#代码,以输出Key和IV的值.它给了我:
takKsX7IBXq3R0Q5GWgJo/XhhEHDNfRFxSVru12vtU4=
y/lm9eKzBJTMdU+uA6GlXA==
作为Key和IV的Base64编码值.您可以只在Ruby代码中使用这些值,这样就无需继续使用PBKDF2 gem生成这些值.
所以这个Ruby代码
clear_text = 'HELLO WORLD'
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.key = Base64.decode64('takKsX7IBXq3R0Q5GWgJo/XhhEHDNfRFxSVru12vtU4=')
cipher.iv = Base64.decode64('y/lm9eKzBJTMdU+uA6GlXA==')
clearBytes = clearText.encode('UTF-16LE')
encrypted = cipher.update(clearBytes)
encrypted << cipher.final
puts Base64.encode64(encrypted)
将输出与Encrypt(“ HELLO WORLD”)相同的内容