Amazon.Runtime.Internal.Settings.UserCrypto.Decrypt C# (CSharp) Method

Decrypt() public static method

public static Decrypt ( string encrypted ) : string
encrypted string
return string
        public static string Decrypt(string encrypted)
        {
            List<Byte> dataIn = new List<byte>();
            for (int i = 0; i < encrypted.Length; i = i + 2)
            {
                byte data = Convert.ToByte(encrypted.Substring(i, 2), 16);
                dataIn.Add(data);
            }

            CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN;
            DATA_BLOB encryptedBlob = ConvertData(dataIn.ToArray());
            DATA_BLOB unencryptedBlob = new DATA_BLOB();
            DATA_BLOB dataOption = new DATA_BLOB();

            try
            {

                CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
                if (!CryptUnprotectData(ref encryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref unencryptedBlob))
                {
                    int errCode = Marshal.GetLastWin32Error();
                    throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode);
                }

                byte[] outData = new byte[unencryptedBlob.cbData];
                Marshal.Copy(unencryptedBlob.pbData, outData, 0, outData.Length);

                string unencrypted = Encoding.Unicode.GetString(outData);
                return unencrypted;
            }
            finally
            {
                if (encryptedBlob.pbData != IntPtr.Zero)
                    Marshal.FreeHGlobal(encryptedBlob.pbData);
                if (unencryptedBlob.pbData != IntPtr.Zero)
                    Marshal.FreeHGlobal(unencryptedBlob.pbData);
            }
        }

Usage Example

 void decryptAnyEncryptedValues(Dictionary <string, Dictionary <string, object> > settings)
 {
     foreach (var kvp in settings)
     {
         string settingsKey      = kvp.Key;
         var    objectCollection = kvp.Value;
         foreach (string key in new List <string>(objectCollection.Keys))
         {
             if (IsEncrypted(key) || IsEncrypted(settingsKey))
             {
                 string value = objectCollection[key] as string;
                 if (value != null)
                 {
                     try
                     {
                         objectCollection[key] = UserCrypto.Decrypt(value);
                     }
                     catch (Exception e)
                     {
                         objectCollection.Remove(key);
                         var logger = Logger.GetLogger(typeof(PersistenceManager));
                         logger.Error(e, "Exception decrypting value for key {0}/{1}", settingsKey, key);
                     }
                 }
             }
         }
     }
 }
All Usage Examples Of Amazon.Runtime.Internal.Settings.UserCrypto::Decrypt