Module: CivicSIPSdk::Crypto

Defined in:
lib/civic_sip_sdk/crypto.rb

Constant Summary collapse

CIPHER_ALGO =
'AES-128-CBC'
IV_STRING_LENGTH =
32
ECDSA_CURVE =

“prime256v1” is another name for “secp256r1”

'prime256v1'
JWT_ALGO =
'ES256'
HMAC_DIGEST =
'SHA256'

Class Method Summary collapse

Class Method Details

.civic_extension(secret:, body:) ⇒ Object



74
75
76
77
# File 'lib/civic_sip_sdk/crypto.rb', line 74

def self.civic_extension(secret:, body:)
  hmac = OpenSSL::HMAC.digest(HMAC_DIGEST, secret, body)
  Base64.encode64(hmac)
end

.decode_jwt_token(token:, public_hex_key:, should_verify:) ⇒ Object



67
68
69
70
71
72
# File 'lib/civic_sip_sdk/crypto.rb', line 67

def self.decode_jwt_token(token:, public_hex_key:, should_verify:)
  public_key = public_signing_key(public_hex_key: public_hex_key)
  data, = JWT.decode(token, public_key, should_verify, algorithm: JWT_ALGO)

  data
end

.decrypt(text:, secret:) ⇒ Object

Decrypt the encrypted text using AES-128-CBC with a IV of 32 bytes

Parameters:

  • text (String)

    the encrypted text to be decrypted

  • secret (String)

    the Civic application secret in HEX format



36
37
38
39
40
41
42
43
44
45
# File 'lib/civic_sip_sdk/crypto.rb', line 36

def self.decrypt(text:, secret:)
  cipher = OpenSSL::Cipher.new(CIPHER_ALGO)
  cipher.decrypt
  cipher.key = hex_to_string(hex: secret)
  iv_hex = text[0..(IV_STRING_LENGTH - 1)]
  cipher.iv = hex_to_string(hex: iv_hex)
  encrypted_text = Base64.decode64(text[IV_STRING_LENGTH..-1])

  "#{cipher.update(encrypted_text)}#{cipher.final}"
end

.encrypt(text:, secret:) ⇒ Object

Create encrypted text using AES-128-CBC with a IV of 16 bytes

Parameters:

  • text (String)

    the plain text to be encrypted

  • secret (String)

    the Civic application secret in HEX format



21
22
23
24
25
26
27
28
29
30
# File 'lib/civic_sip_sdk/crypto.rb', line 21

def self.encrypt(text:, secret:)
  cipher = OpenSSL::Cipher.new(CIPHER_ALGO)
  cipher.encrypt
  cipher.key = hex_to_string(hex: secret)
  iv = cipher.random_iv
  cipher.iv = iv

  encrypted_text = "#{cipher.update(text)}#{cipher.final}"
  "#{string_to_hex(str: iv)}#{Base64.encode64(encrypted_text)}"
end

.jwt_token(app_id:, sip_base_url:, data:, private_key:) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/civic_sip_sdk/crypto.rb', line 47

def self.jwt_token(app_id:, sip_base_url:, data:, private_key:)
  now = Time.now.to_i

  payload = {
    iat: now,
    exp: now + 60 * 3,
    iss: app_id,
    aud: sip_base_url,
    sub: app_id,
    jti: SecureRandom.uuid,
    data: data
  }

  JWT.encode(
    payload,
    private_signing_key(private_hex_key: private_key),
    JWT_ALGO
  )
end