github.com/ethersphere/bee/v2@v2.2.0/pkg/encryption/elgamal/encryption_test.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package elgamal_test 6 7 import ( 8 "bytes" 9 "crypto/rand" 10 "io" 11 "testing" 12 13 "github.com/ethersphere/bee/v2/pkg/crypto" 14 "github.com/ethersphere/bee/v2/pkg/encryption/elgamal" 15 "github.com/ethersphere/bee/v2/pkg/swarm" 16 ) 17 18 func TestElgamalCorrect(t *testing.T) { 19 t.Parallel() 20 21 plaintext := []byte("some highly confidential text") 22 key, err := crypto.GenerateSecp256k1Key() 23 if err != nil { 24 t.Fatal(err) 25 } 26 pub := &key.PublicKey 27 salt := make([]byte, 32) 28 if _, err := io.ReadFull(rand.Reader, salt); err != nil { 29 t.Fatal(err) 30 } 31 padding := 4032 32 enc, ephpub, err := elgamal.NewEncryptor(pub, salt, padding, swarm.NewHasher) 33 if err != nil { 34 t.Fatal(err) 35 } 36 ciphertext, err := enc.Encrypt(plaintext) 37 if err != nil { 38 t.Fatal(err) 39 } 40 if len(ciphertext) != padding { 41 t.Fatalf("ciphertext has incorrect length: expected %v, got %v", padding, len(ciphertext)) 42 } 43 44 dec, err := elgamal.NewDecrypter(key, ephpub, salt, swarm.NewHasher) 45 if err != nil { 46 t.Fatal(err) 47 } 48 expected := plaintext 49 decryptedtext, err := dec.Decrypt(ciphertext) 50 if err != nil { 51 t.Fatal(err) 52 } 53 if len(decryptedtext) != padding { 54 t.Fatalf("decrypted text has incorrect length: expected %v, got %v", padding, len(decryptedtext)) 55 } 56 plaintext = decryptedtext[:len(expected)] 57 if !bytes.Equal(plaintext, expected) { 58 t.Fatalf("original and encrypted-decrypted plaintexts do no match: expected %x, got %x", expected, plaintext) 59 } 60 61 }