Skip to content

Commit

Permalink
sha: add WriteString and WriteByte method
Browse files Browse the repository at this point in the history
  • Loading branch information
qmuntal committed Apr 18, 2023
1 parent fc045de commit 6755754
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
20 changes: 20 additions & 0 deletions openssl/sha.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,26 @@ func (h *evpHash) Write(p []byte) (int, error) {
return len(p), nil
}

func (h *evpHash) WriteString(s string) (int, error) {
// TODO: use unsafe.StringData once we drop support
// for go1.19 and earlier.
hdr := (*struct {
Data *byte
Len int
})(unsafe.Pointer(&s))
if len(s) > 0 && C.go_openssl_EVP_DigestUpdate(h.ctx, unsafe.Pointer(hdr.Data), C.size_t(len(s))) == 0 {
panic("openssl: EVP_DigestUpdate failed")
}
return len(s), nil
}

func (h *evpHash) WriteByte(c byte) error {
if C.go_openssl_EVP_DigestUpdate(h.ctx, unsafe.Pointer(&c), 1) == 0 {
panic("openssl: EVP_DigestUpdate failed")
}
return nil
}

func (h *evpHash) Size() int {
return h.size
}
Expand Down
18 changes: 18 additions & 0 deletions openssl/sha_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"bytes"
"encoding"
"hash"
"io"
"testing"
)

Expand Down Expand Up @@ -62,6 +63,23 @@ func TestSha(t *testing.T) {
if !bytes.Equal(sum, initSum) {
t.Errorf("got:%x want:%x", sum, initSum)
}

bw := h.(io.ByteWriter)
for i := 0; i < len(msg); i++ {
bw.WriteByte(msg[i])
}
h.Reset()
sum = h.Sum(nil)
if !bytes.Equal(sum, initSum) {
t.Errorf("got:%x want:%x", sum, initSum)
}

h.(io.StringWriter).WriteString(string(msg))
h.Reset()
sum = h.Sum(nil)
if !bytes.Equal(sum, initSum) {
t.Errorf("got:%x want:%x", sum, initSum)
}
})
}
}
Expand Down

0 comments on commit 6755754

Please sign in to comment.