Fork me on GitHub

2009/02/12

Recent entries from same category

  1. わざわざrubyからsetlocale()呼び出すのにライブラリ作らなくても呼べた。 Hatena
  2. Windows版のruby-irbでも正しくマルチバイトを扱いたい。 Hatena
  3. Jekyllで始める簡単ブログ Hatena
  4. WindowsでApache2.2を動かしmod_rubyでtDiaryを動かす。 Hatena
  5. rmagickを使ってtumblr風レンダリング Hatena

hexdigestでなくdigestですね。:-)
mod_access_tokenを入れてみた - まめ畑

ここまでは良かったのですが、Signatureを生成するスクリプトを作ろうと思ったのですが、Rubyで上手くいかない・・・。

http://d.hatena.ne.jp/con_mame/20090209
あとはbase64に付く改行とターミネータをカットすればOKですね。
require 'openssl'
require 'base64'
require 'uri'
require 'time'

access_key = 'foo'
secret = 'bar'
url = 'http://localhost:8080/access_token/example.jpg'
exp = (Time.new+300).to_i.to_s
uri = URI.parse(url)
plain = "GET#{uri.path}#{exp}#{access_key}"
hmac = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA1.new, secret, plain)
sig = Base64.encode64(hmac).chomp.sub(/=*$/, '')
puts "#{url}?Signature=#{URI.escape(sig)}&AccessKey=#{URI.escape(access_key)}&Expires=#{URI.escape(exp.to_s)}"
結果はこんな感じ。
http://localhost:8080/access_token/example.jpg?Signature=Rt2cKnnOYuDiE/XYKTLTaOuY4Wg&AccessKey=foo&Expires=1234417692
ちなみにBase64.b64encodeはエンコード結果を表示してしまうのでencode64が良さそうですね。
  def b64encode(bin, len = 60)
    encode64(bin).scan(/.{1,#{len}}/) do
      print $&, "\n"
    end
  end 
Posted at 14:57 in ソフトウェア::lang::ruby | Edit
Tagged as: ruby
Bookmarks: add to hatena add to hatena | add to delicious.com | add to livedoor.clip add to livedoor.clip

blog comments powered by Disqus