Class: GLogin::Codec
- Inherits:
-
Object
- Object
- GLogin::Codec
- Defined in:
- lib/glogin/codec.rb
Overview
The codec
Defined Under Namespace
Classes: DecodingError
Instance Method Summary collapse
- #decrypt(text) ⇒ Object
- #encrypt(text) ⇒ Object
-
#initialize(secret = '', base64: false) ⇒ Codec
constructor
Ctor.
Constructor Details
#initialize(secret = '', base64: false) ⇒ Codec
Ctor. secret
: The secret to do the encoding base64
: If TRUE, Base-64 will be used, otherwise Base-58
43 44 45 46 47 |
# File 'lib/glogin/codec.rb', line 43 def initialize(secret = '', base64: false) raise 'Secret can\'t be nil' if secret.nil? @secret = secret @base64 = base64 end |
Instance Method Details
#decrypt(text) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/glogin/codec.rb', line 49 def decrypt(text) raise 'Text can\'t be nil' if text.nil? if @secret.empty? text else cpr = cipher cpr.decrypt cpr.key = digest(cpr.key_len) if @base64 raise DecodingError, 'This is not Base64' unless %r{^[a-zA-Z0-9\\+/=]+$}.match?(text) else raise DecodingError, 'This is not Base58' unless /^[a-zA-Z0-9]+$/.match?(text) end plain = @base64 ? Base64.decode64(text) : Base58.base58_to_binary(text) raise DecodingError if plain.empty? decrypted = cpr.update(plain) decrypted << cpr.final salt, body = decrypted.to_s.split(' ', 2) raise DecodingError if salt.empty? raise DecodingError if body.nil? body.force_encoding('UTF-8') body end rescue OpenSSL::Cipher::CipherError => e raise DecodingError, e. end |
#encrypt(text) ⇒ Object
76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/glogin/codec.rb', line 76 def encrypt(text) raise 'Text can\'t be nil' if text.nil? if @secret.empty? text else cpr = cipher cpr.encrypt cpr.key = digest(cpr.key_len) salt = SecureRandom.base64(Random.rand(8..32)) encrypted = cpr.update("#{salt} #{text}") encrypted << cpr.final @base64 ? Base64.encode64(encrypted).gsub("\n", '') : Base58.binary_to_base58(encrypted) end end |