kraken
1// Copyright (c) 2016-2019 Uber Technologies, Inc.
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.
14package core15
16import (17"crypto"18"encoding/hex"19"hash"20"io"21)
22
23const (24// SHA256 is the only algorithm supported.25SHA256 = "sha256"26)
27
28// Digester calculates the digest of data stream.
29type Digester struct {30hash hash.Hash31}
32
33// NewDigester instantiates and returns a new Digester object.
34func NewDigester() *Digester {35return &Digester{36hash: crypto.SHA256.New(),37}38}
39
40// Digest returns the digest of existing data.
41func (d *Digester) Digest() Digest {42digest, err := NewSHA256DigestFromHex(hex.EncodeToString(d.hash.Sum(nil)))43if err != nil {44// This should never fail.45panic(err)46}47return digest48}
49
50// FromReader returns the digest of data from reader.
51func (d Digester) FromReader(rd io.Reader) (Digest, error) {52if _, err := io.Copy(d.hash, rd); err != nil {53return Digest{}, err54}55
56return d.Digest(), nil57}
58
59// FromBytes digests the input and returns a Digest.
60func (d Digester) FromBytes(p []byte) (Digest, error) {61if _, err := d.hash.Write(p); err != nil {62return Digest{}, err63}64
65return d.Digest(), nil66}
67
68// Tee allows d to calculate a digest of r while the caller reads from the
69// returned reader.
70func (d Digester) Tee(r io.Reader) io.Reader {71return io.TeeReader(r, d.hash)72}
73