-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher_simple.go
87 lines (76 loc) · 2.3 KB
/
cipher_simple.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright [2020] [thinkgos] [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package encrypt
import (
"crypto/cipher"
"crypto/md5"
"crypto/rc4"
"encoding/binary"
"golang.org/x/crypto/chacha20"
"golang.org/x/crypto/salsa20/salsa"
)
// NewRc4Md5 new rc4-md5 key size should 16, iv size should one of 6,16
func NewRc4Md5(key, iv []byte) (cipher.Stream, error) {
if k := len(key); k != 16 {
return nil, KeySizeError(k)
}
if i := len(iv); i != 16 && i != 6 {
return nil, IvSizeError(i)
}
h := md5.New()
h.Write(key) // nolint: errcheck
h.Write(iv) // nolint: errcheck
return rc4.NewCipher(h.Sum(nil))
}
// NewChacha20 new chacha20 key size should 32, iv size should one of 12,24
func NewChacha20(key, iv []byte) (cipher.Stream, error) {
return chacha20.NewUnauthenticatedCipher(key, iv)
}
// NewSalsa20 new salsa20 key size should 32, iv size should one of 8
func NewSalsa20(key, iv []byte) (cipher.Stream, error) {
if k := len(key); k != 32 {
return nil, KeySizeError(k)
}
if i := len(iv); i != 8 {
return nil, IvSizeError(i)
}
var c salsaStreamCipher
copy(c.key[:], key)
copy(c.nonce[:], iv)
return &c, nil
}
type salsaStreamCipher struct {
nonce [8]byte
key [32]byte
counter int
}
func (c *salsaStreamCipher) XORKeyStream(dst, src []byte) {
var buf []byte
padLen := c.counter % 64
dataSize := len(src) + padLen
if cap(dst) >= dataSize {
buf = dst[:dataSize]
} else {
buf = make([]byte, dataSize)
}
var subNonce [16]byte
copy(subNonce[:], c.nonce[:])
binary.LittleEndian.PutUint64(subNonce[len(c.nonce):], uint64(c.counter/64))
// It's difficult to avoid data copy here. src or dst maybe slice from
// Conn.Read/Write, which can't have padding.
copy(buf[padLen:], src)
salsa.XORKeyStream(buf, buf, &subNonce, &c.key)
copy(dst, buf[padLen:])
c.counter += len(src)
}