【发布时间】:2013-06-11 16:22:04
【问题描述】:
我正在将用 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 的字符串,在 ruby 中,使用 aes gem,我做到了:
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
【问题讨论】:
-
您似乎还没有触及 PBKDF2 (
Rfc2898DeriveBytes) 的部分。也许首先阅读密码学。然后开始与密钥派生部分。 -
@owlstead 我做到了,但没有运气。你能看看我在 ruby 中的尝试吗?
-
如果您的密钥 is 32 字节,那么我认为您必须使用 AES-256。 AES 中的 256 是密钥大小,所以
256 / 8 = 32...首先比较派生的密钥值(十六进制),然后继续 AES 部分...
标签: .net ruby encryption aes