| 1 | package csblob |
| 2 | |
| 3 | import ( |
| 4 | "crypto" |
| 5 | "fmt" |
| 6 | "hash" |
| 7 | "io" |
| 8 | ) |
| 9 | |
| 10 | type HashType uint8 |
| 11 | |
| 12 | // CSCommon.h |
| 13 | const ( |
| 14 | HashNone HashType = iota |
| 15 | HashSHA1 |
| 16 | HashSHA256 |
| 17 | HashSHA256Truncated |
| 18 | HashSHA384 |
| 19 | HashSHA512 |
| 20 | ) |
| 21 | |
| 22 | func hashFunc(hashType HashType, hashLen uint8) (h crypto.Hash, err error) { |
| 23 | switch hashType { |
| 24 | case HashSHA1: |
| 25 | h = crypto.SHA1 |
| 26 | case HashSHA256: |
| 27 | h = crypto.SHA256 |
| 28 | case HashSHA384: |
| 29 | h = crypto.SHA384 |
| 30 | } |
| 31 | if h == 0 { |
| 32 | err = fmt.Errorf("unknown hash type %d", err) |
| 33 | } else if h.Size() != int(hashLen) { |
| 34 | err = fmt.Errorf("expected size %d for hash %d (%s) but got %d", h.Size(), hashType, h, hashLen) |
| 35 | } |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | func hashType(h crypto.Hash) (HashType, error) { |
| 40 | switch h { |
| 41 | case crypto.SHA1: |
| 42 | return HashSHA1, nil |
| 43 | case crypto.SHA256: |
| 44 | return HashSHA256, nil |
| 45 | case crypto.SHA384: |
| 46 | return HashSHA384, nil |
| 47 | default: |
| 48 | return 0, fmt.Errorf("unsupported hash type %s", h) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func hashPages(hashFuncs []crypto.Hash, pages io.Reader, singlePage bool) (slots [][]byte, slotCount uint32, codeLimit int64, err error) { |
| 53 | hashers := make([]hash.Hash, len(hashFuncs)) |
| 54 | writers := make([]io.Writer, len(hashFuncs)) |
| 55 | slots = make([][]byte, len(hashFuncs)) |
| 56 | for i, f := range hashFuncs { |
| 57 | hashers[i] = f.New() |
| 58 | writers[i] = hashers[i] |
| 59 | } |
| 60 | if singlePage { |
| 61 | codeLimit, err = io.Copy(io.MultiWriter(writers...), pages) |
| 62 | if err != nil { |
| 63 | return |
| 64 | } |
| 65 | for i, h := range hashers { |
| 66 | slots[i] = h.Sum(nil) |
| 67 | } |
| 68 | slotCount = 1 |
| 69 | return |
| 70 | } |
| 71 | buf := make([]byte, 1<<defaultPageSizeLog2) |
| 72 | for { |
| 73 | var n int |
| 74 | n, err = io.ReadFull(pages, buf) |
| 75 | if n <= 0 { |
| 76 | if err == io.EOF { |
| 77 | err = nil |
| 78 | } |
| 79 | return |
| 80 | } |
| 81 | for i, h := range hashers { |
| 82 | h.Reset() |
| 83 | h.Write(buf[:n]) |
| 84 | slots[i] = h.Sum(slots[i]) |
| 85 | } |
| 86 | codeLimit += int64(n) |
| 87 | slotCount++ |
| 88 | } |
| 89 | } |