· 7 years ago · Jun 01, 2018, 03:48 PM
1require 'openssl'
2require 'base64'
3
4class UserEncrypted < ActiveRecord::Base
5 PADDING = { 2 => "==", 3 => "=" }
6 def to_param
7 crypto = OpenSSL::Cipher::Cipher.new('aes-256-ecb').send(:encrypt)
8 crypto.key = SECRET_KEY
9 cipher = crypto.update(id.to_s)
10 cipher << crypto.final
11
12 cipher = Base64.encode64(cipher).gsub(/[\s=]+/, "").gsub("+", "-").gsub("/", "_")
13 end
14
15 class << self
16 def find_by_encrypted_id(encrypted_data)
17 encrypted_data = Base64.decode64("#{encrypted_data.gsub("-", "+").gsub("_", "/")}#{PADDING[encrypted_data.length % 4]}")
18
19 crypto = OpenSSL::Cipher::Cipher.new('aes-256-ecb').send(:decrypt)
20 crypto.key = SECRET_KEY
21 id = crypto.update(encrypted_data)
22 id << crypto.final
23
24 find_by_id(id)
25 end
26 end
27end