Generate ECDSA signature in Ruby with a PEM file

1 minute read

Given a private key in the form of a “.pem” file and some data, how would you generate a signature using the Elliptic Curve Digital Signature Algorithm (ECDSA), in ruby?

Ruby has a EC class specifically for this in the Openssl standard library.

But the documentation wasn’t clear to me. I got it working after a few tries.

Here’s the setup where we have the data which is some random string and the pem file’s content.

data = "foo bar"
private_key ="./pivate-key.pem")

Now we can use EC to generate a binary signature.

ecdsa =
signature_in_binary = ecdsa.dsa_sign_asn1(data)

As you can see, the signature is now generated for the given data using ecdsa algorithm with the given private key.

But what if you have to send this binary data over the network reliably? We can easily do that by encoding it in base64.

signature_in_base64_encoded_string = Base64.encode64(signature_in_binary)

This can now be send as a json response from, say, a rails controller.

render json: { sign: signature_in_base64_encoded_string }, status: :ok

The actual usecase was that I was working on a client project and had to generate a signature for subscription offers configured in Apple. Apple’s page explains what needs to be done, but not how, as it’s language dependent.