github.com/pion/dtls/v2@v2.2.12/pkg/crypto/hash/hash.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 // Package hash provides TLS HashAlgorithm as defined in TLS 1.2 5 package hash 6 7 import ( //nolint:gci 8 "crypto" 9 "crypto/md5" //nolint:gosec 10 "crypto/sha1" //nolint:gosec 11 "crypto/sha256" 12 "crypto/sha512" 13 ) 14 15 // Algorithm is used to indicate the hash algorithm used 16 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-18 17 type Algorithm uint16 18 19 // Supported hash algorithms 20 const ( 21 None Algorithm = 0 // Blacklisted 22 MD5 Algorithm = 1 // Blacklisted 23 SHA1 Algorithm = 2 // Blacklisted 24 SHA224 Algorithm = 3 25 SHA256 Algorithm = 4 26 SHA384 Algorithm = 5 27 SHA512 Algorithm = 6 28 Ed25519 Algorithm = 8 29 ) 30 31 // String makes hashAlgorithm printable 32 func (a Algorithm) String() string { 33 switch a { 34 case None: 35 return "none" 36 case MD5: 37 return "md5" // [RFC3279] 38 case SHA1: 39 return "sha-1" // [RFC3279] 40 case SHA224: 41 return "sha-224" // [RFC4055] 42 case SHA256: 43 return "sha-256" // [RFC4055] 44 case SHA384: 45 return "sha-384" // [RFC4055] 46 case SHA512: 47 return "sha-512" // [RFC4055] 48 case Ed25519: 49 return "null" 50 default: 51 return "unknown or unsupported hash algorithm" 52 } 53 } 54 55 // Digest performs a digest on the passed value 56 func (a Algorithm) Digest(b []byte) []byte { 57 switch a { 58 case None: 59 return nil 60 case MD5: 61 hash := md5.Sum(b) // #nosec 62 return hash[:] 63 case SHA1: 64 hash := sha1.Sum(b) // #nosec 65 return hash[:] 66 case SHA224: 67 hash := sha256.Sum224(b) 68 return hash[:] 69 case SHA256: 70 hash := sha256.Sum256(b) 71 return hash[:] 72 case SHA384: 73 hash := sha512.Sum384(b) 74 return hash[:] 75 case SHA512: 76 hash := sha512.Sum512(b) 77 return hash[:] 78 default: 79 return nil 80 } 81 } 82 83 // Insecure returns if the given HashAlgorithm is considered secure in DTLS 1.2 84 func (a Algorithm) Insecure() bool { 85 switch a { 86 case None, MD5, SHA1: 87 return true 88 default: 89 return false 90 } 91 } 92 93 // CryptoHash returns the crypto.Hash implementation for the given HashAlgorithm 94 func (a Algorithm) CryptoHash() crypto.Hash { 95 switch a { 96 case None: 97 return crypto.Hash(0) 98 case MD5: 99 return crypto.MD5 100 case SHA1: 101 return crypto.SHA1 102 case SHA224: 103 return crypto.SHA224 104 case SHA256: 105 return crypto.SHA256 106 case SHA384: 107 return crypto.SHA384 108 case SHA512: 109 return crypto.SHA512 110 case Ed25519: 111 return crypto.Hash(0) 112 default: 113 return crypto.Hash(0) 114 } 115 } 116 117 // Algorithms returns all the supported Hash Algorithms 118 func Algorithms() map[Algorithm]struct{} { 119 return map[Algorithm]struct{}{ 120 None: {}, 121 MD5: {}, 122 SHA1: {}, 123 SHA224: {}, 124 SHA256: {}, 125 SHA384: {}, 126 SHA512: {}, 127 Ed25519: {}, 128 } 129 }