Class: SelfSDK::Crypto

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

Instance Method Summary collapse

Constructor Details

#initialize(client, device, storage_folder, storage_key) ⇒ Crypto

Returns a new instance of Crypto.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/crypto.rb', line 7

def initialize(client, device, storage_folder, storage_key)
  @client = client
  @device = device
  @storage_key = storage_key
  @storage_folder = "#{storage_folder}/#{@client.jwt.key_id}"
  @lock_strategy = true
  @mode = "r+"

  if File.exist?()
    # 1a) if alice's account file exists load the pickle from the file
    @account = SelfCrypto::.from_pickle(File.read(), @storage_key)
  else
    # 1b-i) if create a new account for alice if one doesn't exist already
    @account = SelfCrypto::.from_seed(@client.jwt.key)

    # 1b-ii) generate some keys for alice and publish them
    @account.gen_otk(100)

    # 1b-iii) convert those keys to json
    keys = @account.otk['curve25519'].map{|k,v| {id: k, key: v}}.to_json

    # 1b-iv) post those keys to POST /v1/identities/<selfid>/devices/1/pre_keys/
    res = @client.post("/v1/apps/#{@client.jwt.id}/devices/#{@device}/pre_keys", keys)
    raise 'unable to push prekeys, please try in a few minutes' if res.code != 200

    # 1b-v) store the account to a file
    FileUtils.mkdir_p(@storage_folder)
    File.write(, @account.to_pickle(storage_key))
  end
end

Instance Method Details

#decrypt(message, sender, sender_device) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/crypto.rb', line 101

def decrypt(message, sender, sender_device)
  f = nil
  ::SelfSDK.logger.debug("- [crypto] decrypting a message")
  session_file_name = session_path(sender, sender_device)

  if File.exist?(session_file_name)
    # Lock the session file
    f = File.open(session_file_name, @mode)
    f.flock(File::LOCK_EX)
  end

  ::SelfSDK.logger.debug("- [crypto] loading sessions")
  session_with_bob = get_inbound_session_with_bob(f, message)

  # 8) create a group session and set the identity of the account you're using
  ::SelfSDK.logger.debug("- [crypto] create a group session and set the identity of the account #{@client.jwt.id}:#{@device}")
  gs = SelfCrypto::GroupSession.new("#{@client.jwt.id}:#{@device}")

  # 9) add all recipients and their sessions
  ::SelfSDK.logger.debug("- [crypto] add all recipients and their sessions #{@sender}:#{@sender_device}")
  gs.add_participant("#{sender}:#{sender_device}", session_with_bob)

  # 10) decrypt the message ciphertext
  ::SelfSDK.logger.debug("- [crypto] decrypt the message ciphertext")
  pt = gs.decrypt("#{sender}:#{sender_device}", message).to_s

  # 11) store the session to a file
  ::SelfSDK.logger.debug("- [crypto] store the session to a file")

  pickle = session_with_bob.to_pickle(@storage_key)
  if !f.nil?
    f.rewind
    f.write(pickle)
    f.truncate(f.pos)
  else
    File.write(session_file_name, pickle)
  end

  pt
ensure
  # Unlock the session file
  f&.flock(File::LOCK_UN)
  f&.close
end

#encrypt(message, recipients) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/crypto.rb', line 38

def encrypt(message, recipients)
  ::SelfSDK.logger.debug('- [crypto] encrypting a message')

  # create a group session and set the identity of the account youre using
  ::SelfSDK.logger.debug('- [crypto] create a group session and set the identity of the account youre using')
  gs = SelfCrypto::GroupSession.new("#{@client.jwt.id}:#{@device}")

  sessions = {}
  locks = {}
  ::SelfSDK.logger.debug('- [crypto] managing sessions with all recipients')

  recipients.each do |r|
    f = nil
    next if r[:id] == @client.jwt.id && r[:device_id] == @device

    session_file_name = session_path(r[:id], r[:device_id])
    session_with_bob = nil

    begin
      if File.exist?(session_file_name)
        # Lock the session file
        locks[session_file_name] = File.open(session_file_name, @mode)
        locks[session_file_name].flock(File::LOCK_EX)
      end
      session_with_bob = get_outbound_session_with_bob(locks[session_file_name], r[:id], r[:device_id])
    rescue => e
      ::SelfSDK.logger.warn("- [crypto]   there is a problem adding group participant #{r[:id]}:#{r[:device_id]}, skipping...")
      ::SelfSDK.logger.warn("- [crypto] #{e}")
      next
    end

    ::SelfSDK.logger.debug("- [crypto]   adding group participant #{r[:id]}:#{r[:device_id]}")
    gs.add_participant("#{r[:id]}:#{r[:device_id]}", session_with_bob)
    sessions[session_file_name] = session_with_bob
  end

  # 5) encrypt a message
  ::SelfSDK.logger.debug("- [crypto] group encrypting message")
  ct = gs.encrypt(message).to_s

  # 6) store the session to a file
  ::SelfSDK.logger.debug("- [crypto] storing sessions")
  sessions.each do |session_file_name, session_with_bob|
    pickle = session_with_bob.to_pickle(@storage_key)
    if locks[session_file_name]
      locks[session_file_name].rewind
      locks[session_file_name].write(pickle)
      locks[session_file_name].truncate(locks[session_file_name].pos)
    else
      File.write(session_file_name, pickle)
    end
  end

  ct
ensure
  locks.each do |session_file_name, lock|
    # Unlock the file
    if lock
      lock.flock(File::LOCK_UN)
    end
  end
end