def testM2CryptoCompatibility(self): message = b"HMAC by M2Crypto!" signature = binascii.unhexlify("99cae3ec7b41ceb6e6619f2f85368cb3ae118b70") key = rdf_crypto.EncryptionKey.FromHex("94bd4e0ecc8397a8b2cdbc4b127ee7b0") h = rdf_crypto.HMAC(key) self.assertEqual(h.HMAC(message), signature) h.Verify(message, signature)
def testSHA256(self): """Tests that both types of signatures are ok.""" key = rdf_crypto.EncryptionKey.GenerateKey() message = b"Hello World!" h = rdf_crypto.HMAC(key) signature_sha1 = h.HMAC(message) signature_sha256 = h.HMAC(message, use_sha256=True) self.assertNotEqual(signature_sha1, signature_sha256) h.Verify(message, signature_sha1) h.Verify(message, signature_sha256)
def testHMAC(self): """A basic test for the HMAC class.""" key = rdf_crypto.EncryptionKey.GenerateKey() message = b"Hello World!" h = rdf_crypto.HMAC(key) signature = h.HMAC(message) h.Verify(message, signature) broken_message = message + b"!" self.assertRaises(rdf_crypto.VerificationError, h.Verify, broken_message, signature) broken_signature = _Tamper(signature) self.assertRaises(rdf_crypto.VerificationError, h.Verify, b"Hello World!", broken_signature)
def _VerifyHMAC(self, comms=None): """Verifies the HMAC. This method raises a DecryptionError if the received HMAC does not verify. If the HMAC verifies correctly, True is returned. Args: comms: The comms RdfValue to verify. Raises: DecryptionError: The HMAC did not verify. Returns: True """ # Check the encrypted message integrity using HMAC. if self.hmac_type == "SIMPLE_HMAC": msg = comms.encrypted digest = comms.hmac elif self.hmac_type == "FULL_HMAC": msg = b"".join([ comms.encrypted, comms.encrypted_cipher, comms.encrypted_cipher_metadata, comms.packet_iv.SerializeToString(), struct.pack("<I", comms.api_version) ]) digest = comms.full_hmac else: raise DecryptionError("HMAC type no supported.") try: rdf_crypto.HMAC(self.cipher.hmac_key).Verify(msg, digest) except rdf_crypto.VerificationError as e: raise DecryptionError("HMAC verification failed: %s" % e) return True
def GetHMAC(self): return rdf_crypto.HMAC(self.hmac_key.RawBytes())
def HMAC(self, *data): return rdf_crypto.HMAC(self.cipher.hmac_key).HMAC(b"".join(data))