sha1.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright (C) 2017. See AUTHORS.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package openssl
  15. // #include "shim.h"
  16. import "C"
  17. import (
  18. "errors"
  19. "runtime"
  20. "unsafe"
  21. )
  22. type SHA1Hash struct {
  23. ctx *C.EVP_MD_CTX
  24. engine *Engine
  25. }
  26. func NewSHA1Hash() (*SHA1Hash, error) { return NewSHA1HashWithEngine(nil) }
  27. func NewSHA1HashWithEngine(e *Engine) (*SHA1Hash, error) {
  28. hash := &SHA1Hash{engine: e}
  29. hash.ctx = C.X_EVP_MD_CTX_new()
  30. if hash.ctx == nil {
  31. return nil, errors.New("openssl: sha1: unable to allocate ctx")
  32. }
  33. runtime.SetFinalizer(hash, func(hash *SHA1Hash) { hash.Close() })
  34. if err := hash.Reset(); err != nil {
  35. return nil, err
  36. }
  37. return hash, nil
  38. }
  39. func (s *SHA1Hash) Close() {
  40. if s.ctx != nil {
  41. C.X_EVP_MD_CTX_free(s.ctx)
  42. s.ctx = nil
  43. }
  44. }
  45. func engineRef(e *Engine) *C.ENGINE {
  46. if e == nil {
  47. return nil
  48. }
  49. return e.e
  50. }
  51. func (s *SHA1Hash) Reset() error {
  52. if 1 != C.X_EVP_DigestInit_ex(s.ctx, C.X_EVP_sha1(), engineRef(s.engine)) {
  53. return errors.New("openssl: sha1: cannot init digest ctx")
  54. }
  55. return nil
  56. }
  57. func (s *SHA1Hash) Write(p []byte) (n int, err error) {
  58. if len(p) == 0 {
  59. return 0, nil
  60. }
  61. if 1 != C.X_EVP_DigestUpdate(s.ctx, unsafe.Pointer(&p[0]),
  62. C.size_t(len(p))) {
  63. return 0, errors.New("openssl: sha1: cannot update digest")
  64. }
  65. return len(p), nil
  66. }
  67. func (s *SHA1Hash) Sum() (result [20]byte, err error) {
  68. if 1 != C.X_EVP_DigestFinal_ex(s.ctx,
  69. (*C.uchar)(unsafe.Pointer(&result[0])), nil) {
  70. return result, errors.New("openssl: sha1: cannot finalize ctx")
  71. }
  72. return result, s.Reset()
  73. }
  74. func SHA1(data []byte) (result [20]byte, err error) {
  75. hash, err := NewSHA1Hash()
  76. if err != nil {
  77. return result, err
  78. }
  79. defer hash.Close()
  80. if _, err := hash.Write(data); err != nil {
  81. return result, err
  82. }
  83. return hash.Sum()
  84. }