source: Common/SecureApi.cs

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