Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HMAC SHA256 in Ruby

Tags:

I'm trying to apply HMAC-SHA256 for generate a key for an Rest API.

I'm doing something like this:

def generateTransactionHash(stringToHash)   key = '123'   data = 'stringToHash'   digest = OpenSSL::Digest.new('sha256')    hmac = OpenSSL::HMAC.digest(digest, key, data)   puts hmac end 

The output of this is always this: (if I put '12345' as parameter or 'HUSYED815X', I do get the same)

ۯw/{o���p�T����:��a�h��E|q 

The API is not working because of this... Can some one help me with that?

like image 556
Eduardo Pedroso Avatar asked Jan 18 '16 12:01

Eduardo Pedroso


People also ask

Is HMAC SHA256 the same as SHA256?

Remarks. HMACSHA256 is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC).

Is HMAC SHA256 encrypted?

HMAC(Hash-based message authentication code) is a message authentication code that uses a cryptographic hash function such as SHA-256, SHA-512 and a secret key known as a cryptographic key. HMAC is more secure than any other authentication codes as it contains Hashing as well as MAC.

What is OpenSSL HMAC?

OpenSSL::HMAC allows computing Hash-based Message Authentication Code (HMAC). It is a type of message authentication code (MAC) involving a hash function in combination with a key. HMAC can be used to verify the integrity of a message as well as the authenticity.

How do I create a signature in HMAC?

Setting up HMAC using the DashboardScroll to the Authentication options. Select HMAC (Signed Authetication Key) from the drop-down list. Configure your HMAC Request Signing settings. Select Strip Authorization Data to strip any authorization data from your API requests.


2 Answers

According to the documentation OpenSSL::HMAC.digest

Returns the authentication code an instance represents as a binary string.

If you have a problem using that maybe you need a hex encoded form provided by OpenSSL::HMAC.hexdigest

Example

key = 'key' data = 'The quick brown fox jumps over the lazy dog' digest = OpenSSL::Digest.new('sha256')  OpenSSL::HMAC.digest(digest, key, data) #=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"  OpenSSL::HMAC.hexdigest(digest, key, data) #=> "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" 
like image 95
Mike Szyndel Avatar answered Sep 30 '22 12:09

Mike Szyndel


Try This:

hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, data) 
like image 35
Vish Avatar answered Sep 30 '22 10:09

Vish