File: data.go

package info (click to toggle)
golang-github-twstrike-otr3 0.0~git20161015.0.744856d-3.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,080 kB
  • sloc: ansic: 127; makefile: 76
file content (111 lines) | stat: -rw-r--r-- 2,254 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package otr3

import (
	"hash"
	"math/big"
	"strconv"
)

func appendWord(l []byte, r uint32) []byte {
	return append(l, byte(r>>24), byte(r>>16), byte(r>>8), byte(r))
}

func appendShort(l []byte, r uint16) []byte {
	return append(l, byte(r>>8), byte(r))
}

func appendData(l, r []byte) []byte {
	return append(appendWord(l, uint32(len(r))), r...)
}

func appendMPI(l []byte, r *big.Int) []byte {
	return appendData(l, r.Bytes())
}

func appendMPIs(l []byte, r ...*big.Int) []byte {
	for _, mpi := range r {
		l = appendMPI(l, mpi)
	}
	return l
}

func hashMPIs(h hash.Hash, magic byte, mpis ...*big.Int) []byte {
	h.Reset()
	h.Write([]byte{magic})
	for _, mpi := range mpis {
		h.Write(appendMPI(nil, mpi))
	}
	return h.Sum(nil)
}

func hashMPIsBN(h hash.Hash, magic byte, mpis ...*big.Int) *big.Int {
	return new(big.Int).SetBytes(hashMPIs(h, magic, mpis...))
}

func extractWord(d []byte) ([]byte, uint32, bool) {
	if len(d) < 4 {
		return nil, 0, false
	}

	return d[4:], uint32(d[0])<<24 |
		uint32(d[1])<<16 |
		uint32(d[2])<<8 |
		uint32(d[3]), true
}

func extractMPI(d []byte) (newPoint []byte, mpi *big.Int, ok bool) {
	d, mpiLen, ok := extractWord(d)
	if !ok || len(d) < int(mpiLen) {
		return nil, nil, false
	}

	mpi = new(big.Int).SetBytes(d[:int(mpiLen)])
	newPoint = d[int(mpiLen):]
	ok = true
	return
}

func extractMPIs(d []byte) ([]byte, []*big.Int, bool) {
	current, mpiCount, ok := extractWord(d)
	if !ok {
		return nil, nil, false
	}
	result := make([]*big.Int, int(mpiCount))
	for i := 0; i < int(mpiCount); i++ {
		current, result[i], ok = extractMPI(current)
		if !ok {
			return nil, nil, false
		}
	}
	return current, result, true
}

func extractShort(d []byte) ([]byte, uint16, bool) {
	if len(d) < 2 {
		return nil, 0, false
	}

	return d[2:], uint16(d[0])<<8 |
		uint16(d[1]), true
}

func extractData(d []byte) (newPoint []byte, data []byte, ok bool) {
	newPoint, length, ok := extractWord(d)
	if !ok || len(newPoint) < int(length) {
		return d, nil, false
	}

	data = newPoint[:int(length)]
	newPoint = newPoint[int(length):]
	ok = true
	return
}

func bytesToUint16(d []byte) (uint16, error) {
	res, e := strconv.Atoi(string(d))
	return uint16(res), e
}

func makeCopy(i []byte) []byte {
	return append([]byte{}, i...)
}