def _open_for_signing(infile_path, signer_cert=None, signer_key=None): from pyhanko.pdf_utils import crypt infile = open(infile_path, 'rb') writer = IncrementalPdfFileWriter(infile) # TODO make this an option higher up the tree # TODO mention filename in prompt if writer.prev.encrypted: sh = writer.prev.security_handler if isinstance(sh, crypt.StandardSecurityHandler): pdf_pass = getpass.getpass( prompt='Password for encrypted file \'%s\': ' % infile_path) writer.encrypt(pdf_pass) elif isinstance(sh, crypt.PubKeySecurityHandler) \ and signer_key is not None: # attempt to decrypt using signer's credentials cred = SimpleEnvelopeKeyDecrypter(signer_cert, signer_key) logger.warning( "The file \'%s\' appears to be encrypted using public-key " "encryption. This is only partially supported in pyHanko's " "CLI. PyHanko will attempt to decrypt the document using the " "signer's public key, but be aware that using the same key " "for both signing and decryption is considered bad practice. " "Never use the same RSA key that you use to decrypt messages to" "sign hashes that you didn't compute yourself!" % infile_path) writer.encrypt_pubkey(cred) else: raise click.ClickException( "Input file appears to be encrypted, but appropriate " "credentials are not available.") return writer
def test_sign_crypt_pubkey_rc4(): w = IncrementalPdfFileWriter(BytesIO(MINIMAL_PUBKEY_ONE_FIELD_RC4)) w.encrypt_pubkey(PUBKEY_SELFSIGNED_DECRYPTER) out = signers.sign_pdf(w, signers.PdfSignatureMetadata(), signer=FROM_CA, existing_fields_only=True) r = PdfFileReader(out) r.decrypt_pubkey(PUBKEY_SELFSIGNED_DECRYPTER) s = r.embedded_signatures[0] val_trusted(s)