OpenSSL代码本机工作,但由于DLL导致OPENSSL_Uplink:无OPENSSL_Applink

问题描述 投票:2回答:1

这几乎无法得到任何答案,但是还是让我们尝试一下。而且我可能只是做了一些非常基本的事情而已...但是无论如何:

我必须使用一些OpenSSL函数来通过PHP对AES / RSA进行加密/解密(只是告诉您,以便您知道一些省时的方法,就可以知道...)。由于OpenSSL.NET首先无法与Mono配合使用,其次它不再受到支持,因此我不得不将我需要的功能直接从C OpenSSL移植到DLL,然后从C#调用这些功能,痛苦本身。

您可能会注意到,加密/解密功能直接被盗的AHEM,取自the 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):没有OPENSSL_Applink,并且在我尝试编写解密的文本时将其抛出。

根据documentation of the website,如果您忘记在代码中包含applink.c,但是如您所见,它位于.h文件中,就会发生这种情况。

所以我应该如何摆脱它?包含applink.c无效。

如果您能让我摆脱这个永恒的地狱,我会把我的灵魂卖给您。

问候

c# c++ dll mono openssl
1个回答
0
投票

只需将applink.c包含在main.c中,请勿将其包含在任何其他文件中!

© www.soinside.com 2019 - 2024. All rights reserved.