This is the Diffie-Hellman key exchange algorithm. Diffie–Hellman key exchange establishes a shared secret between two parties that can be used for secret communication for exchanging data over a public network.
(Note: I've only written the algorithm, but not the prime root modulo number generator yet, so don't expect that lol.)