• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1## This file is part of Scapy
2## Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
3##                     2015, 2016 Maxence Tury
4## This program is published under a GPLv2 license
5
6"""
7Hash classes.
8"""
9
10from __future__ import absolute_import
11from hashlib import md5, sha1, sha224, sha256, sha384, sha512
12import scapy.modules.six as six
13
14
15_tls_hash_algs = {}
16
17class _GenericHashMetaclass(type):
18    """
19    Hash classes are automatically registered through this metaclass.
20    Furthermore, their name attribute is extracted from their class name.
21    """
22    def __new__(cls, hash_name, bases, dct):
23        if hash_name != "_GenericHash":
24            dct["name"] = hash_name[5:]     # remove leading "Hash_"
25        the_class = super(_GenericHashMetaclass, cls).__new__(cls, hash_name,
26                                                              bases, dct)
27        if hash_name != "_GenericHash":
28            _tls_hash_algs[hash_name[5:]] = the_class
29        return the_class
30
31
32class _GenericHash(six.with_metaclass(_GenericHashMetaclass, object)):
33    def digest(self, tbd):
34        return self.hash_cls(tbd).digest()
35
36
37class Hash_NULL(_GenericHash):
38    hash_len = 0
39
40    def digest(self, tbd):
41        return b""
42
43class Hash_MD5(_GenericHash):
44    hash_cls = md5
45    hash_len = 16
46
47class Hash_SHA(_GenericHash):
48    hash_cls = sha1
49    hash_len = 20
50
51class Hash_SHA224(_GenericHash):
52    hash_cls = sha224
53    hash_len = 28
54
55class Hash_SHA256(_GenericHash):
56    hash_cls = sha256
57    hash_len = 32
58
59class Hash_SHA384(_GenericHash):
60    hash_cls = sha384
61    hash_len = 48
62
63class Hash_SHA512(_GenericHash):
64    hash_cls = sha512
65    hash_len = 64
66
67