github.com/ethersphere/bee/v2@v2.2.0/pkg/encryption/elgamal/encryption.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 6 7 import ( 8 "crypto/ecdsa" 9 "hash" 10 11 "github.com/ethersphere/bee/v2/pkg/crypto" 12 "github.com/ethersphere/bee/v2/pkg/encryption" 13 ) 14 15 // New constructs an encryption interface (the modified blockcipher) with a base key derived from 16 // a shared secret (using a private key and the counterparty's public key) hashed with a salt 17 func New(key *ecdsa.PrivateKey, pub *ecdsa.PublicKey, salt []byte, padding int, hashfunc func() hash.Hash) (encryption.Interface, error) { 18 dh := crypto.NewDH(key) 19 sk, err := dh.SharedKey(pub, salt) 20 if err != nil { 21 return nil, err 22 } 23 return encryption.New(sk, padding, 0, hashfunc), nil 24 } 25 26 // NewEncryptor constructs an El-Gamal encryptor 27 // this involves generating an ephemeral key pair the public part of which is returned 28 // as it is needed for the counterparty to decrypt 29 func NewEncryptor(pub *ecdsa.PublicKey, salt []byte, padding int, hashfunc func() hash.Hash) (encryption.Encrypter, *ecdsa.PublicKey, error) { 30 privKey, err := crypto.GenerateSecp256k1Key() 31 if err != nil { 32 return nil, nil, err 33 } 34 enc, err := New(privKey, pub, salt, padding, hashfunc) 35 if err != nil { 36 return nil, nil, err 37 } 38 return enc, &privKey.PublicKey, nil 39 } 40 41 // NewDecrypter constructs an el-Gamal decrypter the receiving party uses 42 // the public key must be the ephemeral return value of the Encrypter constructor 43 func NewDecrypter(key *ecdsa.PrivateKey, pub *ecdsa.PublicKey, salt []byte, hashfunc func() hash.Hash) (encryption.Decrypter, error) { 44 return New(key, pub, salt, 0, hashfunc) 45 }