Other people seem to have given good answers to the question with your generation of random numbers, so I will answer your question: "Is this right for Diffie-Hellman?"
Your understanding of Diffie-Hellman is a little from me, I think. First, you continue to use the term "private key" as if there is also a "public key". Diffie-Hellman key exchange is a method used to exchange a single symmetric key. There is no private key and no public key, there is only a key that both parties are going to use to encrypt their messages. Moreover, you said that this is the code for "generating" a key. With Diffie Hellman, he takes two tangos. This code is not enough to create the final product key. You need to send Ya to the second side and get something from this second side to complete the process. See below for more details.
Your formula for generating Ya correct, assuming Xa is what it should be. I'm a little worried about your understanding of what you should do with Xa because you reassign it to a random value after you created Ya . To create the final version of the key, you will need to insert Xa .
After you have created Ya , you must send it to the other side. The other side will return a certain number in return (let me call it R ). To create the final version of the symmetric key (call SK on it), you will need to calculate it as
SK = (int)Math.pow(R, Xa) % P;
In short, do not recount Xa after you calculate Ya , otherwise you will not be able to generate the key. The process is going on:
- Create
Ya (I just use this variable name because this is what you used). - Send
Ya someone. - Get some number from the person you sent
Ya to (called this R number in the example above). - Calculate that there should be a symmetric key that you will use for encryption using
R , Xa and P (See Formula above for SK )
source share