如何使用 python 将证书安装到受信任的根证书?

How do I install a certificate to trusted root certificates using python?

我需要编写一个 python 代码来将证书安装到我的机器 (windows) 或本地用户的受信任根证书中。我试过下面的代码。代码运行没有错误,但看起来商店不是 windows 受信任的根。我还阅读了 wincertwin32crypt python 模块的文档,似乎没有任何作用。

import OpenSSL.crypto

cert = OpenSSL.crypto.load_certificate(
    OpenSSL.crypto.FILETYPE_PEM, 
    open('certFile.crt').read()
)

store = OpenSSL.crypto.X509Store()
if not store.add_cert(cert):
    print('Success')

编辑:我需要做类似提到的事情 here 但使用 python.

编辑 2:我也尝试了以下方法(不确定它是否会完成预期的工作):

import win32crypt
import sys

CERT_STORE_PROV_SYSTEM = 0x0000000A
CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000
CRYPT_STRING_BASE64HEADER = 0x00000000

def main():

    store = win32crypt.CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, None, CERT_SYSTEM_STORE_LOCAL_MACHINE|CERT_STORE_OPEN_EXISTING_FLAG, "ROOT")
    cert_str = open('D:\Certificates\certFile.crt').read()
    cert_byte = win32crypt.CryptStringToBinary(cert_str, CRYPT_STRING_BASE64HEADER)[0]
    win32crypt.CertAddSerializedElementToStore(store,cert_byte,1,2,0)

if __name__ == "__main__":

    main()
    print('done')

但我收到以下错误:

win32crypt.CertAddSerializedElementToStore(store,cert_byte,1,2,0)
pywintypes.error: (-2146885629, 'CertAddSerializedElementToStore', 'An error occurred while reading or writing to a file.')

这段代码对我有用。将它张贴在这里以防万一它对某人有帮助。

#Flag variables
CERT_STORE_PROV_SYSTEM = 0x0000000A
CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000
CRYPT_STRING_BASE64HEADER = 0x00000000
CERT_SYSTEM_STORE_CURRENT_USER_ACCOUNT = 1<<16
X509_ASN_ENCODING = 0x00000001
CERT_STORE_ADD_REPLACE_EXISTING = 3
CERT_CLOSE_STORE_FORCE_FLAG = 0x00000001

#replace with your certificate file path
crtPath = "D:\certificates\cert_file.crt"

with open(crtPath,'r') as f:
        cert_str = f.read()

cert_byte = win32crypt.CryptStringToBinary(cert_str, CRYPT_STRING_BASE64HEADER)[0]
store = win32crypt.CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, None, CERT_SYSTEM_STORE_CURRENT_USER_ACCOUNT|CERT_STORE_OPEN_EXISTING_FLAG, "ROOT")
    
try:
   store.CertAddEncodedCertificateToStore(X509_ASN_ENCODING, cert_byte, CERT_STORE_ADD_REPLACE_EXISTING)
finally:
    store.CertCloseStore(CERT_CLOSE_STORE_FORCE_FLAG)

仅供参考,win32crypt 模块可用于 pywin32 库。你可以通过运行这个命令安装它。

pip install pywin32