M
Meron LAVIE
I am writing some encryption utilities. Obviously, I am interested in
ensuring that no trace of the clear, unencrypted data will be left in
memory. Therefore, I dutifully called RtlZeroMemory via pinvoke. This works
fine on byte[] (the source clear data), but when I try it on a String, all
sorts of memory corruption ensues and even VisualStudio itself starts acting
stange (buttons dissapear, etc).
Please find below my code. Any suggestions would be appreciated.
Lavie
ensuring that no trace of the clear, unencrypted data will be left in
memory. Therefore, I dutifully called RtlZeroMemory via pinvoke. This works
fine on byte[] (the source clear data), but when I try it on a String, all
sorts of memory corruption ensues and even VisualStudio itself starts acting
stange (buttons dissapear, etc).
Please find below my code. Any suggestions would be appreciated.
Lavie
Code:
/// <summary>
/// Sets properties for a SymmetricAlgorithm
/// </summary>
/// <param name="symmetricAlgorithm">SymmetricAlgorithm whose properties
should be set</param>
/// <param name="password">Password - WARNING: this methods trounces the
passwords with zeros</param>
private static void SetEncryptionAlgorithmProperties(SymmetricAlgorithm
symmetricAlgorithm, string password)
{
GCHandle gchPassword = GCHandle.Alloc(password, GCHandleType.Pinned);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, SALT);
symmetricAlgorithm.Key =
pdb.GetBytes(symmetricAlgorithm.LegalKeySizes[0].MinSize / BITS_IN_BYTE);
symmetricAlgorithm.IV =
pdb.GetBytes(symmetricAlgorithm.LegalBlockSizes[0].MinSize / BITS_IN_BYTE);
// Trounce the password!
Helper.ZeroMemory(gchPassword.AddrOfPinnedObject(),
(uint)(password.Length*2));
gchPassword.Free();
}
Code:
/// <summary>
/// Zero memory (fill with zeros)
/// </summary>
/// <param name="destinationObject">Address of object in memory, at which
trouncing should commence</param>
/// <param name="length">How many bytes to trounce</param>
/// <returns>Did trouncing succeed</returns>
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory", SetLastError=true)]
public static extern bool ZeroMemory(IntPtr destinationObject, uint length);
[code]