Commit fa7e46c8 authored by Rob Pike's avatar Rob Pike

crypto/sha512: provide top-level Sum512 and Sum384 functions

Makes it easy to ask the simple question, what is the hash of this data?
Also fix the commentary and prints in Sum256.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/10630043
parent 5cd5d889
......@@ -179,7 +179,7 @@ func (d *digest) checkSum() [Size]byte {
return digest
}
// Sum returns the SHA256 checksum of the data.
// Sum256 returns the SHA256 checksum of the data.
func Sum256(data []byte) [Size]byte {
var d digest
d.Reset()
......
......@@ -90,7 +90,7 @@ func TestGolden(t *testing.T) {
g := golden[i]
s := fmt.Sprintf("%x", Sum256([]byte(g.in)))
if s != g.out {
t.Fatalf("Sum function: sha256(%s) = %s want %s", g.in, s, g.out)
t.Fatalf("Sum256 function: sha256(%s) = %s want %s", g.in, s, g.out)
}
c := New()
for j := 0; j < 3; j++ {
......
......@@ -135,7 +135,14 @@ func (d0 *digest) Sum(in []byte) []byte {
// Make a copy of d0 so that caller can keep writing and summing.
d := new(digest)
*d = *d0
hash := d.checkSum()
if d.is384 {
return append(in, hash[:Size384]...)
}
return append(in, hash[:]...)
}
func (d *digest) checkSum() [Size]byte {
// Padding. Add a 1 bit and 0 bits until 112 bytes mod 128.
len := d.len
var tmp [128]byte
......@@ -158,10 +165,8 @@ func (d0 *digest) Sum(in []byte) []byte {
}
h := d.h[:]
size := Size
if d.is384 {
h = d.h[:6]
size = Size384
}
var digest [Size]byte
......@@ -176,5 +181,24 @@ func (d0 *digest) Sum(in []byte) []byte {
digest[i*8+7] = byte(s)
}
return append(in, digest[:size]...)
return digest
}
// Sum returns the SHA512 checksum of the data.
func Sum512(data []byte) [Size]byte {
var d digest
d.Reset()
d.Write(data)
return d.checkSum()
}
// Sum384 returns the SHA384 checksum of the data.
func Sum384(data []byte) (sum384 [Size384]byte) {
var d digest
d.is384 = true
d.Reset()
d.Write(data)
sum := d.checkSum()
copy(sum384[:], sum[:Size384])
return
}
......@@ -88,6 +88,10 @@ var golden384 = []sha512Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
g := golden[i]
s := fmt.Sprintf("%x", Sum512([]byte(g.in)))
if s != g.out {
t.Fatalf("Sum512 function: sha512(%s) = %s want %s", g.in, s, g.out)
}
c := New()
for j := 0; j < 3; j++ {
if j < 2 {
......@@ -106,6 +110,10 @@ func TestGolden(t *testing.T) {
}
for i := 0; i < len(golden384); i++ {
g := golden384[i]
s := fmt.Sprintf("%x", Sum384([]byte(g.in)))
if s != g.out {
t.Fatalf("Sum384 function: sha384(%s) = %s want %s", g.in, s, g.out)
}
c := New384()
for j := 0; j < 3; j++ {
if j < 2 {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment