sha256.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 SHA256Hash struct {
  23. ctx *C.EVP_MD_CTX
  24. engine *Engine
  25. }
  26. func NewSHA256Hash() (*SHA256Hash, error) { return NewSHA256HashWithEngine(nil) }
  27. func NewSHA256HashWithEngine(e *Engine) (*SHA256Hash, error) {
  28. hash := &SHA256Hash{engine: e}
  29. hash.ctx = C.X_EVP_MD_CTX_new()
  30. if hash.ctx == nil {
  31. return nil, errors.New("openssl: sha256: unable to allocate ctx")
  32. }
  33. runtime.SetFinalizer(hash, func(hash *SHA256Hash) { hash.Close() })
  34. if err := hash.Reset(); err != nil {
  35. return nil, err
  36. }
  37. return hash, nil
  38. }
  39. func (s *SHA256Hash) Close() {
  40. if s.ctx != nil {
  41. C.X_EVP_MD_CTX_free(s.ctx)
  42. s.ctx = nil
  43. }
  44. }
  45. func (s *SHA256Hash) Reset() error {
  46. if 1 != C.X_EVP_DigestInit_ex(s.ctx, C.X_EVP_sha256(), engineRef(s.engine)) {
  47. return errors.New("openssl: sha256: cannot init digest ctx")
  48. }
  49. return nil
  50. }
  51. func (s *SHA256Hash) Write(p []byte) (n int, err error) {
  52. if len(p) == 0 {
  53. return 0, nil
  54. }
  55. if 1 != C.X_EVP_DigestUpdate(s.ctx, unsafe.Pointer(&p[0]),
  56. C.size_t(len(p))) {
  57. return 0, errors.New("openssl: sha256: cannot update digest")
  58. }
  59. return len(p), nil
  60. }
  61. func (s *SHA256Hash) Sum() (result [32]byte, err error) {
  62. if 1 != C.X_EVP_DigestFinal_ex(s.ctx,
  63. (*C.uchar)(unsafe.Pointer(&result[0])), nil) {
  64. return result, errors.New("openssl: sha256: cannot finalize ctx")
  65. }
  66. return result, s.Reset()
  67. }
  68. func SHA256(data []byte) (result [32]byte, err error) {
  69. hash, err := NewSHA256Hash()
  70. if err != nil {
  71. return result, err
  72. }
  73. defer hash.Close()
  74. if _, err := hash.Write(data); err != nil {
  75. return result, err
  76. }
  77. return hash.Sum()
  78. }