Server/Secure.cs
author StephaneLenclud
Sun, 15 Jan 2017 18:49:06 +0100
changeset 279 10f0de70b69b
permissions -rw-r--r--
Ground work for display layout support.
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Security;
     5 using System.Text;
     6 using System.Threading.Tasks;
     7 
     8 namespace SharpDisplayManager
     9 {
    10     /// <summary>
    11     /// As per: http://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file
    12     /// </summary>
    13     class Secure
    14     {
    15         static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("kd566slqfjls234895DFG743fqdlskj345SDFDepozwxc,n*ù^$^é");
    16 
    17         public static string EncryptString(System.Security.SecureString input)
    18         {
    19             byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
    20                 System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
    21                 entropy,
    22                 System.Security.Cryptography.DataProtectionScope.CurrentUser);
    23             return Convert.ToBase64String(encryptedData);
    24         }
    25 
    26         public static SecureString DecryptString(string encryptedData)
    27         {
    28             try
    29             {
    30                 byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
    31                     Convert.FromBase64String(encryptedData),
    32                     entropy,
    33                     System.Security.Cryptography.DataProtectionScope.CurrentUser);
    34                 return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
    35             }
    36             catch
    37             {
    38                 return new SecureString();
    39             }
    40         }
    41 
    42         public static SecureString ToSecureString(string input)
    43         {
    44             SecureString secure = new SecureString();
    45             foreach (char c in input)
    46             {
    47                 secure.AppendChar(c);
    48             }
    49             secure.MakeReadOnly();
    50             return secure;
    51         }
    52 
    53         public static string ToInsecureString(SecureString input)
    54         {
    55             string returnValue = string.Empty;
    56             IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
    57             try
    58             {
    59                 returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
    60             }
    61             finally
    62             {
    63                 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
    64             }
    65             return returnValue;
    66         }
    67     }
    68 }