diff options
author | icebaker <113217272+icebaker@users.noreply.github.com> | 2023-06-03 20:37:14 -0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-06-03 20:37:14 -0300 |
commit | bffbac01eeb00e5f94cd4d675edc0a0566354265 (patch) | |
tree | 39df8578dd2bbed230e0d222d0175e088f97537e /components/crypto.rb | |
parent | 2c50a06b68a21ce904e5dfd15833e3569ff64bfa (diff) | |
parent | 1be75c768ca9595b54d8e2d5a8287adbc950f659 (diff) |
Merge pull request #3 from icebaker/ib-cryptography
Cryptography and Security
Diffstat (limited to 'components/crypto.rb')
-rw-r--r-- | components/crypto.rb | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/components/crypto.rb b/components/crypto.rb new file mode 100644 index 0000000..1848c9b --- /dev/null +++ b/components/crypto.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require 'singleton' +require 'rbnacl' +require 'base64' + +module NanoBot + module Components + class Crypto + include Singleton + + def initialize + password = ENV.fetch('NANO_BOTS_ENCRYPTION_PASSWORD', nil) + + password = 'UNSAFE' unless password && password != '' + + @box = RbNaCl::SecretBox.new(RbNaCl::Hash.sha256(password)) + @fixed_nonce = RbNaCl::Hash.sha256(password)[0...@box.nonce_bytes] + end + + def encrypt(content, soft: false) + nonce = soft ? @fixed_nonce : RbNaCl::Random.random_bytes(@box.nonce_bytes) + Base64.urlsafe_encode64(nonce + @box.encrypt(nonce, content)) + end + + def decrypt(content) + decoded_content = Base64.urlsafe_decode64(content) + nonce = decoded_content[0...@box.nonce_bytes] + cipher_text = decoded_content[@box.nonce_bytes..] + + @box.decrypt(nonce, cipher_text) + end + + def self.encrypt(content, soft: false) + instance.encrypt(content, soft:) + end + + def self.decrypt(content) + instance.decrypt(content) + end + end + end +end |