# How do I add two secp256k1 keys together?

I have two public/private keypairs, A and B. I want to add them together to get a new keypair AB.

I'd also like to be able to add the public keys of A and B to get the public key of AB.

How do I do this?

• You can be more specific about what you mean by "add together"? You can literally add the two public keys and the two private keys to get a new keypair. – David Schwartz Oct 8 '15 at 23:45
• @DavidSchwartz `You can literally add the two public keys ` Yes, that's what I'm looking for. – Nick ODell Oct 9 '15 at 1:08
• If you're using OpenSSL, `EC_POINT_add`. – David Schwartz Oct 9 '15 at 3:30
• @DavidSchwartz Can I see an example ? – monkeyUser Jan 31 '19 at 0:57

Here is some python code you can reverse engineer

``````def add(p, q):
if p % P == 0 and p % P == 0:
return q
if q % P == 0 and q % P == 0:
return p

if p == q and p == q:
if p == 0:
return [0, 0]
l = (3 * p**2) * modInv((2 * p), P)
elif p == q:
return [0, 0]
else:
l = (p - q) * modInv((p - q), P)

x = l**2 - (p + q)
y = l * (p - x) - p
return [x % P, y % P]

def modInv(n, p):
return pow(n, p - 2, p)

#some constants
P = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
x = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798

#example usage of the add function
g1 = [x, y]
print "g1 = " + hex(g1) + " : " + hex(g1)

g2 = add([x, y], [x, y])
print "g2 = " + hex(g2) + " : " + hex(g2)

print "g3 = " + hex(g3) + " : " + hex(g3)

print "g4 = " + hex(g4) + " : " + hex(g4)
``````

Most ecc libraries will have this function, but if you want to program it yourself, here's what you do:

First, compute the slope of the line containing the points A and B. Let A = (X_a, Y_a) and B = (X_b, Y_b). The equation for the slope is:

s = (Y_a - Y_b) / (X_a - X_b)

The resulting point, we'll call C = (X_c, Y_c) = A+B. Doing some math, you get:

X_c = s^2 - X_a - X_b
Y_c = Y_a + s (X_c - X_a) = Y_b + s(X_c - X_b)

If X_a == X_b, then it depends on Y_a and Y_b. If Y_a == Y_b, then A and B are the same, so really, you're just computing a point doubling (2*A). If Y_a == -Y_b (the only other possibility) then A+B = the point at infinity, or the identity. Usually, that's not a very interesting point for cryptography. Computing 2*A is a little trickier, but can be done. You're already doing that when you compute the public key from the private key with G anyway, so I'll assume you have access to something that lets you double a point.

Note all the operations are all field operations, so you have to mod by P for secp256k1 (FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F in hex).