1 |
|
---|
2 | using System;
|
---|
3 | using System.Runtime.InteropServices;
|
---|
4 | using System.Security;
|
---|
5 | using System.Security.Cryptography;
|
---|
6 | using System.Text;
|
---|
7 | namespace HeuristicLab.Clients.Hive.CloudManager {
|
---|
8 | // see: http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx
|
---|
9 | public static class CryptoService {
|
---|
10 | private static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Salt Is Not A Password");
|
---|
11 |
|
---|
12 | public static string EncryptString(SecureString input) {
|
---|
13 | byte[] encryptedData = ProtectedData.Protect(
|
---|
14 | Encoding.Unicode.GetBytes(ToInsecureString(input)),
|
---|
15 | entropy,
|
---|
16 | DataProtectionScope.CurrentUser);
|
---|
17 | return Convert.ToBase64String(encryptedData);
|
---|
18 | }
|
---|
19 |
|
---|
20 | public static SecureString DecryptString(string encryptedData) {
|
---|
21 | try {
|
---|
22 | byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
|
---|
23 | Convert.FromBase64String(encryptedData),
|
---|
24 | entropy,
|
---|
25 | System.Security.Cryptography.DataProtectionScope.CurrentUser);
|
---|
26 | return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
|
---|
27 | }
|
---|
28 | catch {
|
---|
29 | return new SecureString();
|
---|
30 | }
|
---|
31 | }
|
---|
32 |
|
---|
33 | public static SecureString ToSecureString(string input) {
|
---|
34 | SecureString secure = new SecureString();
|
---|
35 | foreach (char c in input) {
|
---|
36 | secure.AppendChar(c);
|
---|
37 | }
|
---|
38 | secure.MakeReadOnly();
|
---|
39 | return secure;
|
---|
40 | }
|
---|
41 |
|
---|
42 | public static string ToInsecureString(SecureString input) {
|
---|
43 | string returnValue = string.Empty;
|
---|
44 | IntPtr ptr = Marshal.SecureStringToBSTR(input);
|
---|
45 | try {
|
---|
46 | returnValue = Marshal.PtrToStringBSTR(ptr);
|
---|
47 | }
|
---|
48 | finally {
|
---|
49 | Marshal.ZeroFreeBSTR(ptr);
|
---|
50 | }
|
---|
51 | return returnValue;
|
---|
52 | }
|
---|
53 | }
|
---|
54 | }
|
---|