HMAC and SHA

ESEWA INTEGRATION


HMAC-SHA256

Introduction to SHA

SHA (Secure Hash Algorithm) is a family of cryptographic hash functions designed to ensure data integrity. A hash function takes an input and returns a fixed-size string of bytes, typically a digest that is unique to each unique input.

SHA-256 is a popular hashing algorithm that generates a 256-bit (32-byte) hash value from the input data. It's commonly used in cryptography for data integrity verification and is part of the SHA-2 family.

Introduction to MAC

MAC (Message Authentication Code) is a method of verifying data integrity and authenticity. A MAC is produced by a hash function combined with a secret key. Unlike hashing, which is one-way and non-reversible, a MAC ensures that the message is both unmodified and from the authentic source, as it uses a secret key shared between the sender and the receiver.

 

Generating SHA-256 Hash

Below is an example of generating a SHA-256 hash using Python:


import hashlib

# Data to be hashed
data = "Hello, eSewa!"

# Generating SHA-256 hash
sha256_hash = hashlib.sha256(data.encode()).hexdigest()

print("SHA-256 Hash:", sha256_hash)

Generating HMAC with SHA-256

HMAC (Hash-based Message Authentication Code) uses a cryptographic hash function (like SHA-256) and a secret key to provide both integrity and authenticity.

Here’s how to generate an HMAC-SHA256 using Python:


import hmac
import hashlib

# Secret key and data
secret_key = b"my_secret_key"
data = "Hello, eSewa!"

# Generating HMAC-SHA256
hmac_sha256 = hmac.new(secret_key, data.encode(), hashlib.sha256).hexdigest()

print("HMAC-SHA256:", hmac_sha256)

In our case

eSewa has defined that we need to implement HMAC-SHA256 as per RFC-2104, which is a standard. They also specify that the message needs to be arranged like this:

message = f'total_amount={total_amount},transaction_uuid={transaction_uuid},product_code=EPAYTEST'

After constructing the message, we can use the following function to create the signature (HMAC):


import hmac
import hashlib
import base64

def generate_signature(key, message):
    key = key.encode('utf-8')
    message = message.encode('utf-8')

    hmac_sha256 = hmac.new(key, message, hashlib.sha256)
    digest = hmac_sha256.digest()

    # Convert the digest to a Base64-encoded string
    signature = base64.b64encode(digest).decode('utf-8')

    return signature

Conclusion

SHA-256 provides a secure hashing mechanism to verify data integrity, while HMAC-SHA256 enhances this by ensuring message authenticity using a secret key. Both are critical components in cryptography and widely used in secure applications like payment gateways and APIs.

References