Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miguelmota/fe6d4c2c1b5286731e5e9352937f5ca9 to your computer and use it in GitHub Desktop.
Save miguelmota/fe6d4c2c1b5286731e5e9352937f5ca9 to your computer and use it in GitHub Desktop.
Ethereum openssl generate public address from hex private key
ethereum_hex_private_key_to_pem() {
local private_key_hex="$1"
# Wrap the private key in ASN.1 structure and pass directly to openssl
echo "302e0201010420$private_key_hex a00706052b8104000a" | \
xxd -r -p | openssl ec -inform DER -outform PEM 2>/dev/null
}
ethereum_generate_address_from_private_key() {
private_key_hex="$1"
# Convert the hexadecimal private key into PEM format using the helper function
local priv_pem=$(ethereum_hex_private_key_to_pem $private_key_hex)
# Use OpenSSL to parse the PEM private key and extract its details (private key, public key, curve info)
local key=$(openssl ec -in <(echo "$priv_pem") -text -noout 2>/dev/null)
# Extract and clean the public key
local pub=$(echo "$key" | grep pub -A 5 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^04//')
# Extract and clean the private key
local priv=$(echo "$key" | grep priv -A 3 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^00//')
# Generate the address
local address=0x$(echo "$pub" | keccak-256sum -x -l | tr -d ' -' | tail -c 41)
# Print the results
echo "$address"
}
# Example
# $ ethereum_generate_address_from_private_key 5daeb76a04fb1f7c2e25947db20f444ac153e253b105c9d9ac6901c64b661c11
# 0xda946d75f03f0e934abfcabd3b6ab79b67e944d2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment