Module: WebhookSystem::Encoder

Defined in:
lib/webhook_system/encoder.rb

Overview

Class in charge of encoding and decoding encrypted payload

Class Method Summary collapse

Class Method Details

.decode(secret_string, payload) ⇒ Object

Given a secret string, and an encrypted payload, unwrap it, bas64 decode it decrypt it, and JSON decode it

Parameters:

  • secret_string (String)

    some secret string

  • payload (String)

    String as returned from #encode

Returns:

  • (Object)

    return the JSON decode of the encrypted payload



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/webhook_system/encoder.rb', line 27

def decode(secret_string, payload)
  encoded, iv = Payload.decode(payload)
  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  cipher.decrypt
  cipher.iv = iv
  cipher.key = key_from_secret(iv, secret_string)
  decoded = cipher.update(encoded) + cipher.final
  JSON.load(decoded)
rescue OpenSSL::Cipher::CipherError
  raise DecodingError, 'Decoding Failed, probably mismatched secret'
end

.encode(secret_string, payload) ⇒ String

Given a secret string, encode the passed payload to json encrypt it, base64 encode that, and wrap it in its own json wrapper

Parameters:

  • secret_string (String)

    some secret string

  • payload (Object#to_json)

    Any object that responds to to_json

Returns:

  • (String)

    The encoded string payload (its a JSON string)



12
13
14
15
16
17
18
19
# File 'lib/webhook_system/encoder.rb', line 12

def encode(secret_string, payload)
  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  cipher.encrypt
  iv = cipher.random_iv
  cipher.key = key_from_secret(iv, secret_string)
  encoded = cipher.update(payload.to_json) + cipher.final
  Payload.encode(encoded, iv)
end