Exemplo n.º 1
0
        public static string encryptpw(string pw)
        {
            byte[]        pwba    = Encoding.Unicode.GetBytes(pw);
            dataBlob      dataIn  = new dataBlob();
            dataBlob      dataOut = new dataBlob();
            StringBuilder epwsb   = new StringBuilder();

            try
            {
                try
                {
                    InitBLOB(pwba, ref dataIn);
                }
                catch (Exception ex)
                {
                    throw new Exception("Cannot initialize dataIn BLOB.", ex);
                }

                bool success = CryptProtectData(
                    ref dataIn,
                    "psw",
                    nullPtr,
                    nullPtr,
                    nullPtr,
                    CryptprotectUiForbidden,
                    ref dataOut);

                if (!success)
                {
                    int errCode = Marshal.GetLastWin32Error();
                    throw new Exception("CryptProtectData failed.", new Win32Exception(errCode));
                }

                byte[] epwba = new byte[dataOut.cbData];
                Marshal.Copy(dataOut.pbData, epwba, 0, dataOut.cbData);
                // Convert hex data to hex characters (suitable for a string)
                for (int i = 0; i < dataOut.cbData; i++)
                {
                    epwsb.Append(Convert.ToString(epwba[i], 16).PadLeft(2, '0').ToUpper());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("unable to encrypt data.", ex);
            }
            finally
            {
                if (dataIn.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(dataIn.pbData);
                }

                if (dataOut.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(dataOut.pbData);
                }
            }
            return(epwsb.ToString());
        }
Exemplo n.º 2
0
 private static extern bool CryptProtectData(
     ref dataBlob pPlainText,
     [MarshalAs(UnmanagedType.LPWStr)] string szDescription,
     IntPtr pEntroy,
     IntPtr pReserved,
     IntPtr pPrompt,
     int dwFlags,
     ref dataBlob pCipherText);
Exemplo n.º 3
0
        private static void InitBLOB(byte[] data, ref dataBlob blob)
        {
            blob.pbData = Marshal.AllocHGlobal(data.Length);
            if (blob.pbData == IntPtr.Zero)
            {
                throw new Exception("Unable to allocate buffer for BLOB data.");
            }

            blob.cbData = data.Length;
            Marshal.Copy(data, 0, blob.pbData, data.Length);
        }