DroidExplorer.Bootstrapper.Authentication.DPAPI.Decrypt C# (CSharp) Method

Decrypt() public method

public Decrypt ( byte cipherTextBytes ) : byte[]
cipherTextBytes byte
return byte[]
        public byte[] Decrypt( byte[] cipherTextBytes )
        {
            DataBlob plainTextBlob = new DataBlob ( );
            DataBlob cipherTextBlob = new DataBlob ( cipherTextBytes );
            DataBlob entropyBlob = new DataBlob ( entropy );

            description = "";

            try {
                CryptProtectFlags flags = CryptProtectFlags.UIForbidden;

                if ( !CryptUnprotectData ( ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, flags, ref plainTextBlob ) )
                    throw new COMException ( "CryptUnprotectData failed. ", Marshal.GetLastWin32Error ( ) );

                byte[] plainTextBytes = new byte[ plainTextBlob.cbData ];

                Marshal.Copy ( plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData );
                return plainTextBytes;
            } catch ( Exception ex ) {
                throw new Exception ( "DPAPI was unable to decrypt data. " + ex.Message );
            } finally {
                if ( plainTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( plainTextBlob.pbData );

                if ( cipherTextBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( cipherTextBlob.pbData );

                if ( entropyBlob.pbData != IntPtr.Zero )
                    Marshal.FreeHGlobal ( entropyBlob.pbData );
            }
        }

Usage Example

        public bool LoadCredentials( )
        {
            if (!DPAPI.CanUseDPAPI)
            {
                return(false);
            }
            if (File.Exists(PersistFile))
            {
                byte[] cipher;
                using (FileStream stream = new FileStream(PersistFile, FileMode.Open, FileAccess.Read, FileShare.None))
                    using (BinaryReader reader = new BinaryReader(stream)) {
                        int length = reader.ReadInt32( );
                        cipher = reader.ReadBytes(length);
                    }

                DPAPI dpapi = new DPAPI( );
                dpapi.Entropy = GetEntropy( );

                try {
                    byte[] data = dpapi.Decrypt(cipher);

                    using (MemoryStream stream = new MemoryStream(data))
                        using (BinaryReader reader = new BinaryReader(stream)) {
                            Username = reader.ReadString( );
                            Password = reader.ReadString( );
                        }
                } catch (Exception) {
                    return(false);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
All Usage Examples Of DroidExplorer.Bootstrapper.Authentication.DPAPI::Decrypt