-
Notifications
You must be signed in to change notification settings - Fork 21
/
salsa20.go
73 lines (58 loc) · 1.66 KB
/
salsa20.go
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
package salsa20
import (
"errors"
"crypto/cipher"
"encoding/binary"
"golang.org/x/crypto/salsa20/salsa"
"github.com/deatil/go-cryptobin/tool/alias"
)
type Cipher struct {
nonce []byte
key [32]byte
counter uint64
}
// key is 32 bytes, nonce is 16 bytes.
func NewCipher(key, nonce []byte) (cipher.Stream, error) {
var fixedSizedKey [32]byte
if len(key) != 32 {
return nil, errors.New("cryptobin/salsa20: key size must be 32")
}
copy(fixedSizedKey[:], key)
return &Cipher{
key: fixedSizedKey,
nonce: nonce,
}, nil
}
// key is 32 bytes, nonce is 16 bytes.
func NewCipherWithCounter(key, nonce []byte, counter uint64) (cipher.Stream, error) {
var fixedSizedKey [32]byte
if len(key) != 32 {
return nil, errors.New("cryptobin/salsa20: key size must be 32")
}
copy(fixedSizedKey[:], key)
return &Cipher{
key: fixedSizedKey,
nonce: nonce,
counter: counter,
}, nil
}
func (c *Cipher) XORKeyStream(dst, src []byte) {
if len(src) == 0 {
return
}
if len(dst) < len(src) {
panic("cryptobin/salsa20: output smaller than input")
}
if alias.InexactOverlap(dst[:len(src)], src) {
panic("cryptobin/salsa20: invalid buffer overlap")
}
paddingLength := int(c.counter % 64)
buf := make([]byte, len(src)+paddingLength)
var subNonce [16]byte
copy(subNonce[:], c.nonce)
binary.LittleEndian.PutUint64(subNonce[8:], c.counter/64)
copy(buf[paddingLength:], src)
salsa.XORKeyStream(buf, buf, &subNonce, &c.key)
copy(dst, buf[paddingLength:])
c.counter += uint64(len(src))
}