-
Notifications
You must be signed in to change notification settings - Fork 24
/
cipher_chacha20poly1305.go
53 lines (41 loc) · 1.12 KB
/
cipher_chacha20poly1305.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
package ssh
import (
"golang.org/x/crypto/chacha20poly1305"
)
// Chacha20poly1305 加密/解密
type CipherChacha20poly1305 struct {
keySize int
nonceSize int
identifier string
}
// 值大小
func (this CipherChacha20poly1305) KeySize() int {
return this.keySize
}
// 块大小
func (this CipherChacha20poly1305) BlockSize() int {
return this.nonceSize
}
// 名称
func (this CipherChacha20poly1305) Name() string {
return this.identifier
}
// 加密
func (this CipherChacha20poly1305) Encrypt(key, plaintext []byte) ([]byte, error) {
nonce := key[this.keySize : this.keySize+this.nonceSize]
aead, err := chacha20poly1305.New(key[:this.keySize])
if err != nil {
return nil, err
}
ciphertext := aead.Seal(nil, nonce, plaintext, nil)
return ciphertext, nil
}
// 解密
func (this CipherChacha20poly1305) Decrypt(key, ciphertext []byte) ([]byte, error) {
nonce := key[this.keySize : this.keySize+this.nonceSize]
aead, err := chacha20poly1305.New(key[:this.keySize])
if err != nil {
return nil, err
}
return aead.Open(nil, nonce, ciphertext, nil)
}