Ukladani do SecureString ma jednu velkou vyhodu – pokud se pokusite pouzit stejne soubory na jinem PC nebo uctu, Windows vam je neprijme a budete se muset znovu prihlasit. A k heslu se taky nikdo nedostane, pokud zrovna ho nebudete vypisovat nekde v aplikaci, nejhure v plain textu. A protoze jsem si porad myslel ze chyba je nekde ve tride ktere pracuji s SecureString, hledal jsem dalsi zpusoby jak s nim pracovat. Nakonec jsem vytvoril tyto 2 tridy – trida Unsafe jak nazev napovida nemusi byt pro uzivatele verohodna, takovou assembly musite jako unsafe oznacit, jinak vam ji kompilator nezkompiluje. Proto doporucuji pouzit tridu SecureStringHelper, ktera dela uplne tutez praci, jen v kontextu managed kodu. A ted k obema tridam:
Unsafe:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Runtime.InteropServices; using System.Security; public static class Unsafe { public static SecureString ToSecureString(this string value) { unsafe { fixed (char* value3 = value) { SecureString ss = new System.Security.SecureString(value3, value.Length); ss.MakeReadOnly(); return ss; } } } public static string ToInsecureString(SecureString securePassword) { IntPtr unmanagedString = IntPtr.Zero; try { unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword); return Marshal.PtrToStringUni(unmanagedString); } finally { Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); } } } |
SecureStringHelper:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Security; public class SecureStringHelper { public static SecureString ToSecureString(string input) { SecureString secure = new SecureString(); foreach (char c in input) { secure.AppendChar(c); } secure.MakeReadOnly(); return secure; } public static string ToInsecureString(SecureString input) { string returnValue = string.Empty; IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input); try { returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr); } finally { System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr); } return returnValue; } } |