为 OAuth 生成 HMAC-SHA1 签名的 Ruby 方法 [英] Ruby way to generate a HMAC-SHA1 signature for OAuth
问题描述
我正在编写一个小的 ruby 程序来通过 OAuth 使用 Twitter,但还没有找到正确的方法来执行 HMAC-SHA1 签名.到目前为止,我搞砸了
I'm writing a small ruby program to play with Twitter over OAuth and have yet to find a right way to do the HMAC-SHA1 signature. So far, I messed around with
Base64.encode64(OpenSSL::HMAC.hexdigest(digest, key, stuff)).chomp
但这会输出 Twitter 拒绝的东西,而不是有效的签名.我实际上以更糟糕的方式解决了它,请尽量不要打我:
But this outputs something that Twitter rejects, not being a valid signature. I actually solved it in the worse way possible, please try not to slap me:
php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', '#{@signature}', '#{llave}', true)));"
最后一个确实有效,我可以到处做我的事情.
This last one actually works and I can go around doing my stuff.
我想要一些关于如何在不回到 PHP 的情况下实际执行此操作的提示.在尝试学习一门语言时,我不太喜欢图书馆,所以宝石几乎是不可能的.
I'd like some tips on how to do actually do this without reverting back to PHP. I'm not much of a fan of libraries while I'm trying to learn a language, so gems are pretty much out of the question.
谢谢!
推荐答案
下面的代码等价于你的 PHP 代码,虽然我选择不将其封装在一行中.
The following is equivalent to your PHP code, though I chose not to wrap it in a single line.
我正在使用 gem ruby-hmac,因为它适用于 1.8 和 Ruby 1.9.如果你只使用 Ruby 1.9,我相信标准库包digest"已经实现了 HMAC(但在 1.8 版本的包中没有这个).确保 gem install ruby-hmac
I'm using the gem ruby-hmac, because it works with 1.8 as well as Ruby 1.9. If you're exclusively using Ruby 1.9 I believe the standard library package 'digest' has HMAC implemented (but this is missing in the 1.8 version of the package). Make sure to gem install ruby-hmac
require 'rubygems'
require 'base64'
require 'cgi'
require 'hmac-sha1'
key = '1234'
signature = 'abcdef'
hmac = HMAC::SHA1.new(key)
hmac.update(signature)
puts CGI.escape(Base64.encode64("#{hmac.digest}
"))
# equivalent to:
# php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"
更好的是,使用标准库包 OpenSSL(大多数 Linux 和 MacOS 开箱即用).此代码适用于 Ruby 1.8 和 1.9:
Better yet, use the standard library package OpenSSL (which most Linux and MacOS have out of the box). This code will work on Ruby 1.8 and 1.9:
require 'base64'
require 'cgi'
require 'openssl'
key = '1234'
signature = 'abcdef'
puts CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1',key, signature)}
"))
# equivalent to:
# php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"
这篇关于为 OAuth 生成 HMAC-SHA1 签名的 Ruby 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!