Ruby way to generate a HMAC-SHA1 signature for OAuth

后端 未结 2 1952
轻奢々
轻奢々 2020-12-23 14:15

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

相关标签:
2条回答
  • 2020-12-23 15:05
    def hmac_sha1(data, secret=HOST_KEY)
        require 'base64'
        require 'cgi'
        require 'openssl'
        hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), secret.encode("ASCII"), data.encode("ASCII"))
        return hmac
    end
    
    0 讨论(0)
  • 2020-12-23 15:20

    The following is equivalent to your PHP code, though I chose not to wrap it in a single line.

    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}\n"))
    
    # equivalent to:
    # php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"
    

    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)}\n"))
    
    # equivalent to:
    # php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"
    
    0 讨论(0)
提交回复
热议问题