Last active
April 1, 2018 19:40
-
-
Save mjs3339/e3d35e1b8a86c1b49aacba4452261e3b to your computer and use it in GitHub Desktop.
C# Secure String Helper Class ToByteArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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