Example #1
0
        public static bool kull_m_crypto_genericAES128Decrypt(IntPtr pKey, IntPtr pIV, IntPtr pData, uint dwDataLen, ref IntPtr pOut, ref uint dwOutLen)
        {
            bool   status = false;
            IntPtr hProv  = IntPtr.Zero;
            IntPtr hKey   = IntPtr.Zero;
            uint   mode   = CRYPT_MODE_CBC;

            byte[]   bytes       = BitConverter.GetBytes(mode);
            GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            IntPtr   pMode       = pinnedArray.AddrOfPinnedObject();

            if (Natives.CryptAcquireContextA(ref hProv, null, null, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
            {
                if (kull_m_crypto_hkey(hProv, CALG_AES_128, pKey, 16, 0, ref hKey, IntPtr.Zero))
                {
                    if (Natives.CryptSetKeyParam(hKey, KP_MODE, pMode, 0))
                    {
                        if (Natives.CryptSetKeyParam(hKey, KP_IV, pIV, 0))
                        {
                            pOut = Marshal.AllocHGlobal((int)dwDataLen);
                            if (pOut != IntPtr.Zero)
                            {
                                dwOutLen = dwDataLen;
                                byte[] buffer = new byte[(int)dwDataLen];
                                Marshal.Copy(pData, buffer, 0, (int)dwDataLen);
                                Marshal.Copy(buffer, 0, pOut, (int)dwDataLen);
                                //GCHandle pinnedArrayOut = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                                //pOut = pinnedArray.AddrOfPinnedObject();
                                if (!(status = Natives.CryptDecrypt(hKey, IntPtr.Zero, true, 0, pOut, ref dwOutLen)))
                                {
                                    Console.WriteLine("CryptDecrypt " + Marshal.GetLastWin32Error());
                                    //Marshal.FreeHGlobal(pOut);
                                    dwOutLen = 0;
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("CryptSetKeyParam (IV)");
                        }
                    }
                    else
                    {
                        Console.WriteLine("CryptSetKeyParam (MODE)");
                    }
                    Natives.CryptDestroyKey(hKey);
                }
                else
                {
                    Console.WriteLine("kull_m_crypto_hkey");
                }
                Natives.CryptReleaseContext(hProv, 0);
            }
            else
            {
                Console.WriteLine("CryptAcquireContext");
            }
            return(status);
        }