I am migrating a webservice/database written in Microsoft .net framework to ruby. I am stuck at the password encryption part because I can't replicate the encryption on ruby side. Here's the code that generates an encrypted password in .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());
}
I got the string named nexus
and in ruby, using the aes gem, I did:
AES.encrypt(a_password, key)
but the generated hash doesn't match the one in .net. What am I missing? thanks
Here's the Encrypt function:
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());
}
}
Ok so I have tried converting this code to ruby, but with no luck:
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