Module: Bixby::CryptoUtil
- Defined in:
- lib/bixby-common/util/crypto_util.rb
Class Method Summary collapse
-
.decrypt(data, key_pem, iv_pem) ⇒ Object
Decrypt the given payload from over-the-wire transmission.
-
.encrypt(data, uuid, key_pem, iv_pem) ⇒ Object
Encrypt the given payload for over-the-wire transmission.
-
.generate_access_key ⇒ String
Generate a new access key.
-
.generate_keypair ⇒ OpenSSL::PKey::RSA
Generate a new 2048-bit RSA keypair.
-
.generate_secret_key ⇒ String
Generate a new secret key.
Class Method Details
.decrypt(data, key_pem, iv_pem) ⇒ Object
Decrypt the given payload from over-the-wire transmission
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 |
# File 'lib/bixby-common/util/crypto_util.rb', line 41 def decrypt(data, key_pem, iv_pem) data = StringIO.new(data, 'rb') if not data.kind_of? StringIO hmac = data.readline.strip key = key_pem.private_decrypt(read_next(data)) iv = iv_pem.public_decrypt(read_next(data)) c = new_cipher() c.decrypt c.key = key c.iv = iv payload = d64(data.read) # very hmac of encrypted payload if not verify_hmac(hmac, key, iv, payload) then raise Bixby::EncryptionError, "hmac verification failed", caller end data = StringIO.new(c.update(payload) + c.final) ts = data.readline.strip if (Time.new.to_i - ts.to_i) > 900 then # must be within last 15 min raise Bixby::EncryptionError, "payload verification failed", caller end return data.read end |
.encrypt(data, uuid, key_pem, iv_pem) ⇒ Object
Encrypt the given payload for over-the-wire transmission
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/bixby-common/util/crypto_util.rb', line 17 def encrypt(data, uuid, key_pem, iv_pem) c = new_cipher() c.encrypt key = c.random_key iv = c.random_iv data = Time.new.to_i.to_s + "\n" + data # prepend timestamp encrypted = c.update(data) + c.final out = [] out << uuid out << create_hmac(key, iv, encrypted) out << w( key_pem.public_encrypt(key) ) out << w( iv_pem.private_encrypt(iv) ) out << e64(encrypted) return out.join("\n") end |
.generate_access_key ⇒ String
Generate a new access key
:nocov:
80 81 82 |
# File 'lib/bixby-common/util/crypto_util.rb', line 80 def generate_access_key Digest.hexencode(Digest::MD5.new.digest(OpenSSL::Random.random_bytes(512))) end |
.generate_keypair ⇒ OpenSSL::PKey::RSA
Generate a new 2048-bit RSA keypair
72 73 74 |
# File 'lib/bixby-common/util/crypto_util.rb', line 72 def generate_keypair OpenSSL::PKey::RSA.generate(2048) end |
.generate_secret_key ⇒ String
Generate a new secret key
:nocov:
89 90 91 |
# File 'lib/bixby-common/util/crypto_util.rb', line 89 def generate_secret_key Digest.hexencode(Digest::SHA2.new(512).digest(OpenSSL::Random.random_bytes(512))) end |