hi to all, this is my first post.... sorry for my poor English :)
i have some problems while creating the secret key with DH.... the code below (the same in Server and Client) generating an InvalidKeyException from "doPhase".
i think this isn't a transmission error, Server and Client send and receive serialized object called "pacchetto" (the Italian word for "Packet").
(in the code below i simplified the "send" and "receive" but i think this is not the problem).
i want only to print out the result secret key
private void DiffieHellman(){
String valuesInStr=genDHParams();
String[] values = valuesInStr.split(",");
BigInteger p = new BigInteger(values[0]);
BigInteger g = new BigInteger(values[1]);
int l = Integer.parseInt(values[2]);
try {
// Use the values to generate a key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
DHParameterSpec dhSpec = new DHParameterSpec(p, g, l);
keyGen.initialize(dhSpec);
KeyPair keypair = keyGen.generateKeyPair();
// Get the generated public and private keys
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
// Send the public key bytes to the other party...
stream.writeObject(new Pacchetto(publicKey));
// Retrieve the public key bytes of the other party
Pacchetto pacchetto=(PublicKey)stream.readObject();
publicKey=pacchetto.publicKey;
// Prepare to generate the secret key with the private key and public key of the other party
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(privateKey);
ka.doPhase(publicKey, true);
// Specify the type of key to generate;
// see e458 Listing All Available Symmetric Key Generators
String algorithm = "DES";
// Generate the secret key
SecretKey secretKey = ka.generateSecret(algorithm);
// Use the secret key to encrypt/decrypt data;
// see e462 Encrypting a String with DES
System.out.println( "key: "+secretKey.toString());
}
catch (InvalidKeyException e) {System.out.println(e.toString());}
catch (InvalidAlgorithmParameterException e) {System.out.println(e.toString());
} catch (NoSuchAlgorithmException e) {System.out.println(e.toString());
} catch (IOException ex){ System.out.println(ex.toString());
} catch (ClassNotFoundException ex){System.out.println(ex.toString());
}
}
private static String genDHParams() {
try {
// Create the parameter generator for a 1024-bit DH key pair
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(1024);
// Generate the parameters
AlgorithmParameters params = paramGen.generateParameters();
DHParameterSpec dhSpec
= (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
// Return the three values in a string
return ""+dhSpec.getP()+","+dhSpec.getG()+","+dhSpec.getL();
} catch (NoSuchAlgorithmException e) {
} catch (InvalidParameterSpecException e) {
}
return null;
}
the output is:
java.security.InvalidKeyException: Incompatible parameters