tunnel: reduce allocation and improve performance (#1320)
* tunnel: reduce allocation and improve performance BenchmarkSha256Old-16 100000 156748 ns/op 11835 B/op 168 allocs/op BenchmarkSha256Old-16 100000 156229 ns/op 11819 B/op 168 allocs/op BenchmarkSha256New-16 100000 154751 ns/op 11107 B/op 161 allocs/op BenchmarkSha256New-16 100000 154263 ns/op 11110 B/op 161 allocs/op simple change lowers allocations and brings performance Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * fix Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * tunnel: reuse buf in Decrypt Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * fix unneeded conversations Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * base32 string is smaller than hex string Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
@@ -14,22 +14,17 @@ var (
|
||||
// gcmStandardNonceSize from crypto/cipher/gcm.go is 12 bytes
|
||||
// 100 - is max size of pool
|
||||
noncePool = bpool.NewBytePool(100, 12)
|
||||
hashPool = bpool.NewBytePool(1024*32, 32)
|
||||
)
|
||||
|
||||
// hash hahes the data into 32 bytes key and returns it
|
||||
// hash uses sha256 underneath to hash the supplied key
|
||||
func hash(key string) []byte {
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(key))
|
||||
out := hashPool.Get()
|
||||
defer hashPool.Put(out[:0])
|
||||
out = hasher.Sum(out[:0])
|
||||
return out
|
||||
func hash(key []byte) []byte {
|
||||
sum := sha256.Sum256(key)
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// Encrypt encrypts data and returns the encrypted data
|
||||
func Encrypt(data []byte, key string) ([]byte, error) {
|
||||
func Encrypt(data []byte, key []byte) ([]byte, error) {
|
||||
// generate a new AES cipher using our 32 byte key
|
||||
c, err := aes.NewCipher(hash(key))
|
||||
if err != nil {
|
||||
@@ -59,7 +54,7 @@ func Encrypt(data []byte, key string) ([]byte, error) {
|
||||
}
|
||||
|
||||
// Decrypt decrypts the payload and returns the decrypted data
|
||||
func Decrypt(data []byte, key string) ([]byte, error) {
|
||||
func Decrypt(data []byte, key []byte) ([]byte, error) {
|
||||
// generate AES cipher for decrypting the message
|
||||
c, err := aes.NewCipher(hash(key))
|
||||
if err != nil {
|
||||
@@ -81,10 +76,10 @@ func Decrypt(data []byte, key string) ([]byte, error) {
|
||||
// NOTE: we need to parse out nonce from the payload
|
||||
// we prepend the nonce to every encrypted payload
|
||||
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
ciphertext, err = gcm.Open(ciphertext[:0], nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user