Skip to content

Commit

Permalink
sha256_length_extension_attacks
Browse files Browse the repository at this point in the history
  • Loading branch information
Sylvain committed May 23, 2023
1 parent 9b6be54 commit b771c65
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
6 changes: 6 additions & 0 deletions blog/2023/sha256_length_extension_attacks/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,9 @@ func loadSha256(hashBytes []byte, secretKeyAndDataLength uint64) (hash *digest,

return
}

func NewSha256() *digest {
d := new(digest)
d.Reset()
return d
}
40 changes: 34 additions & 6 deletions blog/2023/sha256_length_extension_attacks/sha256.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@
package main

import (
"crypto"
// "crypto/internal/boring"
"encoding/binary"
"errors"
"hash"
)

// func init() {
// crypto.RegisterHash(crypto.SHA256, New)
// }
func init() {
crypto.RegisterHash(crypto.SHA224, New224)
crypto.RegisterHash(crypto.SHA256, New)
}

// The size of a SHA256 checksum in bytes.
const Size = 32
Expand Down Expand Up @@ -144,8 +147,16 @@ func (d *digest) Reset() {
// also implements encoding.BinaryMarshaler and
// encoding.BinaryUnmarshaler to marshal and unmarshal the internal
// state of the hash.
func NewSha256() *digest {
func New() hash.Hash {
d := new(digest)
d.Reset()
return d
}

// New224 returns a new hash.Hash computing the SHA224 checksum.
func New224() hash.Hash {
d := new(digest)
d.is224 = true
d.Reset()
return d
}
Expand All @@ -160,7 +171,6 @@ func (d *digest) Size() int {
func (d *digest) BlockSize() int { return BlockSize }

func (d *digest) Write(p []byte) (nn int, err error) {
// boring.Unreachable()
nn = len(p)
d.len += uint64(nn)
if d.nx > 0 {
Expand All @@ -184,7 +194,6 @@ func (d *digest) Write(p []byte) (nn int, err error) {
}

func (d *digest) Sum(in []byte) []byte {
// boring.Unreachable()
// Make a copy of d so that caller can keep writing and summing.
d0 := *d
hash := d0.checkSum()
Expand Down Expand Up @@ -231,3 +240,22 @@ func (d *digest) checkSum() [Size]byte {

return digest
}

// Sum256 returns the SHA256 checksum of the data.
func Sum256(data []byte) [Size]byte {
var d digest
d.Reset()
d.Write(data)
return d.checkSum()
}

// Sum224 returns the SHA224 checksum of the data.
func Sum224(data []byte) [Size224]byte {
var d digest
d.is224 = true
d.Reset()
d.Write(data)
sum := d.checkSum()
ap := (*[Size224]byte)(sum[:])
return *ap
}

0 comments on commit b771c65

Please sign in to comment.