2010-08-03 45 views
1

这是一个C#代码:如何做到这一点在Ruby on Rails的

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); 

如何做相同的Ruby on Rails的?更具体地说,我需要知道从字符串中获取字节的函数,base64对它们进行编码并计算hmac哈希。

回答

4

不知道是否完全相同相同,但它为我工作:

@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)) 
+0

@policy变量的初始值是什么? – 2011-11-23 19:01:59

+0

这是一些字符串。在我的情况下,它是一个json格式的字符串。 – 2011-11-24 08:16:23

2

我会再试一次。

有几个HMAC库的Ruby/Rails的,可能使这个简单得多: http://auth-hmac.rubyforge.org/

+0

谢谢!但实际上我需要这样做: byte [] pb = System.Text.Encoding.UTF8.GetBytes(policy.ToString()); //使用Base64对这些UTF-8字节进行编码 string policyB = Convert.ToBase64String(pb); //使用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); – 2010-08-03 06:03:38

+0

对不起,无法在评论中格式化代码。我在问题中添加了这个代码。 – 2010-08-03 06:07:46