when you encrypted the data, you probably missed calling FlushFinalBlock()
Encryption
ANB
181
Reputation points
Hi there,
I have a method which gets a encrypted value and will be decrypted to a guid that I have on my database.
It almost works, but the problem is the 4 last guid characteres are missing. Why ?
public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new()
{
byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
byte[] saltBytes = Encoding.ASCII.GetBytes(_salt);
byte[] valueBytes = Convert.FromBase64String(value);
byte[] decrypted;
int decryptedByteCount = 0;
using (T cipher = new T())
{
PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
try
{
using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes))
{
using (MemoryStream from = new MemoryStream(valueBytes))
{
using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read))
{
decrypted = new byte[valueBytes.Length];
decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
}
}
}
}
catch (Exception ex)
{
return String.Empty;
}
cipher.Clear();
}
var xxxx = Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
}
Thx guys !
2 answers
Sort by: Most helpful
-
-
ANB 181 Reputation points
2022-05-10T22:01:47.117+00:00 No. I do have it.
public static string Encrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() { byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector); byte[] saltBytes = Encoding.ASCII.GetBytes(_salt); byte[] valueBytes = Encoding.UTF8.GetBytes(value); byte[] encrypted; using (T cipher = new T()) { PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) { using (MemoryStream to = new MemoryStream()) { using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) { writer.Write(valueBytes, 0, valueBytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); } } } cipher.Clear(); } return Convert.ToBase64String(encrypted); }