Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Security;
- using System.Runtime.InteropServices;
- class Program
- {
- static void Main(string[] args)
- {
- var str = "Is this string secure?";
- using (var secureString = new SecureString())
- {
- foreach (var chr in str)
- {
- secureString.AppendChar(chr);
- }
- secureString.MakeReadOnly();
- Console.WriteLine(secureString.ToString());
- Console.WriteLine(secureString.GetString());
- }
- Console.ReadLine();
- }
- }
- static class SecureStringExtension
- {
- public static string GetString(this SecureString source)
- {
- if (source == null) throw new ArgumentNullException("source");
- var length = source.Length;
- string result = null;
- char[] chars = new char[length];
- IntPtr pointer = IntPtr.Zero;
- try
- {
- pointer = Marshal.SecureStringToBSTR(source);
- Marshal.Copy(pointer, chars, 0, length);
- result = String.Join("", chars);
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("Get data error", ex);
- }
- finally
- {
- if (pointer != IntPtr.Zero)
- {
- Marshal.ZeroFreeBSTR(pointer);
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement