Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

hmac decrypt python

from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
import base64
import binascii

class AESCipher:
    def __init__(self, key):
        key_hash = SHA256.new(key).hexdigest()
        self.hmac_key = binascii.unhexlify(key_hash[len(key_hash)/2:])
        self.key = binascii.unhexlify(key_hash[:len(key_hash)/2])

    def verify_hmac(self, input_cipher, mac):
        local_hash = HMAC.new(self.hmac_key, digestmod=SHA256)
        local_hash.update(input_cipher)
        local_digest = local_hash.digest()

        return SHA256.new(mac).digest() == SHA256.new(local_digest).digest() # more or less constant-time comparison

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        hmac = enc[-32:]
        cipher_text = enc[16:-32]

        verified_hmac = self.verify_hmac((iv+cipher_text), hmac)

        if verified_hmac:
            cipher = AES.new(self.key, AES.MODE_CFB, iv, segment_size=128)
            return cipher.decrypt(cipher_text)
        else:
            return 'Bad Verify'


password = 'BJhtfRjKnTDTtPXUBnErKDxfkiMCOLyP'

input = "btu0CCFbvdYV4B/j7hezAra6Q6u6KB8n5QcyA32JFLU8QRd+jLGW0GxMQsTqxaNaNkcU2I9r1ls4QUPUpaLPQg=="

obj = AESCipher(password)
decryption = obj.decrypt(input)

print 'Decrypted message:', decryption
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #hmac #decrypt #python
ADD COMMENT
Topic
Name
4+3 =