The Prime number and the Generator are not sensitive or secret. Meaning, the two parties can share them over an unsecured medium with no risk.
This article covers how the exchange works, and provides a number calculation example where two parties attain the same shared secret, which is unattainable if you had all the numbers that were shared over the unsecured medium.
Here is the illustration in that article:
The shared secret "3" can only be attained if you have either of the Private Keys (5 or 4). The values shared over the internet (13, 6, 2, 9) can not be reliably combined in such a way as to extract the shared secret (3).
And this Q&A over at the Cryptography Stack Exchange provides more explinations of how it works:
Edit: As Ricky Beam pointed out in the comments, the numbers above used in the illustration are intentionally small and simple to show you the math of the DH exchange.
This is addressed in the aforementioned article, but for the sake of simplicity I'll quote the relevant section below.
Remember, any key is susceptible to brute force. In large part, the goal of Cryptography is to use numbers and calculations so large that attempting to brute force a particular key would take an unreasonable amount of time (1,000's and 10,000's of years).
In our example, we used a Prime number of 13. Since this
Prime number is also is used as the Modulus for each calculation, the
entire key space for the resulting Shared Secret can only ever be
0-12. The bigger this number, the more difficult a time an attacker
will have in brute forcing your shared secret.
Obviously, we were using very small numbers above to help keep the
math relatively simple. True DH exchanges are doing math on numbers
which are vastly larger. There are three typical sizes to the numbers
- DH Group 1 768 bits
- DH Group 2 1024 bits
- DH Group 5 1536 bits
The bit-size is a reference to the Prime number. This directly equates
to the entire key space of the resulting Shared Secret. To give you an
idea of just how large this key space is:
- In order to fully write out a 768 bit number, you would need 232 decimal digits.
- In order to fully write out a 1024 bit number, you would need 309 decimal digits.
- In order to fully write out a 1536 bit number, you would need 463 decimal digits.
(Note, this article was written in 2015. At the current moment (2020), the key sizes above are considered too small)