Cloak/internal/multiplex/crypto.go

94 lines
1.8 KiB
Go
Raw Normal View History

2019-06-09 11:05:41 +00:00
package multiplex
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
2019-06-14 10:26:26 +00:00
"golang.org/x/crypto/chacha20poly1305"
2019-06-09 11:05:41 +00:00
)
type Crypto interface {
encrypt([]byte, []byte) ([]byte, error)
decrypt([]byte, []byte) ([]byte, error)
2019-06-09 11:05:41 +00:00
}
type Plain struct{}
func (p *Plain) encrypt(plaintext []byte, nonce []byte) ([]byte, error) {
salt := make([]byte, 16)
rand.Read(salt)
return append(plaintext, salt...), nil
2019-06-09 11:05:41 +00:00
}
func (p *Plain) decrypt(buf []byte, nonce []byte) ([]byte, error) {
2019-06-09 14:03:28 +00:00
return buf, nil
2019-06-09 11:05:41 +00:00
}
type AES struct {
cipher cipher.Block
}
func MakeAESCipher(key []byte) (*AES, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ret := AES{
c,
}
return &ret, nil
}
func (a *AES) encrypt(plaintext []byte, nonce []byte) ([]byte, error) {
2019-06-09 14:03:28 +00:00
aesgcm, err := cipher.NewGCM(a.cipher)
if err != nil {
return nil, err
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
ret := make([]byte, len(plaintext)+16)
copy(ret, ciphertext)
2019-06-09 14:03:28 +00:00
return ret, nil
2019-06-09 11:05:41 +00:00
}
func (a *AES) decrypt(ciphertext []byte, nonce []byte) ([]byte, error) {
2019-06-09 14:03:28 +00:00
aesgcm, err := cipher.NewGCM(a.cipher)
if err != nil {
return nil, err
}
plain, err := aesgcm.Open(nil, nonce, ciphertext, nil)
2019-06-09 14:03:28 +00:00
if err != nil {
return nil, err
}
return plain, nil
2019-06-09 11:05:41 +00:00
}
2019-06-14 10:26:26 +00:00
type C20P1305 struct {
cipher cipher.AEAD
}
func MakeCPCipher(key []byte) (*C20P1305, error) {
c, err := chacha20poly1305.New(key)
if err != nil {
return nil, err
}
ret := C20P1305{
c,
}
return &ret, nil
}
func (c *C20P1305) encrypt(plaintext []byte, nonce []byte) ([]byte, error) {
ciphertext := c.cipher.Seal(nil, nonce, plaintext, nil)
ret := make([]byte, len(plaintext)+16)
copy(ret, ciphertext)
return ret, nil
}
func (c *C20P1305) decrypt(ciphertext []byte, nonce []byte) ([]byte, error) {
plain, err := c.cipher.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plain, nil
}