Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1680_HeuristicLab.Hive.Azure/HeuristicLab.Clients.Hive.CloudManager/3.3/CryptoService.cs @ 17712

Last change on this file since 17712 was 7663, checked in by spimming, 13 years ago

#1680: encrypt/decrypt azure subscription data

File size: 1.8 KB
Line 
1
2using System;
3using System.Runtime.InteropServices;
4using System.Security;
5using System.Security.Cryptography;
6using System.Text;
7namespace 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}
Note: See TracBrowser for help on using the repository browser.