# Calculate shared key having A public Key and B private Key (Diffie Hellman)

I cannot understand how this works.

$$\text{A}_\text{public} = g^a \bmod p$$

$$\text{B}_\text{private} = \text{B}$$

$$\text{g} = p$$

I also have $$p$$, I need to get the shared key, that I know both $$\text{A}$$ and $$\text{B}$$ get exactly the same value. Im not understanding how can I get the shared key that $$\text{B}$$ generated only having those variables I wrote above.

Also I know that the shared key is $$\text{g}^\text{ab} \bmod p$$, how can I get that $$\text{b}$$ value?

$$\text{B}_\text{private}$$ is $$\text{b}$$ and $$\text{B}_\text{public}$$ is $$\text{g}^\text{b} \bmod p$$.

So $$\text{B}$$ can compute $$(\text{A}_\text{public})^b \bmod p = \text{g}^{\text{ab}} \bmod p$$

• thanks, how am I supposed to calculate that with a 617 digit p? its very large and this is not working Aug 27 '19 at 13:16
• In Python you can use $\mathrm{pow}(\mathrm{publicA}, b, p)$. For others, you can use big numbers library like GMP.
– user69015
Aug 27 '19 at 13:19
• I feel like a complete stupid, I love you guys! Thanks for the help, for real. Aug 27 '19 at 13:27
• The library has vulnerable to timing/power attacks. It is not designed against. Aug 27 '19 at 16:26
• @Conrado For cryptographic purpose, it is better that computations (multiplication, squaring, inversion) are done in constant-time to avoid leaking information. Thanks kelalaka for pointing that.
– user69015
Aug 27 '19 at 17:05