Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

PREVIOUS NEXT
Code Example
Python :: How to pass a data frame as parameter to a SQL query in Python? 
Python :: python method name 
Python :: numpy how to apply interpolation all rows 
Python :: numpy array values not updateing 
Python :: append in dictionary with matrix values 
Python :: np.apply_along_axis third dimension python 
Python :: ORing two cv mat objects 
Python :: fast comand exit python windows 
Python :: readme python convert to pdf 
Python :: multiclass.roc plot title 
Python :: python tags 
Python :: falcon 900 price 
Python :: def square_odd(pylist) 
Python :: elongated muskrat 
Python :: extract label from tf data 
Python :: how to convert small letters to capital letters in python 
Python :: qq plot using seaborn with regression line 
Python :: python generate fibonacci series 
Python :: how to check if a column exists before alter the table 
Python :: user logout in django rest framework 
Python :: operations in python 
Python :: who is agada nathan 
Python :: numpy transpose shorthand 
Python :: python import shelve 
Python :: iterate rows 
Python :: how does gas exchange happen in the alveoli 
Python :: # multithreading for optimal use of CPU 
Python :: python sorted vs sort 
Python :: WS2812 Thonny microPython 
Python :: Example pandas.read_hdf5() 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =