1#--
2#
3# $RCSfile$
4#
5# = Ruby-space predefined Digest subclasses
6#
7# = Info
8# 'OpenSSL for Ruby 2' project
9# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
10# All rights reserved.
11#
12# = Licence
13# This program is licenced under the same licence as Ruby.
14# (See the file 'LICENCE'.)
15#
16# = Version
17# $Id: digest.rb 41809 2013-07-06 16:52:56Z nagachika $
18#
19#++
20
21module OpenSSL
22  class Digest
23
24    alg = %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1)
25    if OPENSSL_VERSION_NUMBER > 0x00908000
26      alg += %w(SHA224 SHA256 SHA384 SHA512)
27    end
28
29    # Return the +data+ hash computed with +name+ Digest. +name+ is either the
30    # long name or short name of a supported digest algorithm.
31    #
32    # === Examples
33    #
34    #   OpenSSL::Digest.digest("SHA256", "abc")
35    #
36    # which is equivalent to:
37    #
38    #   OpenSSL::Digest::SHA256.digest("abc")
39
40    def self.digest(name, data)
41        super(data, name)
42    end
43
44    alg.each{|name|
45      klass = Class.new(Digest){
46        define_method(:initialize){|*data|
47          if data.length > 1
48            raise ArgumentError,
49              "wrong number of arguments (#{data.length} for 1)"
50          end
51          super(name, data.first)
52        }
53      }
54      singleton = (class << klass; self; end)
55      singleton.class_eval{
56        define_method(:digest){|data| Digest.digest(name, data) }
57        define_method(:hexdigest){|data| Digest.hexdigest(name, data) }
58      }
59      const_set(name, klass)
60    }
61
62    # This class is only provided for backwards compatibility.  Use OpenSSL::Digest in the future.
63    class Digest < Digest
64      def initialize(*args)
65        # add warning
66        super(*args)
67      end
68    end
69
70  end # Digest
71
72  # Returns a Digest subclass by +name+.
73  #
74  #   require 'openssl'
75  #
76  #   OpenSSL::Digest("MD5")
77  #   # => OpenSSL::Digest::MD5
78  #
79  #   Digest("Foo")
80  #   # => NameError: wrong constant name Foo
81
82  def Digest(name)
83    OpenSSL::Digest.const_get(name)
84  end
85
86  module_function :Digest
87
88end # OpenSSL
89
90