Sha256: 2a7f09c18d58fd7ad89c0e0e8ba621ced055b7b7f741cf00799eaeb2fdb91936

Contents?: true

Size: 1.18 KB

Versions: 4

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

require 'openssl'
require 'base64'

module Tcat
  class EncryptionService
    class EncryptionError < StandardError; end

    CIPHER_ALGORITHM = 'AES-128-ECB'

    def initialize(secret_key)
      @secret_key = secret_key
      validate_key!
    end

    def encrypt(message)
      cipher = setup_cipher
      padded_message = pad_message(message, cipher.block_size)
      encrypted = cipher.update(padded_message)
      Base64.strict_encode64(encrypted)
    rescue OpenSSL::Cipher::CipherError => e
      raise EncryptionError, "Encryption failed: #{e.message}"
    rescue StandardError => e
      raise EncryptionError, "Unexpected error during encryption: #{e.message}"
    end

    private

    def validate_key!
      raise EncryptionError, 'Secret key cannot be nil or empty' if @secret_key.nil? || @secret_key.empty?
    end

    def setup_cipher
      cipher = OpenSSL::Cipher.new(CIPHER_ALGORITHM)
      cipher.encrypt
      cipher.key = @secret_key
      cipher
    end

    def pad_message(message, block_size)
      padding_size = block_size - (message.length % block_size)
      padding = padding_size.chr * padding_size
      message + padding
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tcat-0.1.8 lib/tcat/encryption_service.rb
tcat-0.1.7 lib/tcat/encryption_service.rb
tcat-0.1.6 lib/tcat/encryption_service.rb
tcat-0.1.5 lib/tcat/encryption_service.rb