Skip to content

Instantly share code, notes, and snippets.

@teghnet
Created August 19, 2024 12:07
Show Gist options
  • Save teghnet/00346506059c8732ae99871f1bbe7489 to your computer and use it in GitHub Desktop.
Save teghnet/00346506059c8732ae99871f1bbe7489 to your computer and use it in GitHub Desktop.
Encryption and Decryption
package main
import (
"crypto/ecdsa"
"crypto/rand"
"fmt"
"log"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/ecies"
)
func Encrypt(pubKey *ecdsa.PublicKey, plaintext string) (string, error) {
ciphertext, err := ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pubKey), []byte(plaintext), nil, nil)
if err != nil {
return "", fmt.Errorf("failed to encrypt plaintext: %w", err)
}
return hexutil.Encode(ciphertext), nil
}
func Decrypt(privKey *ecdsa.PrivateKey, ciphertextHex string) (string, error) {
ciphertext, err := hexutil.Decode(ciphertextHex)
if err != nil {
return "", fmt.Errorf("invalid secret format: should be a hex string: %w", err)
}
plaintext, err := ecies.ImportECDSA(privKey).Decrypt(ciphertext, nil, nil)
if err != nil {
return "", fmt.Errorf("failed to decrypt ciphertext: %w", err)
}
return string(plaintext), nil
}
func privKey(privateKeyHex string) (*ecdsa.PrivateKey, error) {
pkBytes, err := hexutil.Decode(privateKeyHex)
if err != nil {
return nil, fmt.Errorf("invalid key format: should be a hex string: %w", err)
}
ecdsaKey, err := crypto.ToECDSA(pkBytes)
if err != nil {
return nil, fmt.Errorf("invalid key format: not a private key: %w", err)
}
return ecdsaKey, nil
}
func main() {
privKey, err := privKey("0x5868d854a3945327e4ab9a99b961779a4a7f7057acac66b33ba2a71f55d7648c")
if err != nil {
log.Fatalf("Failed to load private key: %v", err)
}
plaintext := "Hello, Ethereum!"
encrypted, err := Encrypt(&privKey.PublicKey, plaintext)
if err != nil {
log.Fatalf("Encryption failed: %v", err)
}
fmt.Printf("Encrypted: %s\n", encrypted)
decrypted, err := Decrypt(privKey, encrypted)
if err != nil {
log.Fatalf("Decryption failed: %v", err)
}
fmt.Printf("Decrypted: %s\n", decrypted)
}
func GetPublicKeyFromAddress(address string) (string, error) {
// Convert the address to bytes
addressBytes := common.HexToAddress(address).Bytes()
// Derive the public key from the address
publicKey, err := crypto.Ecrecover(addressBytes, nil) // nil is the signature and has to be provided
if err != nil {
return "", fmt.Errorf("failed to derive public key: %w", err)
}
// Convert the public key to a hex string
publicKeyHex := common.Bytes2Hex(publicKey)
return publicKeyHex, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment