def obtainKey(self, request, cert): key = self.decrypt(algs.int_repr(request['Key'])) signature = self.decrypt(algs.int_repr(request['Signature'])) length = request['Length'] verified = self.verifyKey(key, signature, cert) if verified: self.__obtained_keys.append( {'Key': algs.hex_repr(key, length), 'From': cert}) return { 'verified': verified, 'key': algs.hex_repr(key, length) }
def verify(self, letter, cert): e = cert['Public Key Info']['Exponent'] n = algs.int_repr(cert['Public Key Info']['Modulus']) if type(letter['Message']) == str: msg = letter['Message'].encode('utf-8') sign = algs.int_repr(letter['Signature']) md5 = hashlib.md5(msg) msg = md5.digest() if msg == pow(sign, e, n).to_bytes(16, 'big'): return True else: return False
def encrypt(self, msg, cert): e = cert['Public Key Info']['Exponent'] n = algs.int_repr(cert['Public Key Info']['Modulus']) if type(msg) == str: msg = msg.encode('utf-8') msg = int.from_bytes(msg, 'big') elif type(msg) == bytes: msg = int.from_bytes(msg, 'big') if msg < n: return pow(msg, e, n) else: raise ValueError('Too long message')
def generateKeyToAbonent(self, length, cert): k = random.randint(2**(length - 1), 2**length) self.__generated_keys.append( {'Key': algs.hex_repr(k, length), 'To': cert}) e = cert['Public Key Info']['Exponent'] n = algs.int_repr(cert['Public Key Info']['Modulus']) l = cert['Public Key Info']['Modulus Length'] k1 = self.encrypt(k, cert) s1 = self.encrypt(self.signKey(k, length), cert) return { 'Key': algs.hex_repr(k1, l), 'Length': length, 'Signature': algs.hex_repr(s1, l) }
def verifyKey(self, key, signature, cert): e = cert['Public Key Info']['Exponent'] n = algs.int_repr(cert['Public Key Info']['Modulus']) return pow(signature, e, n) == key