我正在将用 Microsoft .net 框架编写的 web 服务/数据库迁移到 ruby。我被困在密码加密部分,因为我无法在 ruby 端复制加密。这是在 .net 中生成加密密码的代码:
private static String GetSecret()
{
string nexus = ConfigurationManager.AppSettings["Nexus"];
System.Security.SecureString plain = ProtectedSettings.DecryptString(nexus);
return ProtectedSettings.ToInsecureString(plain);
}
private static String EncryptPassword(string password)
{
return SymmetricEncryption.Encrypt<AesManaged>(password, GetSecret());
}
我nexus
使用 aes gem 将字符串命名为 ruby,我做了:
AES.encrypt(a_password, key)
但生成的哈希与.net 中的不匹配。我错过了什么?谢谢
这是加密功能:
public static string Encrypt<T>(string value, string password, string salt = "4AFB7A1414E4486FAB51A42F5D0D6E7B")
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
好的,所以我尝试将此代码转换为 ruby,但没有运气:
p = PBKDF2.new(:password => pass, :salt => salt, :iterations => 1000)
iv = p.hash_function.digest[0..15]
key = p.hash_function.digest[0..31]
aes = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
aes.encrypt
aes.key = key
aes.iv = iv
aes.update("1123581321") + aes.final