1 import cStringIO
2
3 from M2Crypto import EVP
4 from Anomos.Crypto import global_cryptodir, global_randfile
5 import Anomos.Crypto
6
7 from Anomos import LOG as log
9 - def __init__(self, key=None, iv=None, algorithm='aes_256_cfb'):
10 """
11 @param algorithm: encryption algorithm to use
12 @param key: 32 byte string to use as key
13 @param iv: 32 byte initalization vector to use
14 """
15 if None in (global_cryptodir, global_randfile):
16 raise CryptoError('RNG not initialized, call initCrypto first')
17 self.randfile=global_randfile
18 self.algorithm = algorithm
19
20 if key:
21 self.key = key
22 else:
23 self.key = Anomos.Crypto.get_rand()
24 if iv:
25 self.iv = iv
26 else:
27 self.iv = Anomos.Crypto.get_rand()
28
29
30 self.encCipher = EVP.Cipher(self.algorithm, self.key, self.iv, 1)
31 self.decCipher = EVP.Cipher(self.algorithm, self.key, self.iv, 0)
32
33
35 buf=inf.read()
36 outf.write(cipher.update(buf))
37 outf.write(cipher.final())
38 return outf.getvalue()
39
41 """
42 @param text: Plaintext to encrypt
43 @type text: string
44 """
45 sbuf=cStringIO.StringIO(text)
46 obuf=cStringIO.StringIO()
47 encoder = self.encCipher
48 encrypted = self.cipher_filter(encoder, sbuf, obuf)
49 sbuf.close()
50 obuf.close()
51 return encrypted
52
54 """
55 @param text: Ciphertext to decrypt
56 @type text: string
57 """
58 obuf = cStringIO.StringIO(text)
59 sbuf = cStringIO.StringIO()
60 decoder = self.decCipher
61 decrypted = self.cipher_filter(decoder, obuf, sbuf)
62 sbuf.close()
63 obuf.close()
64 return decrypted
65