使用 Python 从 DLL 访问函数

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

我有一个用 C# 编写的 RSA 加密程序。其工作原理如下:

  1. 使用 DLL 解密公钥
  2. 使用公钥使用自定义加密函数加密数据

此加密数据随后被传递到 API,该 API 将文件作为表单数据返回。

我想通过Python实现相同的功能。

但是我陷入了需要从 DLL 文件访问用于解密数据的函数的步骤。

这是用于解密公钥的 C# 代码:

public string GetPassPublicKey(string mode)
    {
        string PublicKey = "";
        string FilePassword = "abcdef";
        string FilePath = "D:\PublicKey.zip";
try
        {
            if (FilePassword != "" && FilePath != "")
            {
                using (FileStream zipFile = File.Open(FilePath, FileMode.Open))
                {
                    using (Archive archive = new Archive(zipFile, new ArchiveLoadOptions() { DecryptionPassword = FilePassword }))
                    {
                        using (var stream = archive.Entries[0].Open())
                        using (var reader = new StreamReader(stream))
                        {
                            PublicKey = reader.ReadToEnd();
                            PublicKey = Security.EncryptDecrypt.Decrypt(PublicKey);
                        }
                    }
                }
            }
            else
            {

            }
        }
        catch (Exception ex)
        {
            PublicKey = "";
        }
        return PublicKey;

我尝试使用Python如下:

def decrypt_public_key(encrypted_key):
    try:
        # Load the Security.dll
        security_dll = ctypes.WinDLL(r"D:\Security.dll")

        # Define the function signature for Decrypt
        security_dll.EncryptDecrypt_Decrypt = security_dll.EncryptDecrypt.Decrypt()
        security_dll.EncryptDecrypt_Decrypt.argtypes = [ctypes.c_char_p]
        security_dll.EncryptDecrypt_Decrypt.restype = ctypes.c_char_p

        def decrypt(content):
            # Call Decrypt with the input string
            decrypted_key = security_dll.EncryptDecrypt_Decrypt(content.encode('utf-8'))
            return decrypted_key.decode('utf-8')

        return decrypt(encrypted_key)  # Call the decrypt function here

    except Exception as ex:
        print(f"An error occurred during decryption: {str(ex)}")
        return ""

但我得到的只是

An error occurred during decryption: function 'EncryptDecrypt' not found

我尝试使用 dumpbin 来理解 DLL 中的函数,但没有成功,并且在 C# 代码中使用此 DLL 的团队没有相关文档。

python c# encryption dll rsa
1个回答
0
投票

谢谢你@JonasH

我能够使用 pythonnet 解决这个问题。

这是我使用的代码片段:

import clr
clr.AddReference(r"D:\Security.dll")
from Security import EncryptDecrypt

def decrypt_public_key(encrypted_key):
    try:
                
        def decrypt(content):
            # Call Decrypt with the input string
            content_string = content.decode('utf-8')
            instance = EncryptDecrypt()
            decrypted_key = instance.Decrypt(content_string)
            return decrypted_key

        return decrypt(encrypted_key)  # Call the decrypt function here

    except Exception as ex:
        print(f"An error occurred during decryption: {str(ex)}")
        return ""
© www.soinside.com 2019 - 2024. All rights reserved.