Skip to content

Instantly share code, notes, and snippets.

@ruedap
Created June 4, 2012 00:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruedap/2865689 to your computer and use it in GitHub Desktop.
Save ruedap/2865689 to your computer and use it in GitHub Desktop.
rails3: 復号化出来るユーザー情報の保存
# 参考にしたサイト: http://mono-comp.com/programming/rails-web-appli-register/
# URLのコードとほぼ100%同じ
# $ rails g model user name:string access_token:binary access_token_secret:binary salt:string
# または
# $ rails g model user して、 db/migration 下の ***_create_user.rb に
# t.string :name
# t.binary :access_token
# t.binary :access_token_secret
# t.string :salt
# を追記
# 以下 app/model/user.rb
class User < ActiveRecord::Base
SECRET_KEY = '_____'
# 参考にしたサイト: http://mono-comp.com/programming/rails-web-appli-register/
# 暗号化
def self.crypt(password, salt)
cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
cipher.encrypt
cipher.pkcs5_keyivgen(SECRET_KEY, salt)
cipher.update(password) + cipher.final
end
# 復号化
# http://webos-goodies.jp/archives/encryption_in_ruby.html
def self.decrypt(password, salt)
cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
cipher.decrypt
cipher.pkcs5_keyivgen(SECRET_KEY, salt)
cipher.update(password) + cipher.final
end
# Salt生成
def self.new_salt
source = ("a".."z").to_a + ("A".."Z").to_a + (0..9).to_a + ["_","-","."]
key=""
8.times{ key+= source[rand(source.size)].to_s }
return key
end
end
# 参考にしたサイト: http://mono-comp.com/programming/rails-web-appli-register/
# URLのコードとほぼ100%同じ
# $ rails g model user name:string access_token:binary access_token_secret:binary salt:string
# または
# $ rails g model user して、 db/migration 下の ***_create_user.rb に
# t.string :name
# t.binary :access_token
# t.binary :access_token_secret
# t.string :salt
# を追記
# 以下 app/model/user.rb
class User < ActiveRecord::Base
SECRET_KEY = '_____'
# 参考にしたサイト: http://mono-comp.com/programming/rails-web-appli-register/
# 暗号化
def self.crypt(password, salt)
cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
cipher.encrypt
cipher.pkcs5_keyivgen(SECRET_KEY, salt)
cipher.update(password) + cipher.final
end
# 復号化
# http://webos-goodies.jp/archives/encryption_in_ruby.html
def self.decrypt(password, salt)
cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
cipher.decrypt
cipher.pkcs5_keyivgen(SECRET_KEY, salt)
cipher.update(password) + cipher.final
end
# Salt生成
def self.new_salt
source = ("a".."z").to_a + ("A".."Z").to_a + (0..9).to_a + ["_","-","."]
key=""
8.times{ key+= source[rand(source.size)].to_s }
return key
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment