def load_key(key_str, key_pass): """ Function to load password protected key file in p12 or pem format""" try: # First try to parse as a p12 file key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass) except ValueError as e: # If it fails due to invalid password raise error here if e.args[0] == 'Password provided is invalid': raise AS2Exception('Password not valid for Private Key.') # if not try to parse as a pem file key, cert = None, None for kc in split_pem(key_str): try: cert = asymmetric.load_certificate(kc) except (ValueError, TypeError): try: key = asymmetric.load_private_key(kc, key_pass) except OSError: raise AS2Exception( 'Invalid Private Key or password is not correct.') if not key or not cert: raise AS2Exception( 'Invalid Private key file or Public key not included.') return key, cert
def frompfx(cls, responder_pkcs12: StrOrBytes, pkcs12_password: StrOrBytes, validate_func: ValidateFunc, cert_retrieve_func: CertRetrieveFunc = None, next_update_days: int = 7): """ Create a new OCSPResponder instance from a pkcs12 filepath or bytes. :param responder_pfx: Path to or Bytes of the pfx / pkcs12 that also contains the issuer cert. :param validate_func: A function that - given a certificate serial - will return the appropriate :class:`CertificateStatus` and - depending on the status - a revocation datetime. :param cert_retrieve_func: A function that - given a certificate serial - will return the corresponding certificate as a string. :param next_update_days: The ``nextUpdate`` value that will be written into the response. Default: 7 days. """ # Certs and keys _responder_key, _responder_cert, chain_certs = asymmetric.load_pkcs12(responder_pkcs12, pkcs12_password) _issuer_cert = None for cert in chain_certs: if cert.asn1.subject == _responder_cert.asn1.issuer: _issuer_cert = cert break return cls(_issuer_cert, _responder_cert, _responder_key, validate_func=validate_func, cert_retrieve_func=cert_retrieve_func, next_update_days=next_update_days)
def main(): dct = { b'sigflags': 3, b'contact': b'*****@*****.**', b'location': b'City', b'signingdate': b'20180731082642+02\'00\'', b'reason': b'Some descriptive message', } p12 = asymmetric.load_pkcs12( open('CubikaChatbot-2019-06-10-210225.p12', 'rb').read(), 'password') datau = open('1.pdf', 'rb').read() datas = pdf.cms.sign(datau, dct, p12[0], p12[1], [], 'sha256') with open('pdf-signed-cms.pdf', 'wb') as fp: fp.write(datau) fp.write(datas)