Sha256: cc0af5b9f3f2a8d402a6d00cff1664cda31840eb93a7973504b28a1db676a682

Contents?: true

Size: 1.7 KB

Versions: 1

Compression:

Stored size: 1.7 KB

Contents

module Gitlab
  class License
    class Encryptor
      attr_accessor :key

      def initialize(key)
        @key = key
      end

      def encrypt(data)
        unless key.private?
          raise "Provided key is not a private key."
        end

        # Encrypt the data using symmetric AES encryption.
        cipher = OpenSSL::Cipher::AES128.new(:CBC)
        cipher.encrypt
        aes_key = cipher.random_key
        aes_iv  = cipher.random_iv

        encrypted_data = cipher.update(data) + cipher.final

        # Encrypt the AES key using asymmetric RSA encryption.
        encrypted_key = self.key.private_encrypt(aes_key)

        encryption_data = {
          "data" => Base64.encode64(encrypted_data),
          "key"  => Base64.encode64(encrypted_key),
          "iv"   => Base64.encode64(aes_iv)
        }

        json_data = JSON.dump(encryption_data)
        Base64.encode64(json_data)
      end

      def decrypt(data)
        unless key.public?
          raise "Provided key is not a public key."
        end

        json_data = Base64.decode64(data)
        encryption_data = JSON.parse(json_data)

        encrypted_data  = Base64.decode64(encryption_data["data"])
        encrypted_key   = Base64.decode64(encryption_data["key"])
        aes_iv          = Base64.decode64(encryption_data["iv"])

        # Decrypt the AES key using asymmetric RSA encryption.
        aes_key = self.key.public_decrypt(encrypted_key)

        # Decrypt the data using symmetric AES encryption.
        cipher = OpenSSL::Cipher::AES128.new(:CBC)
        cipher.decrypt
        cipher.key  = aes_key
        cipher.iv   = aes_iv

        data = cipher.update(encrypted_data) + cipher.final

        data
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gitlab-license-0.0.1 lib/gitlab/license/encryptor.rb