mac.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. // Message authentication support
  6. import (
  7. "crypto/hmac"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "crypto/sha512"
  11. "hash"
  12. )
  13. type macMode struct {
  14. keySize int
  15. etm bool
  16. new func(key []byte) hash.Hash
  17. }
  18. // truncatingMAC wraps around a hash.Hash and truncates the output digest to
  19. // a given size.
  20. type truncatingMAC struct {
  21. length int
  22. hmac hash.Hash
  23. }
  24. func (t truncatingMAC) Write(data []byte) (int, error) {
  25. return t.hmac.Write(data)
  26. }
  27. func (t truncatingMAC) Sum(in []byte) []byte {
  28. out := t.hmac.Sum(in)
  29. return out[:len(in)+t.length]
  30. }
  31. func (t truncatingMAC) Reset() {
  32. t.hmac.Reset()
  33. }
  34. func (t truncatingMAC) Size() int {
  35. return t.length
  36. }
  37. func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() }
  38. var macModes = map[string]*macMode{
  39. "hmac-sha2-512-etm@openssh.com": {64, true, func(key []byte) hash.Hash {
  40. return hmac.New(sha512.New, key)
  41. }},
  42. "hmac-sha2-256-etm@openssh.com": {32, true, func(key []byte) hash.Hash {
  43. return hmac.New(sha256.New, key)
  44. }},
  45. "hmac-sha2-512": {64, false, func(key []byte) hash.Hash {
  46. return hmac.New(sha512.New, key)
  47. }},
  48. "hmac-sha2-256": {32, false, func(key []byte) hash.Hash {
  49. return hmac.New(sha256.New, key)
  50. }},
  51. "hmac-sha1": {20, false, func(key []byte) hash.Hash {
  52. return hmac.New(sha1.New, key)
  53. }},
  54. "hmac-sha1-96": {20, false, func(key []byte) hash.Hash {
  55. return truncatingMAC{12, hmac.New(sha1.New, key)}
  56. }},
  57. }