diff --git a/cry/enc.go b/cry/enc.go index 907725c6..1c3bce62 100644 --- a/cry/enc.go +++ b/cry/enc.go @@ -114,10 +114,13 @@ func (e Enc) Encrypt(plainTextMsg string) (encryptedMsg []byte) { // Select a random nonce. // https://github.com/golang/crypto/blob/v0.26.0/chacha20poly1305/chacha20poly1305_test.go#L222 - nonce := random(chacha20poly1305.NonceSizeX, chacha20poly1305.NonceSizeX) + nonce := random( + chacha20poly1305.NonceSizeX, + chacha20poly1305.NonceSizeX+len(msgToEncrypt)+chacha20poly1305.Overhead, + ) - // Encrypt while reusing plaintext's storage for the encrypted output. - encrypted := e.aead.Seal(msgToEncrypt[:0], nonce, msgToEncrypt, nil) + // Encrypt the message and append the ciphertext to the nonce. + encrypted := e.aead.Seal(nonce, nonce, msgToEncrypt, nil) // Append the salt & nonce to encrypted msg. // |salt|nonce|encryptedMsg| @@ -127,10 +130,9 @@ func (e Enc) Encrypt(plainTextMsg string) (encryptedMsg []byte) { // // "salt does not need to be secret." // see: https://crypto.stackexchange.com/a/99502 - nonce, + e.salt, encrypted..., ) - encrypted = append(e.salt, encrypted...) return encrypted } diff --git a/new.txt b/new.txt index 9a40f4cf..613bd738 100644 --- a/new.txt +++ b/new.txt @@ -2,15 +2,15 @@ goos: linux goarch: amd64 pkg: github.com/komuw/ong/cry cpu: Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz -BenchmarkEnc-4 198574 5729 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 196320 6186 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 182754 6660 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 197444 5698 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 208227 5659 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 205922 5794 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 206336 5606 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 222356 5653 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 198865 6238 ns/op 728 B/op 16 allocs/op -BenchmarkEnc-4 186834 5660 ns/op 728 B/op 16 allocs/op +BenchmarkEnc-4 168698 5992 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 204858 5794 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 207462 5717 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 193176 5851 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 167646 6160 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 210864 5449 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 201039 5514 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 162837 6249 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 212643 5664 ns/op 672 B/op 14 allocs/op +BenchmarkEnc-4 188997 5665 ns/op 672 B/op 14 allocs/op PASS -ok github.com/komuw/ong/cry 16.162s +ok github.com/komuw/ong/cry 15.550s