views:

54

answers:

2

This is a C# code:

byte[] pb = System.Text.Encoding.UTF8.GetBytes(policy.ToString());

// Encode those UTF-8 bytes using Base64
string policyB = Convert.ToBase64String(pb);

// Sign the policy with your Secret Key using HMAC SHA-1.
System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1();
hmac.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);

byte[] signb = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(policyB));

string signature = Convert.ToBase64String(signb);

How to do the same in Ruby on rails? More specifically I need to know functions to get bytes from string and base64 encode them and calculate hmac hash.

+1  A: 

I'll try again.

There are a couple of HMAC libraries for ruby/rails that might make this much simpler: http://auth-hmac.rubyforge.org/

Toby Hede
Thanks! But actually I need to do the same like:byte[] pb = System.Text.Encoding.UTF8.GetBytes(policy.ToString());// Encode those UTF-8 bytes using Base64string policyB = Convert.ToBase64String(pb);// Sign the policy with your Secret Key using HMAC SHA-1.System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1();hmac.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);byte[] signb = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(policy));string signature = Convert.ToBase64String(signb);
Andrey M.
Sorry, can't format code in the comment. I add this code in the question.
Andrey M.
A: 

Not sure if it exactly the same, but it works for me:

@policy = ActiveSupport::Base64.encode64s(@policy)

# Sign policy with secret key
digest = OpenSSL::Digest::Digest.new('sha1')
@signature = ActiveSupport::Base64.encode64s(OpenSSL::HMAC.digest(digest, secretKey, @policy))
Andrey M.