File: base.rb

package info (click to toggle)
ruby-openssl-signature-algorithm 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 200 kB
  • sloc: ruby: 268; sh: 4; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,184 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

require "openssl"
require "openssl/signature_algorithm/error"

module OpenSSL
  module SignatureAlgorithm
    class SignatureVerificationError < Error; end
    class UnsupportedParameterError < Error; end
    class VerifyKeyError < Error; end

    class Base
      attr_reader :signing_key, :verify_key

      def verify_key=(key)
        if compatible_verify_key?(key)
          @verify_key = key
        else
          raise(OpenSSL::SignatureAlgorithm::VerifyKeyError, "Incompatible verify key for algorithm")
        end
      end

      def compatible_verify_key?(verify_key)
        verify_key.respond_to?(:verify)
      end

      def sign(data)
        signing_key.sign(hash_function, data)
      end

      def verify(signature, verification_data)
        formatted_signature =
          if respond_to?(:formatted_signature, true)
            formatted_signature(signature)
          else
            signature
          end

        verify_key.verify(hash_function, formatted_signature, verification_data) ||
          raise(OpenSSL::SignatureAlgorithm::SignatureVerificationError, "Signature verification failed")
      end
    end
  end
end