您好,我正在尝试在C++和C#之间进行加密和解密,并使用CryptEncrypt wincrypt创建了一个dll项目,这里我使用了代码
C++

#include <Windows.h>
#include <stdio.h>
extern "C" __declspec(dllexport)

BOOL EncryptData(char* szData, char* szPassword, char* szErroror, BYTE* pData, BYTE* pDataLen, BOOL Encrypt)
{
    HANDLE hSourceFile = INVALID_HANDLE_VALUE;
    HANDLE hDestinationFile = INVALID_HANDLE_VALUE;

    HCRYPTPROV hProv = NULL;
    HCRYPTKEY hKey = NULL;
    HCRYPTKEY hXchgKey = NULL;
    HCRYPTHASH hHash = NULL;

    PBYTE pbKeyBlob = NULL;
    DWORD dwKeyBlobLen;

    PBYTE pbBuffer = NULL;
    DWORD dwBlockLen = 0;
    DWORD dwBufferLen = 0;
    DWORD dwCount = 0;
    bool bRet = true;

    int len = strlen(szData);

    if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0))
    {
        if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
            return false;
    }

    // Create a hash object.
    if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
        return false;

    // Hash in the password data.
    if (!CryptHashData(hHash, (BYTE*)szPassword, strlen(szPassword), 0))
        return false;

    // Derive a session key from the hash object.
    if (!CryptDeriveKey(hProv, CALG_RC4, hHash, 0x00800000, &hKey))
        return false;

    dwBlockLen = 1000 - 1000 % 8;

    // Allocate memory.
    if ((pbBuffer = (BYTE*)malloc(dwBufferLen)) == NULL)
        return false;

    if (Encrypt)
    {
        if (!CryptEncrypt(hKey, 0, false, 0, pbBuffer, &dwCount, dwBufferLen))
        {
            DWORD  dwError = GetLastError();
            strcpy(szErroror, "CryptEncrypt Failed Error ");
            char szError[10];
            memset(szError, 0, 10);
            sprintf(szError, "%d", dwError);
            strcat(szErroror, szError);
            bRet = false;
        }
    }
    else
    {
        if (!CryptDecrypt(hKey, 0, false, 0, pbBuffer, &dwCount))
        {
            DWORD  dwError = GetLastError();
            strcpy(szErroror, "CryptDecrypt Failed Error ");
            char szError[10];
            memset(szError, 0, 10);
            sprintf(szError, "%d", dwError);
            strcat(szErroror, szError);
            bRet = false;
        }
    }

    char szDataLen[16];
    memset(szDataLen, 0, 16);
    sprintf(szDataLen, "%d", dwCount);
    memcpy(pDataLen, szDataLen, 16);

    BYTE* pMyData = (BYTE*)malloc(len);

    memset(pMyData, 0, len);
    memcpy(pData, pbBuffer, len);

    // Free memory.
    if (pbKeyBlob) free(pbKeyBlob);
    if (pbBuffer) free(pbBuffer);
    if (pMyData) free(pMyData);

    // Destroy session key.
    if (hKey) CryptDestroyKey(hKey);

    // Release key exchange key handle.
    if (hXchgKey) CryptDestroyKey(hXchgKey);

    // Destroy hash object.
    if (hHash) CryptDestroyHash(hHash);

    // Release provider handle.
    if (hProv) CryptReleaseContext(hProv, 0);

    return bRet;
}


和C#项目调用dll和函数
namespace ConsoleApp1
{
    class Program
    {
        [DllImport("Project3.dll", CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EncryptData(byte[] szData, char[] szPassword, StringBuilder sbError, byte[] pData, byte[] pDataLen, bool Encrypt);

        static void Main(string[] args)
        {

            StringBuilder sbError = new StringBuilder(255);
            byte[] szData = Encoding.ASCII.GetBytes("datatest");
            char[] szPassword = ("test").ToCharArray();
            byte[] pData = new byte[1008];
            byte[] pDataLen = new byte[16];
            Console.WriteLine("Encrypt");
            bool bRet = EncryptData(szData, szPassword, sbError, pData, pDataLen, true);

            Console.WriteLine(Encoding.ASCII.GetString(pData));

            Console.WriteLine("Decrypt");
            bool bRet2 = EncryptData(szData, szPassword, sbError, pData, pDataLen, false);
            Console.WriteLine(Encoding.ASCII.GetString(pData));

            Console.ReadKey();

        }
    }
}

但是我对解密有问题





如您所见,解密是错误的,可能是错误的

最佳答案

首先,您的C / C++代码使用了不推荐使用的Windows函数,其次,使用了许多“不安全的” C运行时函数,例如:“strcpy”,“strcat”,“sprintf”等,其次,并非所有代码都是防止缓冲区编码错误。如果没有重大更正,则C代码不能在任何最新的Visual Studio编译器中编译。

请尝试修复所有错误,简化代码,然后再次发布。

在C#端,传递给C代码的数据缓冲区没有固定,可以随时由GC移动。由于其体积小,GC可能会将它们从Gen 0急切提升到Gen 1,这将导致内存移动操作和指向缓冲区的指针无效。简单地说,指向所有缓冲区的指针在被C代码读取时可能是无效的。

在C#端,您可以执行以下操作:

    [DllImport("Project3.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static unsafe extern bool EncryptData(
        byte* szData, char* szPassword, StringBuilder sbError, byte* pData, byte* pDataLen, bool Encrypt);

    static unsafe void Main(string[] args)
    {
        StringBuilder sbError = new StringBuilder(255);
        byte[] szDataBuff = Encoding.ASCII.GetBytes("datatest");
        char[] szPasswordBuff = ("test").ToCharArray();
        byte[] pDataBuff = new byte[1008];
        byte[] pDataLenBuff = new byte[16];

        fixed (byte* szData = szDataBuff)
        fixed (char* szPassword = szPasswordBuff)
        fixed (byte* pData = pDataBuff)
        fixed (byte* pDataLen = pDataLenBuff)
        {
            Console.WriteLine("Encrypt");
            bool bRet = EncryptData(szData, szPassword, sbError, pData, pDataLen, true);

            Console.WriteLine("Encrypted: {0}", bRet);
            Console.WriteLine(Marshal.PtrToStringAnsi((IntPtr)pData));

            Console.WriteLine("Decrypt");
            bool bRet2 = EncryptData(szData, szPassword, sbError, pData, pDataLen, false);
            Console.WriteLine("Derypted: {0}", bRet2);
            Console.WriteLine(Marshal.PtrToStringAnsi((IntPtr)pData));
        }

        Console.ReadKey();
    }

还有其他可能的方法,但这似乎是最直接和最简单的方法。

10-07 22:03