Module: CryptoTools

Included in:
Nostr
Defined in:
lib/crypto_tools.rb

Class Method Summary collapse

Class Method Details

.aes_256_cbc_decrypt(priv_key_a, pub_key_b, payload, iv) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/crypto_tools.rb', line 23

def self.aes_256_cbc_decrypt(priv_key_a, pub_key_b, payload, iv)
  cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
  cipher.decrypt
  cipher.iv = Base64.decode64(iv)
  cipher.key = calculate_shared_key(priv_key_a, pub_key_b)
  (cipher.update(Base64.decode64(payload)) + cipher.final).force_encoding('UTF-8')
end

.aes_256_cbc_encrypt(priv_key_a, pub_key_b, payload) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/crypto_tools.rb', line 12

def self.aes_256_cbc_encrypt(priv_key_a, pub_key_b, payload)
  cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
  cipher.encrypt
  cipher.iv = iv = cipher.random_iv
  cipher.key = calculate_shared_key(priv_key_a, pub_key_b)
  encrypted_text = cipher.update(payload)
  encrypted_text << cipher.final
  encrypted_text = "#{Base64.encode64(encrypted_text)}?iv=#{Base64.encode64(iv)}"
  encrypted_text.gsub("\n", '')
end

.calculate_shared_key(priv_key_a, pub_key_b) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/crypto_tools.rb', line 3

def self.calculate_shared_key(priv_key_a, pub_key_b)
  ec = OpenSSL::PKey::EC.new('secp256k1')
  ec.private_key = OpenSSL::BN.new(priv_key_a, 16)
  pub_key_hex = "02#{pub_key_b}"
  pub_key_bn = OpenSSL::BN.new(pub_key_hex, 16)
  secret_point = OpenSSL::PKey::EC::Point.new(ec.group, pub_key_bn)
  ec.dh_compute_key(secret_point)
end