You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python调用DLL中的解密函数实现RSA加密功能?

解决Python调用C#托管DLL中Decrypt方法的问题

问题根源

你遇到的function 'EncryptDecrypt' not found错误,核心原因是Security.dll是C#编写的.NET托管程序集,而非原生Win32 DLL。ctypes仅能调用原生C/C++编译的DLL,无法直接识别托管DLL中的类和方法;dumpbin看不到目标函数,也是因为托管DLL的导出表仅包含.NET运行时所需的入口,不会直接导出类的成员方法。

解决方案:使用pythonnet调用托管DLL

pythonnet是专门用于Python与.NET程序集交互的库,可直接加载C# DLL并调用其中的类和方法,步骤如下:

1. 安装pythonnet

通过pip安装(注意匹配你的Python版本与.NET框架版本):

pip install pythonnet

2. 修正后的Python代码

以下代码完整对应你C#中的公钥读取+解密流程:

import clr
import zipfile
import os

def decrypt_public_key(encrypted_key):
    try:
        # 添加DLL所在目录到加载路径
        dll_dir = r"D:\"
        if dll_dir not in clr.AddReferencePaths:
            clr.AddReferencePaths(dll_dir)
        
        # 加载Security.dll并导入目标类
        clr.AddReference("Security")
        from Security import EncryptDecrypt

        # 调用Decrypt方法
        return EncryptDecrypt.Decrypt(encrypted_key)

    except Exception as ex:
        print(f"解密过程出错: {str(ex)}")
        return ""

def get_pass_public_key():
    file_password = "abcdef"
    file_path = r"D:\PublicKey.zip"
    public_key = ""
    try:
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            zip_ref.setpassword(file_password.encode('utf-8'))
            # 读取压缩包内第一个文件的内容
            with zip_ref.open(zip_ref.namelist()[0]) as stream:
                encrypted_key = stream.read().decode('utf-8')
                public_key = decrypt_public_key(encrypted_key)
    except Exception as ex:
        print(f"读取公钥文件出错: {str(ex)}")
        public_key = ""
    return public_key

# 测试调用
if __name__ == "__main__":
    decrypted_key = get_pass_public_key()
    print(f"解密后的公钥: {decrypted_key}")

关键注意事项

  • .NET版本兼容:确保pythonnet支持Security.dll依赖的.NET框架版本(如.NET Framework 4.x),版本不匹配会导致加载失败。
  • 依赖DLL路径:如果Security.dll依赖其他DLL,需确保所有依赖文件在可加载路径下(如与脚本同目录,或添加到系统PATH)。
  • 编码处理:pythonnet会自动处理Python字符串与.NET UTF-16字符串的编码转换,无需手动转字节。

内容的提问来源于stack exchange,提问作者liverpoolsunil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:23:12