Created
December 12, 2019 09:50
-
-
Save TomasBouda/94f677e5a9cb8eb1815877508eb14f82 to your computer and use it in GitHub Desktop.
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 static class StringEncryption | |
{ | |
private static readonly byte[] Entropy = Encoding.Unicode.GetBytes("4asd894a9d8as5d4sad4asd48sa9w8d4aw8da1d"); | |
public static string EncryptString(this SecureString input) | |
{ | |
var encryptedData = ProtectedData.Protect( | |
Encoding.Unicode.GetBytes(ToInsecureString(input)), | |
Entropy, | |
DataProtectionScope.CurrentUser); | |
return Convert.ToBase64String(encryptedData); | |
} | |
public static SecureString DecryptString(this string encryptedData) | |
{ | |
try | |
{ | |
var decryptedData = ProtectedData.Unprotect( | |
Convert.FromBase64String(encryptedData), | |
Entropy, | |
DataProtectionScope.CurrentUser); | |
return ToSecureString(Encoding.Unicode.GetString(decryptedData)); | |
} | |
catch | |
{ | |
return new SecureString(); | |
} | |
} | |
public static SecureString ToSecureString(this string input) | |
{ | |
var secure = new SecureString(); | |
foreach (var c in input) | |
{ | |
secure.AppendChar(c); | |
} | |
secure.MakeReadOnly(); | |
return secure; | |
} | |
public static string ToInsecureString(this SecureString input) | |
{ | |
string returnValue; | |
var ptr = Marshal.SecureStringToBSTR(input); | |
try | |
{ | |
returnValue = Marshal.PtrToStringBSTR(ptr); | |
} | |
finally | |
{ | |
Marshal.ZeroFreeBSTR(ptr); | |
} | |
return returnValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment