{"id":275,"date":"2020-12-10T20:04:16","date_gmt":"2020-12-10T20:04:16","guid":{"rendered":"https:\/\/michaeljohnsteiner.com\/?p=275"},"modified":"2020-12-10T20:04:16","modified_gmt":"2020-12-10T20:04:16","slug":"securestringhelper-cs","status":"publish","type":"post","link":"https:\/\/michaeljohnsteiner.com\/index.php\/2020\/12\/10\/securestringhelper-cs\/","title":{"rendered":"SecureStringHelper.cs"},"content":{"rendered":"\n<p>Secure String Helper Class<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class SecureStringHelper : IDisposable\n    {\n        private readonly Encoding     _encoding;\n        private readonly SecureString _secureString;\n        private          byte[]       _bytes;\n        private          bool         _disposed;\n        public SecureStringHelper(SecureString secureString) : this(secureString, Encoding.Default)\n        {\n        }\n        public SecureStringHelper(SecureString secureString, Encoding encoding)\n        {\n            if(secureString == null)\n                throw new Exception(nameof(secureString));\n            _encoding     = encoding ?? Encoding.Default;\n            _secureString = secureString;\n        }\n        public void Dispose()\n        {\n            if(!_disposed)\n            {\n                Destroy();\n                _disposed = true;\n            }\n            GC.SuppressFinalize(this);\n        }\n        public static string ToString(SecureString secureStr)\n        {\n            var Str = new NetworkCredential(string.Empty, secureStr).Password;\n            return Str;\n        }\n        public static SecureString ToSecureString(string password)\n        {\n            if(password == null)\n                throw new Exception(\"Error: Password cannot be null.\");\n            var securePassword = new SecureString();\n            foreach(var c in password)\n                securePassword.AppendChar(c);\n            securePassword.MakeReadOnly();\n            return securePassword;\n        }\n        internal unsafe byte[] ToByteArray()\n        {\n            if(_bytes != null)\n            {\n                _bytes.Fill(0);\n                _bytes = null;\n            }\n            var maxLength = _encoding.GetMaxByteCount(_secureString.Length);\n            var bytes     = IntPtr.Zero;\n            var str       = IntPtr.Zero;\n            try\n            {\n                bytes = Marshal.AllocHGlobal(maxLength);\n                str   = Marshal.SecureStringToBSTR(_secureString);\n                var chars = (char*) str.ToPointer();\n                var bptr  = (byte*) bytes.ToPointer();\n                var len   = _encoding.GetBytes(chars, _secureString.Length, bptr, maxLength);\n                _bytes = new byte[len];\n                for(var i = 0; i &lt; len; ++i)\n                {\n                    _bytes[i] = *bptr;\n                    bptr++;\n                }\n                return _bytes;\n            }\n            finally\n            {\n                if(bytes != IntPtr.Zero)\n                    Marshal.FreeHGlobal(bytes);\n                if(str != IntPtr.Zero)\n                    Marshal.ZeroFreeBSTR(str);\n            }\n        }\n        private void Destroy()\n        {\n            if(_bytes != null)\n            {\n                _bytes.Fill(0);\n                _bytes = null;\n            }\n        }\n    }\n\npublic static class SecureStringEx\n    {\n        \/\/\/ &lt;summary>\n        \/\/\/     Converts a standard string to a secure string\n        \/\/\/ &lt;\/summary>\n        public static SecureString ToSecureString(this string password)\n        {\n            if(password == null)\n                throw new Exception(\"Error: Password cannot be null.\");\n            var securePassword = new SecureString();\n            foreach(var c in password)\n                securePassword.AppendChar(c);\n            securePassword.MakeReadOnly();\n            return securePassword;\n        }\n    }<\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Secure String Helper Class<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[134,133,27,135,136],"_links":{"self":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/275"}],"collection":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/comments?post=275"}],"version-history":[{"count":1,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/275\/revisions"}],"predecessor-version":[{"id":276,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/275\/revisions\/276"}],"wp:attachment":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/media?parent=275"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/categories?post=275"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/tags?post=275"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}