source: Common/SecureApi.cs

Last change on this file was 15, checked in by chronos, 13 months ago
  • Modified: Updated files.
File size: 1.9 KB
Line 
1using System;
2using System.Text;
3using System.Security;
4using System.Security.Cryptography;
5
6namespace Common
7{
8 static class SecureApi
9 {
10 private static readonly byte[] Entropy = Encoding.Unicode.GetBytes("Salt Is Not A Password");
11
12 public static string EncryptString(SecureString input)
13 {
14 byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),
15 Entropy, DataProtectionScope.CurrentUser);
16 return Convert.ToBase64String(encryptedData);
17 }
18
19 public static SecureString DecryptString(string encryptedData)
20 {
21 try
22 {
23 byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData), Entropy,
24 DataProtectionScope.CurrentUser);
25 return ToSecureString(Encoding.Unicode.GetString(decryptedData));
26 }
27 catch
28 {
29 return new SecureString();
30 }
31 }
32
33 public static SecureString ToSecureString(string input)
34 {
35 SecureString secure = new SecureString();
36 foreach (char c in input)
37 {
38 secure.AppendChar(c);
39 }
40 secure.MakeReadOnly();
41 return secure;
42 }
43
44 public static string ToInsecureString(SecureString input)
45 {
46 string returnValue;
47 IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
48 try
49 {
50 returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
51 }
52 finally
53 {
54 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
55 }
56 return returnValue;
57 }
58 }
59}
Note: See TracBrowser for help on using the repository browser.