2019-06-09 11:05:41 +00:00
|
|
|
package multiplex
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
|
|
|
"crypto/rand"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Crypto interface {
|
2019-06-14 09:48:59 +00:00
|
|
|
encrypt([]byte, []byte) ([]byte, error)
|
|
|
|
decrypt([]byte, []byte) ([]byte, error)
|
2019-06-09 11:05:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Plain struct{}
|
|
|
|
|
2019-06-14 09:48:59 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-06-14 09:48:59 +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
|
|
|
|
}
|
|
|
|
|
2019-06-14 09:48:59 +00:00
|
|
|
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)
|
2019-06-14 09:48:59 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-06-14 09:48:59 +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
|
|
|
|
}
|
2019-06-14 09:48:59 +00:00
|
|
|
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
|
|
|
}
|