Advertisement
Geograph

Untitled

May 23rd, 2017
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Security;
  3. using System.Runtime.InteropServices;
  4.  
  5. class Program
  6. {
  7.     static void Main(string[] args)
  8.     {
  9.         var str = "Is this string secure?";
  10.  
  11.         using (var secureString = new SecureString())
  12.         {
  13.             foreach (var chr in str)
  14.             {
  15.                 secureString.AppendChar(chr);
  16.             }
  17.             secureString.MakeReadOnly();
  18.  
  19.             Console.WriteLine(secureString.ToString());
  20.             Console.WriteLine(secureString.GetString());
  21.         }
  22.  
  23.         Console.ReadLine();
  24.     }
  25. }
  26.  
  27. static class SecureStringExtension
  28. {
  29.     public static string GetString(this SecureString source)
  30.     {
  31.         if (source == null) throw new ArgumentNullException("source");
  32.  
  33.         var length = source.Length;
  34.         string result = null;
  35.         char[] chars = new char[length];
  36.         IntPtr pointer = IntPtr.Zero;
  37.  
  38.         try
  39.         {
  40.             pointer = Marshal.SecureStringToBSTR(source);
  41.             Marshal.Copy(pointer, chars, 0, length);
  42.  
  43.             result = String.Join("", chars);
  44.         }
  45.         catch (Exception ex)
  46.         {
  47.             throw new InvalidOperationException("Get data error", ex);
  48.         }
  49.         finally
  50.         {
  51.             if (pointer != IntPtr.Zero)
  52.             {
  53.                 Marshal.ZeroFreeBSTR(pointer);
  54.             }
  55.         }
  56.  
  57.         return result;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement