Package Anomos :: Package Crypto :: Module _PeerCert
[hide private]
[frames] | no frames]

Source Code for Module Anomos.Crypto._PeerCert

 1  # This program is free software: you can redistribute it and/or modify 
 2  # it under the terms of the GNU General Public License as published by 
 3  # the Free Software Foundation, either version 3 of the License, or 
 4  # (at your option) any later version. 
 5  # 
 6  # This program is distributed in the hope that it will be useful, 
 7  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 8  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 9  # GNU General Public License for more details. 
10  # 
11  # You should have received a copy of the GNU General Public License 
12  # along with this program.  If not, see <http://www.gnu.org/licenses/>. 
13   
14  import hashlib 
15   
16  from M2Crypto import RSA, X509 
17   
18  from Anomos import tobinary 
19  from Anomos.Crypto import global_randfile 
20  import Anomos.Crypto 
21   
22 -class PeerCert:
23 - def __init__(self, certObj):
24 self.hash_alg = 'sha256' 25 self.fingerprint = certObj.get_fingerprint(self.hash_alg) 26 self.pubkey = certObj.get_pubkey().get_rsa() 27 # The following prevents a nasty segfault in M2Crypto 28 # versions < .19 29 # TODO: Ban M2Cryto versions < 0.19 and remove this 30 if not isinstance(self.pubkey, RSA.RSA_pub): 31 self.pubkey = RSA.new_pub_key((self.pubkey.e, self.pubkey.n))
32
33 - def cmp(self, certObj):
34 return self.fingerprint == certObj.get_fingerprint(self.hash_alg)
35
36 - def encrypt(self, data, rmsglen=None):
37 """ 38 @type data: string 39 @return: ciphertext of data, format: {RSA encrypted session key}[Checksum(sessionkey, info, content)][msg length][content][padding] 40 @rtype: string 41 """ 42 sessionkey = Anomos.Crypto.AESKey() 43 # Encrypt the session key which we'll use to bulk encrypt the rest of the data 44 esk = self.pubkey.public_encrypt(sessionkey.key+sessionkey.iv, RSA.pkcs1_oaep_padding) 45 if rmsglen: 46 bmsglen = tobinary(rmsglen) 47 else: 48 rmsglen = len(data) 49 bmsglen = tobinary(len(data)) 50 checksum = hashlib.sha1(sessionkey.key + bmsglen + data[:rmsglen]).digest() 51 content = checksum + bmsglen + data 52 padlen = 32-(len(content)%32) 53 padding = Anomos.Crypto.get_rand(padlen) 54 ciphertext = sessionkey.encrypt(content+padding) 55 return esk + ciphertext
56