main
 1# frozen_string_literal: true
 2
 3module Xml
 4  module Kit
 5    # This generates a fingerprint for an X509 Certificate.
 6    #
 7    #   certificate, _ = Xml::Kit::SelfSignedCertificate.new.create
 8    #
 9    #   puts Xml::Kit::Fingerprint.new(certificate).to_s
10    #   # B7:AB:DC:BD:4D:23:58:65:FD:1A:99:0C:5F:89:EA:87:AD:F1:D7:83:34:7A:E9:E4:88:12:DD:46:1F:38:05:93
11    #
12    # {include:file:spec/xml/kit/fingerprint_spec.rb}
13    class Fingerprint
14      # The OpenSSL::X509::Certificate
15      attr_reader :x509
16
17      def initialize(raw_certificate)
18        @x509 = Certificate.to_x509(raw_certificate)
19      end
20
21      # Generates a formatted fingerprint using the specified hash algorithm.
22      #
23      # @param algorithm [OpenSSL::Digest] the openssl algorithm to use `OpenSSL::Digest::SHA256`, `OpenSSL::Digest::SHA1`.
24      # @return [String] in the format of `"BF:ED:C5:F1:6C:AB:F5:B2:15:1F:BF:BD:7D:68:1A:F9:A5:4E:4C:19:30:BC:6D:25:B1:8E:98:D4:23:FD:B4:09"`
25      def algorithm(algorithm)
26        pretty_fingerprint(algorithm.new.hexdigest(x509.to_der))
27      end
28
29      def ==(other)
30        to_s == other.to_s
31      end
32
33      def eql?(other)
34        self == other
35      end
36
37      def hash
38        to_s.hash
39      end
40
41      def to_s
42        algorithm(OpenSSL::Digest::SHA256)
43      end
44
45      private
46
47      def pretty_fingerprint(fingerprint)
48        fingerprint.upcase.scan(/../).join(':')
49      end
50    end
51  end
52end