|
| 1 | +package tlsh |
| 2 | + |
| 3 | +import ( |
| 4 | + "hash" |
| 5 | +) |
| 6 | + |
| 7 | +var _ hash.Hash = &TLSH{} |
| 8 | + |
| 9 | +func (t *TLSH) Reset() { |
| 10 | + t.checksum = byte(0) |
| 11 | + t.lValue = 0 |
| 12 | + t.q1Ratio = 0 |
| 13 | + t.q2Ratio = 0 |
| 14 | + t.qRatio = 0 |
| 15 | + t.code = [codeSize]byte{} |
| 16 | + t.state = chunkState{ |
| 17 | + buckets: [numBuckets]uint{}, |
| 18 | + chunk: [windowLength]byte{}, |
| 19 | + chunkSlice: []byte{}, |
| 20 | + fileSize: 0, |
| 21 | + checksum: byte(0), |
| 22 | + chunk3: &[3]byte{}, |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func (t *TLSH) BlockSize() int { |
| 27 | + return 1 |
| 28 | +} |
| 29 | + |
| 30 | +func (t *TLSH) Size() int { |
| 31 | + return len(t.Binary()) |
| 32 | +} |
| 33 | + |
| 34 | +func (t *TLSH) Sum(b []byte) []byte { |
| 35 | + q1, q2, q3 := quartilePoints(t.state.buckets) |
| 36 | + q1Ratio := byte(float32(q1)*100/float32(q3)) % 16 |
| 37 | + q2Ratio := byte(float32(q2)*100/float32(q3)) % 16 |
| 38 | + qRatio := ((q1Ratio & 0xF) << 4) | (q2Ratio & 0xF) |
| 39 | + |
| 40 | + biHash := bucketsBinaryRepresentation(t.state.buckets, q1, q2, q3) |
| 41 | + |
| 42 | + *t = *new(t.state.checksum, lValue(t.state.fileSize), q1Ratio, q2Ratio, qRatio, biHash, t.state) |
| 43 | + return t.Binary() |
| 44 | +} |
| 45 | + |
| 46 | +func (t *TLSH) Write(p []byte) (int, error) { |
| 47 | + t.state.fileSize += len(p) |
| 48 | + if len(t.state.chunkSlice) < windowLength { |
| 49 | + missing := windowLength - len(t.state.chunkSlice) |
| 50 | + switch { |
| 51 | + case len(p) < missing: |
| 52 | + t.state.chunkSlice = append(t.state.chunkSlice, p...) |
| 53 | + return len(p), nil |
| 54 | + default: |
| 55 | + t.state.chunkSlice = append(t.state.chunkSlice, p[0:missing]...) |
| 56 | + p = p[missing:] |
| 57 | + copy(t.state.chunk[:], t.state.chunkSlice[0:5]) |
| 58 | + t.state.chunk = reverse(t.state.chunk) |
| 59 | + t.state.process() |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + for _, b := range p { |
| 64 | + t.state.chunk[0] = b |
| 65 | + t.state.process() |
| 66 | + } |
| 67 | + |
| 68 | + return len(p), nil |
| 69 | +} |
0 commit comments