I need to write a python code that installs a certificate into my machine's (windows) or local user's trusted root certificates. I tried the below code. The code runs without error but looks like the store is not windows trusted root. I also read the documentation of wincert and win32crypt python module, nothing seems to do the job.
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')
Edit : I need to do something similar mentioned here but using python.
Edit 2 : I also tried the below method (not sure if it will do the intended job):
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')
but I get the below error :
win32crypt.CertAddSerializedElementToStore(store,cert_byte,1,2,0)
pywintypes.error: (-2146885629, 'CertAddSerializedElementToStore', 'An error occurred while reading or writing to a file.')
This piece of code worked for me. Posting it here just in case it helps someone.
#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)
FYI, win32crypt module is available with pywin32 library. You can install it by running this command.
pip install pywin32
User contributions licensed under CC BY-SA 3.0