0

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.

9
  • The signature shouldn’t be changing length, a fixed length digest is (part of) the point. Can you give examples where you are getting different lengths? Also what hash algorithm are you using in PHP, is it SHA256 as well? Commented Sep 29, 2015 at 12:23
  • hi sry, you were correct, the digest length is fixed, and yes PHP also used sha256. Have edited my question accordingly Commented Sep 29, 2015 at 12:29
  • How different are they? I’m getting the same results except Ruby is adding a line feed at the end. (Try Base64.strict_encode to have Ruby not add line feeds). Commented Sep 29, 2015 at 12:49
  • this is what i am getting in ruby 4ZC7dPRWHl6%2BzDcw9pDnfo2MMRCMNSvTZ8a7a6iPo6Q%3D%0A and this is in php Jth7QaN%2F2eCMZxqjZRP%2FZ%2F%2FtKcHHkGf%2F6XB8xPBvp3I%3D Commented Sep 29, 2015 at 12:57
  • encode64 isn’t going to give you % in the output. Commented Sep 29, 2015 at 13:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.