Class: Nanite::SecureSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/nanite/security/secure_serializer.rb

Overview

Serializer implementation which secures messages by using X.509 certificate sigining.

Class Method Summary collapse

Class Method Details

.dump(obj, encrypt = nil) ⇒ Object

Serialize message and sign it using X.509 certificate



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nanite/security/secure_serializer.rb', line 31

def self.dump(obj, encrypt=nil)
  raise "Missing certificate identity" unless @identity
  raise "Missing certificate" unless @cert
  raise "Missing certificate key" unless @key
  raise "Missing certificate store" unless @store || !@encrypt
  must_encrypt = encrypt.nil? ? @encrypt : encrypt
  json = obj.to_json
  if must_encrypt
    certs = @store.get_recipients(obj)
    json = EncryptedDocument.new(json, certs).encrypted_data if certs
  end
  sig = Signature.new(json, @cert, @key)
  { 'id' => @identity, 'data' => json, 'signature' => sig.data, 'encrypted' => !certs.nil? }.to_json
end

.init(identity, cert, key, store, encrypt = true) ⇒ Object

Initialize serializer, must be called prior to using it.

- 'identity':   Identity associated with serialized messages
- 'cert':       Certificate used to sign and decrypt serialized messages
- 'key':        Private key corresponding to 'cert'
- 'store':      Certificate store. Exposes certificates used for
                encryption and signature validation.
- 'encrypt':    Whether data should be signed and encrypted ('true')
                or just signed ('false'), 'true' by default.


17
18
19
20
21
22
23
# File 'lib/nanite/security/secure_serializer.rb', line 17

def self.init(identity, cert, key, store, encrypt = true)
  @identity = identity
  @cert = cert
  @key = key
  @store = store
  @encrypt = encrypt
end

.initialized?Boolean

Was serializer initialized?

Returns:

  • (Boolean)


26
27
28
# File 'lib/nanite/security/secure_serializer.rb', line 26

def self.initialized?
  @identity && @cert && @key && @store
end

.load(json) ⇒ Object

Unserialize data using certificate store



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/nanite/security/secure_serializer.rb', line 47

def self.load(json)
  raise "Missing certificate store" unless @store
  raise "Missing certificate" unless @cert || !@encrypt
  raise "Missing certificate key" unless @key || !@encrypt
  data = JSON.load(json)
  sig = Signature.from_data(data['signature'])
  certs = @store.get_signer(data['id'])
  raise "Could not find a cert for signer #{data['id']}" unless certs
  certs = [ certs ] unless certs.respond_to?(:any?)
  raise "Failed to check signature for signer #{data['id']}" unless certs.any? { |c| sig.match?(c) }
  jsn = data['data']
  if jsn && @encrypt && data['encrypted']
    jsn = EncryptedDocument.from_data(jsn).decrypted_data(@key, @cert)
  end
  JSON.load(jsn) if jsn
end