I am writing a test harness in java for an existing program. As part of this i need to generate a Diffie Hellman key pair and pass the public key to the other program in its raw (i.e unencoded bytes) form.
I can successfully the key pair using the following code:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair dkp = kpg.generateKeyPair();
However, i cannot seem to retrieve the raw byte value of the keys :-( Calling dkp.getPublic().getEncoded()
returns a byte array but its of the Key in an x509 encoded format.
Three possible ways forward occur to me:
But im not how to go about doing any of them (and which will turn out to be best)?
Any help or advice would be greatly appreciated!
The formula to calculate the key is K = (Yb)Xa mod q. For the receiver, you need the private key (Ya), sender's public key (Xb), and the original q. The formula to calculate the secret key is K = (Ya)Xb mod q. If both the values of K generated are equal, the Diffie-Hellman key exchange algorithm is complete.
Step 1: Alice and Bob get public numbers P = 23, G = 9 Step 2: Alice selected a private key a = 4 and Bob selected a private key b = 3 Step 3: Alice and Bob compute public values Alice: x =(9^4 mod 23) = (6561 mod 23) = 6 Bob: y = (9^3 mod 23) = (729 mod 23) = 16 Step 4: Alice and Bob exchange public numbers Step 5: ...
The Diffie–Hellman (DH) Algorithm is a key-exchange protocol that enables two parties communicating over public channel to establish a mutual secret without it being transmitted over the Internet. DH enables the two to use a public key to encrypt and decrypt their conversation or data using symmetric cryptography.
The Diffie-Hellman (DH) method of authenticating a user is nontrivial for an intruder to crack. The client and the server each have their own private key (sometimes called a secret key) which they use together with the public key to devise a common key.
You can get the X and Y (where Y = G^X mod P
) values like this:
BigInteger x = ((javax.crypto.interfaces.DHPrivateKey) dkp.getPrivate()).getX();
BigInteger y = ((javax.crypto.interfaces.DHPublicKey) dkp.getPublic()).getY();
You can get the G and P values from either the public or private key like this:
DHParameterSpec params =
((javax.crypto.interfaces.DHPublicKey) dkp.getPublic()).getParams();
BigInteger p = params.getP();
BigInteger g = params.getG();
From there you can get them all as raw byte arrays:
byte[] xBytes = x.toByteArray();
byte[] yBytes = y.toByteArray();
byte[] pBytes = p.toByteArray();
byte[] gBytes = g.toByteArray();
The combination of Y, P, and G make the public key. X should be kept secret.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With