Class: EncryptedJson::Secure

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

Instance Method Summary collapse

Constructor Details

#initialize(key, password = '', digest = 'SHA1') ⇒ Secure

Returns a new instance of Secure.



10
11
12
13
14
15
16
17
# File 'lib/encrypted_json.rb', line 10

def initialize(key, password='', digest='SHA1')
  if password != ''
    @key = OpenSSL::PKey::RSA.new(key, password)
  else
    @key = OpenSSL::PKey::RSA.new(key)
  end
  @digest = digest
end

Instance Method Details

#decrypt(input, password = '') ⇒ Object

Raises:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/encrypted_json.rb', line 37

def decrypt(input, password = '')
  data = ""
  digest, edata = json_decode(input)
  begin
    if @key.private?
      data = @key.private_decrypt(Base64.decode64(edata))
    else
      data = @key.public_decrypt(Base64.decode64(edata))
    end
  rescue => e
    raise DecryptionError
  end
  raise SignatureError unless digest == sign(data)
  begin
    JSON.parse(data)
  rescue
    data
  end
end

#encrypt(input, password = '') ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/encrypted_json.rb', line 19

def encrypt(input, password = '') 
  if input.is_a?(String)
    i = input
  else
    i = input.to_json
  end
  begin
    if @key.private?
      data = Base64.encode64(@key.private_encrypt(i))
    else
      data = Base64.encode64(@key.public_encrypt(i))
    end
    [sign(i), data].to_json
  rescue => e
    raise EncryptionError
  end
end

#json_decode(input) ⇒ Object

Raises:



57
58
59
60
61
62
63
64
65
# File 'lib/encrypted_json.rb', line 57

def json_decode(input)
  begin
    parts = JSON.parse(input)
  rescue TypeError, JSON::ParserError
    raise InputError
  end
  raise InputError unless parts.instance_of?(Array) && parts.length == 2
  parts    
end

#sign(input) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/encrypted_json.rb', line 67

def sign(input)
  digest = OpenSSL::Digest.const_get(@digest).new
  if @key.private?
    secret = Digest::MD5.hexdigest(@key.public_key.to_der)
  else
    secret = Digest::MD5.hexdigest(@key.to_der)
  end
  OpenSSL::HMAC.hexdigest(digest, secret, input)
end