Ethereum Public Key Serialization

Alright! Today we’re going to talk about something that might make your head spin Ethereum Public Key Serialization. But don’t worry, I’m here to break it down for you in a way that won’t give you a migraine.

To begin with, let’s start with the basics. In cryptography, a public key is essentially a fancy math equation that allows someone else (like your bank) to encrypt data so only you can decipher it using your private key. It’s like having a secret handshake or code word that nobody else knows but you and your trusted partner.

Now, in Ethereum specifically, public keys are used for something called account addresses which is just a fancy way of saying “your wallet.” When you send Ether (or any other cryptocurrency) to someone’s address, it gets stored in their digital wallet until they decide to spend it.

So how do we convert our private key into an Ethereum public key? Well, that’s where the magic happens! We use a fancy algorithm called Elliptic Curve Cryptography (ECC) to generate a point on a mathematical curve which is essentially what makes up your public key.

In order for our public keys to be compatible with Ethereum, we need to serialize them into a specific format called the “uncompressed” or “extended” form. This involves adding some extra bytes at the beginning of the point coordinates (x and y) to indicate that it’s an uncompressed key.

Here’s what this looks like in code:

# Require the 'eth' and 'securerandom' libraries
require 'eth'
require 'securerandom'

# Generate a random private key using SecureRandom library
secret = SecureRandom.hex(32)

# Create a new Eth::Key object with the generated private key
key = Eth::Key.new priv: secret

# Convert the public key to a string in binary format with a length of 65 bytes
# and replace the first two characters with "0x" to indicate it is an uncompressed key
public_key = key.public_key.to_s(2, 65).gsub(/^04/, "0x")

So what’s going on here? First we require the `eth` and `securerandom` gems to generate our private key using SecureRandom (which is a fancy way of saying “super secret random number generator”).

Next, we create an Ethereum Key object with our private key. Then we convert that public key into its serialized form by converting it from binary format (2) to hexadecimal format (65), and then prepending the prefix byte `0x` to indicate that it’s a hex string.

You now have an Ethereum public key in serialized form, ready for use with your favorite wallet or blockchain explorer.

If you’re still feeling a bit confused, don’t worry! Just remember that at the end of the day, all this math and code is just a fancy way to keep your money safe.

SICORPS