Module ezPyCrypto :: Class key
[show private | hide private]
[frames | no frames]

Class key


This may well be the only crypto class for Python that you'll ever need. Think of this class, and the ezPyCrypto module, as 'cryptography for the rest of us'.

Designed to strike the optimal balance between ease of use, features and performance.

Basic High-level methods: Middle-level (stream-oriented) methods: Low-level methods: Principle of operation:
Method Summary
  __init__(self, something, algoPub, algoSess, **kwds)
Constructor.
  decEnd(self)
Ends a stream decryption session.
  decNext(self, chunk)
Decrypt the next piece of incoming stream data.
  decStart(self)
Start a stream decryption session.
  decString(self, enc)
Decrypts a previously encrypted string.
  decStringFromAscii(self, enc)
Decrypts a previously encrypted string in ASCII (base64) format, as created by encryptAscii()
  encEnd(self)
Called to terminate a stream session.
  encNext(self, raw)
Encrypt the next piece of data in a stream.
  encStart(self)
Starts a stream encryption session Sets up internal buffers for accepting ad-hoc data.
  encString(self, raw)
Encrypt a string of data
  encStringToAscii(self, raw)
Encrypts a string of data to printable ASCII format
  exportKey(self)
Exports the public key as a printable string.
  exportKeyPrivate(self, **kwds)
Exports public/private key pair as a printable string.
  importKey(self, keystring, **kwds)
Imports a public key or private/public key pair.
  makeNewKeys(self, keysize, **kwds)
Creates a new keypair in cipher object, and a new session key
  signString(self, raw)
Sign a string using private key
  test(self, raw)
Encrypts, then decrypts a string.
  testAscii(self, raw)
Encrypts, then decrypts a string.
  verifyString(self, raw, signature)
Verifies a string against a signature.
  _calcPubBlkSize(self)
Determine size of public key
  _calcSesBlkSize(self)
Determine size of session blocks
  _decRawPub(self, enc)
Decrypt a public-key encrypted block, and return the decrypted string
  _encRawPub(self, raw)
Encrypt a small raw string using the public key algorithm.
  _genNewSessKey(self)
Generate a new random session key
  _initBlkCipher(self)
Create a new block cipher object, set up with a new session key and IV
  _padToPubBlkSize(self, raw)
padToPubBlkSize - pad a string to max size encryptable by public key
  _rawPubKey(self)
Returns a binary-encoded string of public key
  _testPubKey(self, k)
Checks if binary-encoded key matches this object's pubkey
  _unwrap(self, type, msg)
Unwraps a previously _wrap()'ed message.
  _wrap(self, type, msg)
Encodes message as base64 and wraps with <StartPyCryptoname>/<EndPycryptoname> Args:

Class Variable Summary
dict _algosPub
dict _algosPub1
dict _algosSes
dict _algosSes1
list _algosSes2
dict _algosSes3
str _encBuf
str _passIV

Method Details

__init__(self, something=512, algoPub=None, algoSess=None, **kwds)
(Constructor)

Constructor. Creates a key object

This constructor, when creating the key object, does one of two things:
  1. Creates a completely new keypair, OR
  2. Imports an existing keypair
Arguments:
  1. If new keys are desired:
    • key size in bits (int), default 512 - advise at least 1536
    • algoPub - either 'RSA' or 'ElGamal' (default 'RSA')
    • algoSess - one of 'ARC2', 'Blowfish', 'CAST', 'DES3', 'IDEA', 'RC5', (default 'Blowfish')
  2. If importing an existing key or keypair:
    • keyobj (string) - result of a prior exportKey() call
Keywords:
  • passphrase - default '':
    • If creating new keypair, this passphrase is used to encrypt privkey when exporting.
    • If importing a new keypair, the passphrase is used to authenticate and grant/deny access to private key

decEnd(self)

Ends a stream decryption session.

decNext(self, chunk)

Decrypt the next piece of incoming stream data.

Arguments:
  • chunk - some more of the encrypted stream
Returns (depending on state)
  • '' - no more decrypted data available just yet
  • data - the next available piece of decrypted data
  • None - session is complete - no more data available

decStart(self)

Start a stream decryption session.

Call this method first, then feed in pieces of stream data into decNext until there's no more data to decrypt

Arguments:
  • None
Returns:
  • None

decString(self, enc)

Decrypts a previously encrypted string.

Arguments:
  • enc - string, previously encrypted in binary mode with encString
Returns:
  • dec - raw decrypted string

decStringFromAscii(self, enc)

Decrypts a previously encrypted string in ASCII (base64) format, as created by encryptAscii()

Arguments:
  • enc - ascii-encrypted string, as previously encrypted with encStringToAscii()
Returns:
  • dec - decrypted string

May generate an exception if the public key of the encrypted string doesn't match the public/private keypair in this key object.

To work around this problem, either instantiate a key object with the saved keypair, or use the importKey() function.

Exception will also occur if this object is not holding a private key (which can happen if you import a key which was previously exported via exportKey(). If you get this problem, use exportKeyPrivate() instead to export your keypair.

encEnd(self)

Called to terminate a stream session. Encrypts any remaining data in buffer.

Arguments:
  • None
Returns - one of:
  • last block of data, as a string

encNext(self, raw='')

Encrypt the next piece of data in a stream.

Arguments:
  • raw - raw piece of data to encrypt
Returns - one of:
  • '' - not enough data to encrypt yet - stored for later
  • encdata - string of encrypted data

encStart(self)

Starts a stream encryption session Sets up internal buffers for accepting ad-hoc data.

No arguments needed, nothing returned.

encString(self, raw)

Encrypt a string of data

High-level func. encrypts an entire string of data, returning the encrypted string as binary.

Arguments:
  • raw string to encrypt
Returns:
  • encrypted string as binary
Note - the encrypted string can be stored in files, but I'd suggest not emailing them - use encStringToAscii instead. The sole advantage of this method is that it produces more compact data, and works a bit faster.

encStringToAscii(self, raw)

Encrypts a string of data to printable ASCII format

Use this method instead of encString, unless size and speed are major issues.

This method returns encrypted data in bracketed base64 format, safe for sending in email.

Arguments:
  • raw - string to encrypt
Returns:
  • enc - encrypted string, text-wrapped and Base-64 encoded, safe for mailing.
There's an overhead with base64-encoding. It costs size, bandwidth and speed. Unless you need ascii-safety, use encString() instead.

exportKey(self)

Exports the public key as a printable string.

Exported keys can be imported elsewhere into MyCipher instances with the importKey method.

Note that this object contains only the public key. If you want to export the private key as well, call exportKeyPrivate instaead.

Note also that the exported string is Base64-encoded, and safe for sending in email.

Arguments:
  • None
Returns:
  • a base64-encoded string containing an importable key

exportKeyPrivate(self, **kwds)

Exports public/private key pair as a printable string.

This string is a binary string consisting of a pickled key object, that can be imported elsewhere into MyCipher instances with the importKey method.

Note that this object contains the public AND PRIVATE keys. Don't EVER email any keys you export with this function (unless you know what you're doing, and you encrypt the exported keys against another key). When in doubt, use exportKey instead.

Keep your private keys safe at all times. You have been warned.

Note also that the exported string is Base64-encoded, and safe for sending in email.

Arguments:
  • None
Keywords:
  • passphrase - default (None) to using existing passphrase. Set to '' to export without passphrase (if this is really what you want to do!)
Returns:
  • a base64-encoded string containing an importable key

importKey(self, keystring, **kwds)

Imports a public key or private/public key pair.

(as previously exported from this object with the exportKey or exportKeyPrivate methods.)

Arguments: Keywords:
  • passphrase - string (default '', meaning 'try to import without passphrase')
Returns:
  • True if import successful, False if failed

You don't have to call this if you instantiate your key object in 'import' mode - ie, by calling it with a previously exported key.

Note - you shouldn't give a 'passphrase' when importing a public key.

makeNewKeys(self, keysize=512, **kwds)

Creates a new keypair in cipher object, and a new session key

Arguments:
  • keysize (default 512), advise at least 1536
Returns:
  • None
Keywords:
  • passphrase - used to secure exported private key - default '' (no passphrase)

Keypair gets stored within the key object. Refer exportKey, exportKeyPrivate and importKey.

Generally no need to call this yourself, since the constructor calls this in cases where you aren't instantiating with an importable key.

signString(self, raw)

Sign a string using private key

Arguments:
  • raw - string to be signed
Returns:
  • wrapped, base-64 encoded string of signature
Note - private key must already be present in the key object. Call importKey for the right private key first if needed.

test(self, raw)

Encrypts, then decrypts a string. What you get back should be the same as what you put in.

This is totally useless - it just gives a way to test if this API is doing what it should.

testAscii(self, raw)

Encrypts, then decrypts a string. What you get back should be the same as what you put in.

This is totally useless - it just gives a way to test if this API is doing what it should.

verifyString(self, raw, signature)

Verifies a string against a signature.

Object must first have the correct public key loaded. (see importKey). An exception will occur if this is not the case.

Arguments:
  • raw - string to be verified
  • signature - as produced when key is signed with signString
Returns:
  • True if signature is authentic, or False if not

_calcPubBlkSize(self)

Determine size of public key

_calcSesBlkSize(self)

Determine size of session blocks

_decRawPub(self, enc)

Decrypt a public-key encrypted block, and return the decrypted string

Arguments:
  • enc - the encrypted string, in the format as created by _encRawPub()
Returns:
  • decrypted block

_encRawPub(self, raw)

Encrypt a small raw string using the public key algorithm. Input must not exceed the allowable block size.

Arguments:
  • raw - small raw bit of string to encrypt
Returns:
  • binary representation of encrypted chunk, or None if verify failed

_genNewSessKey(self)

Generate a new random session key

_initBlkCipher(self)

Create a new block cipher object, set up with a new session key and IV

_padToPubBlkSize(self, raw)

padToPubBlkSize - pad a string to max size encryptable by public key

Defence against factoring attacks that can uplift a session key when that key is encrypted by itself against public key

Arguments:
  • raw - string to pad with random bytes
returns:
  • padded string. Note - it is the responsibility of the decryption code to know how much of the string to extract once decrypted.

_rawPubKey(self)

Returns a binary-encoded string of public key

_testPubKey(self, k)

Checks if binary-encoded key matches this object's pubkey

_unwrap(self, type, msg)

Unwraps a previously _wrap()'ed message.

_wrap(self, type, msg)

Encodes message as base64 and wraps with <StartPyCryptoname>/<EndPycryptoname> Args:
  • type - string to use in header/footer - eg 'Key', 'Message'
  • msg - binary string to wrap

Class Variable Details

_algosPub

Type:
dict
Value:
{'ElGamal': <module 'Crypto.PublicKey.ElGamal' from '/usr/lib/python2.\
2/site-packages/Crypto/PublicKey/ElGamal.pyc'>,
 'RSA': <module 'Crypto.PublicKey.RSA' from '/usr/lib/python2.2/site-p\
ackages/Crypto/PublicKey/RSA.pyc'>}                                    

_algosPub1

Type:
dict
Value:
{<module 'Crypto.PublicKey.ElGamal' from '/usr/lib/python2.2/site-pack\
ages/Crypto/PublicKey/ElGamal.pyc'>: 'ElGamal',
 <module 'Crypto.PublicKey.RSA' from '/usr/lib/python2.2/site-packages\
/Crypto/PublicKey/RSA.pyc'>: 'RSA'}                                    

_algosSes

Type:
dict
Value:
{'ARC2': <module 'Crypto.Cipher.ARC2' from '/usr/lib/python2.2/site-pa\
ckages/Crypto/Cipher/ARC2.so'>,
 'Blowfish': <module 'Crypto.Cipher.Blowfish' from '/usr/lib/python2.2\
/site-packages/Crypto/Cipher/Blowfish.so'>,
 'CAST': <module 'Crypto.Cipher.CAST' from '/usr/lib/python2.2/site-pa\
ckages/Crypto/Cipher/CAST.so'>,
 'DES3': <module 'Crypto.Cipher.DES3' from '/usr/lib/python2.2/site-pa\
ckages/Crypto/Cipher/DES3.so'>,
...                                                                    

_algosSes1

Type:
dict
Value:
{'CAST': 2, 'Blowfish': 1, 'ARC2': 0, 'RC5': 5, 'IDEA': 4, 'DES3': 3}  

_algosSes2

Type:
list
Value:
[<module 'Crypto.Cipher.ARC2' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/ARC2.so'>,
 <module 'Crypto.Cipher.Blowfish' from '/usr/lib/python2.2/site-packag\
es/Crypto/Cipher/Blowfish.so'>,
 <module 'Crypto.Cipher.CAST' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/CAST.so'>,
 <module 'Crypto.Cipher.DES3' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/DES3.so'>,
...                                                                    

_algosSes3

Type:
dict
Value:
{<module 'Crypto.Cipher.ARC2' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/ARC2.so'>: 'ARC2',
 <module 'Crypto.Cipher.IDEA' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/IDEA.so'>: 'IDEA',
 <module 'Crypto.Cipher.DES3' from '/usr/lib/python2.2/site-packages/C\
rypto/Cipher/DES3.so'>: 'DES3',
 <module 'Crypto.Cipher.RC5' from '/usr/lib/python2.2/site-packages/Cr\
ypto/Cipher/RC5.so'>: 'RC5',
...                                                                    

_encBuf

Type:
str
Value:
''                                                                     

_passIV

Type:
str
Value:
"w8Z4(51fKH#p{!29Q05HWcb@K 6(1qdyv{9|4=+gvji$chw!9$38^2cyGK#;}'@DHx%3)\
q_skvh4#0*="                                                           

Generated by Epydoc 1.1 on Thu Jul 24 11:15:07 2003 http://epydoc.sf.net