Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# Secure String Helper Class ToByteArray
public class SecureStringHelper : IDisposable
{
private readonly Encoding _encoding;
private readonly SecureString _secureString;
private byte[] _bytes;
private bool _disposed;
public SecureStringHelper(SecureString secureString)
: this(secureString, Encoding.Default)
{
}
public SecureStringHelper(SecureString secureString, Encoding encoding)
{
if (secureString == null)
throw new Exception(nameof(secureString));
_encoding = encoding ?? Encoding.Default;
_secureString = secureString;
}
public static SecureString ToSecureString(string str)
{
if (str == null)
throw new Exception("Error: String cannot be null.");
var securestr = new SecureString();
foreach (var c in str)
securestr.AppendChar(c);
securestr.MakeReadOnly();
return securestr;
}
public void Dispose()
{
if (!_disposed)
{
Destroy();
_disposed = true;
}
GC.SuppressFinalize(this);
}
internal unsafe byte[] ToByteArray()
{
if (_bytes != null)
{
_bytes.Fill(0);
_bytes = null;
}
var maxLength = _encoding.GetMaxByteCount(_secureString.Length);
var bytes = IntPtr.Zero;
var str = IntPtr.Zero;
try
{
bytes = Marshal.AllocHGlobal(maxLength);
str = Marshal.SecureStringToBSTR(_secureString);
var chars = (char*) str.ToPointer();
var bptr = (byte*) bytes.ToPointer();
var len = _encoding.GetBytes(chars, _secureString.Length, bptr, maxLength);
_bytes = new byte[len];
for (var i = 0; i < len; ++i)
{
_bytes[i] = *bptr;
bptr++;
}
return _bytes;
}
finally
{
if (bytes != IntPtr.Zero)
Marshal.FreeHGlobal(bytes);
if (str != IntPtr.Zero)
Marshal.ZeroFreeBSTR(str);
}
}
private void Destroy()
{
if (_bytes != null)
{
_bytes.Fill(0);
_bytes = null;
}
}
~SecureStringHelper()
{
Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment