From cb8a84a60773cfe9e7fab03d93fc6430e4574351 Mon Sep 17 00:00:00 2001 From: icebaker Date: Sat, 3 Jun 2023 19:13:26 -0300 Subject: add cryptography to state and user identifiers --- components/crypto.rb | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 components/crypto.rb (limited to 'components/crypto.rb') diff --git a/components/crypto.rb b/components/crypto.rb new file mode 100644 index 0000000..3f97f57 --- /dev/null +++ b/components/crypto.rb @@ -0,0 +1,47 @@ +# 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) + return content unless @box + + nonce = soft ? @fixed_nonce : RbNaCl::Random.random_bytes(@box.nonce_bytes) + Base64.urlsafe_encode64(nonce + @box.encrypt(nonce, content)) + end + + def decrypt(content) + return content unless @box + + 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 -- cgit v1.2.3 From 1be75c768ca9595b54d8e2d5a8287adbc950f659 Mon Sep 17 00:00:00 2001 From: icebaker Date: Sat, 3 Jun 2023 20:35:23 -0300 Subject: typo --- components/crypto.rb | 4 ---- 1 file changed, 4 deletions(-) (limited to 'components/crypto.rb') diff --git a/components/crypto.rb b/components/crypto.rb index 3f97f57..1848c9b 100644 --- a/components/crypto.rb +++ b/components/crypto.rb @@ -19,15 +19,11 @@ module NanoBot end def encrypt(content, soft: false) - return content unless @box - nonce = soft ? @fixed_nonce : RbNaCl::Random.random_bytes(@box.nonce_bytes) Base64.urlsafe_encode64(nonce + @box.encrypt(nonce, content)) end def decrypt(content) - return content unless @box - decoded_content = Base64.urlsafe_decode64(content) nonce = decoded_content[0...@box.nonce_bytes] cipher_text = decoded_content[@box.nonce_bytes..] -- cgit v1.2.3