1

I'm trying to encrypt a file using OpenPGP in python via the pycrypto application. I've been following the sample provided in their code here: https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Cipher/CAST.py

So I'm using mode.openPGP, but I can't seem to encrypt anything using a public key. My public key is well over the 16byte limit they specify (and any generation I've seen is over this limit as well). Is there a different value I'm supposed to use here, like the fingerprint ID?

I'm trying to read the contents of a file, encrypt it with a key, then print it into a new file to be sent (both will be deleted later on). My code is as follows:

iv = CryptoRandom.new().read(CAST.block_size)
cipher = CAST.new(public_key, CAST.MODE_OPENPGP, iv)
file = open(filename)
contents = ''.join(file.readlines())
encrypted_contents = cipher.encrypt(contents)
encrypted_filename = filename.replace('/tmp/', '/tmp/encrypted')
encrypted_filename = encrypted_filename.replace('.csv', '.asc')
encrypted_file = open(encrypted_filename, 'w')
encrypted_file.write(encrypted_contents)
return encrypted_filename
Jens Erat
  • 37,523
  • 16
  • 80
  • 96

1 Answers1

0

I think you may be misunderstanding the algorithm you're using here. CAST is a symmetric-key algorithm, but whilst this implementation has an "OpenPGP mode", that doesn't mean that you simply pass your public key to it.

You should be generating a unique 16 byte key and passing that to CAST.new(). You would then generally encrypt that randomly-generated key using the public-key, and store/transmit the cipher text, and encrypted random-key together. The decryption process would decrypt the random-key using the private-key, then use the decrypted random-key to decrypt the cipher text.

Iridium
  • 23,323
  • 6
  • 52
  • 74
  • Ahh that makes sense, but how do I encrypt something with the public-key then, I'll run into the same error. I'm currently trying to use an RSA generated PGP key, and using the RSA public key file in pycrypto to load it but it keeps telling me it's "Not a DER structure" when importing the key. I'm really lost here I think... – user1686149 Oct 10 '13 at 17:26
  • @user1686149 I would suggest asking a separate question regarding the RSA encryption problems you're having, being sure to post the code you're using. – Iridium Oct 10 '13 at 19:40