Class: Cryptonite::Coder

Inherits:
Object
  • Object
show all
Defined in:
lib/cryptonite/coder.rb

Overview

:nodoc:

Constant Summary collapse

HEADER =
"Cryptonite #{VERSION}: "
BASE64_REGEXP =
%r{([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)}
SEMVER_REGEXP =
/
  \bv?(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.
  (?:0|[1-9][0-9]*)(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?\b
/ix
REGEXP =
/^Cryptonite #{SEMVER_REGEXP}: (?<value>#{BASE64_REGEXP})$/

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Coder

Returns a new instance of Coder.



14
15
16
17
# File 'lib/cryptonite/coder.rb', line 14

def initialize(key)
  fail ArgumentError unless key.is_a?(::OpenSSL::PKey::RSA)
  @key = key
end

Instance Method Details

#decrypt(value) ⇒ Object Also known as: load

Decrypts a value with public key encryption. Keys should be defined in environment.



30
31
32
33
34
# File 'lib/cryptonite/coder.rb', line 30

def decrypt(value)
  return unless value
  fail ArgumentError, 'Value is not encrypted' unless value.match(REGEXP)
  @key.private_decrypt(Base64.strict_decode64(Regexp.last_match(:value)))
end

#encrypt(value) ⇒ Object Also known as: dump

Encrypts a value with public key encryption. Keys should be defined in environment.



21
22
23
24
25
# File 'lib/cryptonite/coder.rb', line 21

def encrypt(value)
  return unless value
  fail ArgumentError, 'Value is already encrypted' if value.match(REGEXP)
  HEADER + Base64.strict_encode64(@key.public_encrypt(value))
end