opensource-developer
opensource-developer

Reputation: 3038

generating signature using base64_encode and hash_hmac in ruby on rails

I am con verting PHP code to Rails code and i am facing issues generating signature using base64_encode and hash_mac. The signature generated in php is 48 in length and while in Rails its in different length but fixed.

For example in PHP the signature is Jth7QaN%2F2eCMZxqjZRP%2FZ%2F%2FtKcHHkGf%2F6XB8xPBvp3I%3D

and in rails is 4ZC7dPRWHl6%2BzDcw9pDnfo2MMRCMNSvTZ8a7a6iPo6Q%3D%0A

How can i convert the below code to Rails

PHP Code:

return base64_encode(
    hash_hmac('sha256', $data, $key, true)
);

Below is the Rails code i am using, but the singatures generated are of different length

Rails Code:

signature_val = Base64.encode64(OpenSSL::HMAC.digest('sha256', key, data))

Can anyone help me to convert the PHP code to Correct Rails code, so that i can generate the signature properly.

Thanks.

Upvotes: 0

Views: 1697

Answers (1)

Amro Abdalla
Amro Abdalla

Reputation: 584

You can use the next line if you want to simulate the true part for hmac (the fourth parameter):

 OpenSSL::HMAC.digest(digest, key, data)

and the next line for false:

OpenSSL::HMAC.hexdigest(digest, key, data)

where

key = 'key'
data = 'The quick brown fox jumps over the lazy dog'
digest = OpenSSL::Digest.new('sha1') # replace sha1 with whatever you want

resource is here

Upvotes: 1

Related Questions