OpenSSL代码本机工作,但作为DLL导致OPENSSL_Uplink:没有OPENSSL_Applink

本文关键字:OPENSSL 导致 Uplink Applink 没有 DLL 码本机 代码 工作 OpenSSL | 更新日期: 2023-09-27 18:02:27

这很难得到任何答案,但我们还是试试吧。而且我可能只是做错了一些非常基本的事情…总之:

我必须使用一些OpenSSL函数的AES/RSA加密/解密与PHP(只是告诉这个,所以如果你知道一些节省头的选择,你知道…)与Mono。因为OpenSSL。. NET首先不能与Mono一起工作,其次它不再得到支持,我被迫将我需要的函数直接从C OpenSSL移植到DLL中,并从c#调用这些函数,这本身就是一种痛苦。

你可能会注意到,加密/解密函数是直接从wiki中窃取的。

.h文件是:

#pragma once
#include <comdef.h>
#include <comutil.h>
#include <tchar.h>
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/applink.c>
#define EXPORT __declspec(dllexport)
namespace OpenSSL
{
    extern "C" { EXPORT int NumericTest(int a, int b); }
    extern "C" { EXPORT BSTR StringTest(); }
    extern "C" { EXPORT BSTR StringTestReturn(char *toReturn); }
    extern "C" { EXPORT int Encrypt_AES_256_CBC(unsigned char *plaintext,
                                                int plaintext_len,
                                                unsigned char *key,
                                                unsigned char *iv,
                                                unsigned char *ciphertext); }
    extern "C" { EXPORT int Decrypt_AES_256_CBC(unsigned char *ciphertext,
                                                int ciphertext_len,
                                                unsigned char *key,
                                                unsigned char *iv,
                                                unsigned char *plaintext); }
    extern "C" { EXPORT void HandleErrors(); }
}

.cpp文件是:

#include "OpenSSL.h"
namespace OpenSSL
{
    void HandleErrors()
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    void InitOpenSSL()
    {
        ERR_load_crypto_strings();
        OpenSSL_add_all_algorithms();
        OPENSSL_config(NULL);
    }
    int NumericTest(int a, int b)
    {
        return a + b;
    }
    BSTR StringTest()
    {
        return ::SysAllocString(L"StringTest successful!");
    }
    BSTR StringTestReturn(char *toReturn)
    {
        _bstr_t bstrt(toReturn);
        bstrt += " (StringTestReturn)";
        strcpy_s(toReturn, 256, "StringTestReturn");
        return bstrt;
    }
    int Encrypt_AES_256_CBC(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext)
    {
        InitOpenSSL();
        EVP_CIPHER_CTX *ctx;
        int len;
        int ciphertext_len;
        /* Create and initialise the context */
        if (!(ctx = EVP_CIPHER_CTX_new())) HandleErrors();
        /* Initialise the encryption operation. IMPORTANT - ensure you use a key
        * and IV size appropriate for your cipher
        * In this example we are using 256 bit AES (i.e. a 256 bit key). The
        * IV size for *most* modes is the same as the block size. For AES this
        * is 128 bits */
        if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
            HandleErrors();
        /* Provide the message to be encrypted, and obtain the encrypted output.
        * EVP_EncryptUpdate can be called multiple times if necessary
        */
        if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
            HandleErrors();
        ciphertext_len = len;
        /* Finalise the encryption. Further ciphertext bytes may be written at
        * this stage.
        */
        if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) HandleErrors();
        ciphertext_len += len;
        /* Clean up */
        EVP_CIPHER_CTX_free(ctx);
        return ciphertext_len;
    }
    int Decrypt_AES_256_CBC(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
                unsigned char *iv, unsigned char *plaintext)
    {
        InitOpenSSL();
        EVP_CIPHER_CTX *ctx;
        int len;
        int plaintext_len;
        /* Create and initialise the context */
        if (!(ctx = EVP_CIPHER_CTX_new())) HandleErrors();
        /* Initialise the decryption operation. IMPORTANT - ensure you use a key
        * and IV size appropriate for your cipher
        * In this example we are using 256 bit AES (i.e. a 256 bit key). The
        * IV size for *most* modes is the same as the block size. For AES this
        * is 128 bits */
        if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
            HandleErrors();
        /* Provide the message to be decrypted, and obtain the plaintext output.
        * EVP_DecryptUpdate can be called multiple times if necessary
        */
        if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
            HandleErrors();
        plaintext_len = len;
        /* Finalise the decryption. Further plaintext bytes may be written at
        * this stage.
        */
        if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) HandleErrors();
        plaintext_len += len;
        /* Clean up */
        EVP_CIPHER_CTX_free(ctx);
        return plaintext_len;
    }
}

注意这些函数是如何测试的,并且在c++控制台应用程序上运行得很好

最后但并非最不重要的,我一直用于测试目的的c#代码:

using System;
using System.Text;
using System.Runtime.InteropServices;

namespace OpenSSLTests
{
    [StructLayout(LayoutKind.Sequential)]
    class OpenSSL
    {
        const string OPENSSL_PATH = "(here i putted my dll file path (of course in the program i putted the real path, but not here))";
        [DllImport(OPENSSL_PATH, CallingConvention = CallingConvention.Cdecl)]
        public static extern int NumericTest(int a, int b);
        [DllImport(OPENSSL_PATH, CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.BStr)]
        public static extern string StringTest();
        [DllImport(OPENSSL_PATH, EntryPoint = "StringTestReturn", CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.BStr)]
        public static extern string StringTestReturn(StringBuilder toReturn);
        [DllImport(OPENSSL_PATH, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Encrypt_AES_256_CBC(StringBuilder plainText,
                                                    int plaintext_len,
                                                    StringBuilder key,
                                                    StringBuilder iv,
                                                    StringBuilder ciphertext);
        [DllImport(OPENSSL_PATH, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Decrypt_AES_256_CBC(StringBuilder cipherText,
                                                    int ciphertext_len,
                                                    StringBuilder key,
                                                    StringBuilder iv,
                                                    StringBuilder plaintext);
        static void Main(string[] args)
        {
            Console.WriteLine("the numeric test result is: " + NumericTest(1, 2));
            Console.WriteLine();
            Console.WriteLine("the string test result is: " + StringTest());
            Console.WriteLine();
            StringBuilder test = new StringBuilder(256);
            test.Append("test");
            Console.WriteLine("test is: " + test);
            Console.WriteLine();


            Console.WriteLine("Calling StringTestReturn...");
            string newTest = StringTestReturn(test);
            Console.WriteLine("test is now: " + test);
            Console.WriteLine("newTest is: " + newTest);
            Console.WriteLine();
            StringBuilder plainText = new StringBuilder(1024);
            plainText.Append("this is a really crashy test plz halp");
            StringBuilder key = new StringBuilder(1024);
            StringBuilder IV = new StringBuilder(1024);
            key.Append("randomkey12345asdafsEWFAWEFAERGERUGHERUIGHAEIRUGHOAEGHSD");
            IV.Append("ivtoUse1248235fdghapeorughèaerjèaeribyvgnèaervgjer0vriono");
            StringBuilder ciphredText = new StringBuilder(1024);
            int plainTextLength = Encrypt_AES_256_CBC(plainText, plainText.Length, key, IV, ciphredText);
            if (plainTextLength != -1)
            {
                Console.WriteLine("encrypted text length: " + plainTextLength);
                Console.WriteLine("the encrypted text content is: " + ciphredText);
            }
            else
            {
                Console.WriteLine("error encrypting'n");
            }
            StringBuilder decryptedText = new StringBuilder(1024);
            int decryptedTextLength = -1;
            try
            {
                decryptedTextLength = Decrypt_AES_256_CBC(ciphredText, ciphredText.Length, key, IV, decryptedText);
            }
            catch (Exception e)
            {
                Console.WriteLine("error during decryption");
            }
            if (decryptedTextLength != -1)
            {
                decryptedText[decryptedTextLength] = ''0';
                Console.WriteLine("decrypted text length: " + decryptedTextLength);
                try
                {
                    //here it crashes without even giving you the courtesy of printing anything. It just closes
                    Console.WriteLine("decrypted text is:     " + decryptedText);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            else
            {
                Console.WriteLine("error after decryption");
            }

            Console.ReadLine();
        }
    }
}

如你所料,它不应该工作。不是。或者更好:它不工作,但奇怪的是它不工作的方式:不像我写过或听过的任何其他程序,当程序运行Visual Studio只是打开一个控制台窗口,但只是暂时的,然后它自己关闭,甚至没有抛出一个错误。你知道,就像你学习c#,写hello world,但忘记在末尾添加console。readline()或者在c++中添加system("PAUSE"),所以它会在一秒钟内关闭?

然而,如果我通过按ctrl+F5运行它,我得到控制台,输出将是:

the numeric test result is: 3
the string test result is: StringTest successful!
test is: test
Calling StringTestReturn...
test is now: StringTestReturn
newTest is: test (StringTestReturn)
encrypted text length: 48
the encrypted text content is: 9ïÅèSðdC1¦æÌ?
OPENSSL_Uplink(00007FFFFB388000,08): no OPENSSL_Applink
Premere un tasto per continuare . . . (press a key to finish in italian)

所以错误应该是OPENSSL_Uplink(00007ffffb388000,08): no OPENSSL_Applink,当我试图写解密文本时,它会抛出它。

根据网站的文档,如果你忘记在代码中包含applink.c,就会发生这种情况,但正如你所看到的,它就在。h文件中。

那么我该如何摆脱它呢?包括applink.c不能工作

如果你能把我从这永恒的地狱里救出来,我就把灵魂卖给你。

问候。

OpenSSL代码本机工作,但作为DLL导致OPENSSL_Uplink:没有OPENSSL_Applink

只要将applink.c包含在main.c中,不要将其包含在任何其他文件中!