Created
November 8, 2019 19:48
-
-
Save tresf/d3ba760c822a62335bb2c180aa22bee7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean add(File certFile) { | |
log.info("Writing certificate {} to {} store using Crypt32...", certFile, certType); | |
try { | |
PEMParser pem = new PEMParser(new FileReader(certFile)); | |
X509CertificateHolder certHolder = (X509CertificateHolder)pem.readObject(); | |
byte[] bytes = certHolder.getEncoded(); | |
Pointer pointer = new Memory(bytes.length); | |
pointer.write(0, bytes, 0, bytes.length); | |
WinCrypt.HCERTSTORE certStore = openStore(certType); | |
boolean success = Crypt32.INSTANCE.CertAddEncodedCertificateToStore( | |
certStore, | |
WinCrypt.X509_ASN_ENCODING, | |
pointer, | |
bytes.length, | |
Crypt32.CERT_STORE_ADD_REPLACE_EXISTING, | |
null | |
); | |
log.info(Kernel32Util.formatMessage(Native.getLastError())); | |
closeStore(certStore); | |
return success; | |
} catch(IOException e) { | |
log.warn("An error occurred installing the certificate", e); | |
} | |
return false; | |
} | |
private static WinCrypt.HCERTSTORE openStore(Installer.PrivilegeLevel certType) { | |
log.info("Opening {} store using Crypt32...", certType); | |
WinCrypt.HCERTSTORE store = Crypt32.INSTANCE.CertOpenStore( | |
Crypt32.CERT_STORE_PROV_SYSTEM, | |
0, | |
null, | |
certType == Installer.PrivilegeLevel.USER ? Crypt32.CERT_SYSTEM_STORE_CURRENT_USER : Crypt32.CERT_SYSTEM_STORE_LOCAL_MACHINE, | |
"ROOT" | |
); | |
log.info(Kernel32Util.formatMessage(Native.getLastError())); | |
return store; | |
} | |
private static boolean closeStore(WinCrypt.HCERTSTORE certStore) { | |
boolean isClosed = Crypt32.INSTANCE.CertCloseStore( | |
certStore, 0 | |
); | |
log.info(Kernel32Util.formatMessage(Native.getLastError())); | |
return isClosed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment