2 Replies - 2216 Views - Last Post: 21 July 2012 - 10:35 PM Rate Topic: -----

#1 potatopapabear  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 20-July 12

DiffieHellman secret to AES secret key?

Posted 20 July 2012 - 06:18 PM

import java.math.BigInteger;
import java.security.*;
import javax.crypto.*;

import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
import java.security.spec.InvalidParameterSpecException;


public class DH {

	
	// Returns a comma-separated string of 3 values.
	// The first number is the prime modulus P.
	// The second number is the base generator G.
	// The third number is bit size of the random exponent L.
	public 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;
	}
	
	
	
	public static void main(String args[]){
		// Retrieve the prime, base, and private value for generating the key pair.
		// If the values are encoded as in
		// Generating a Parameter Set for the Diffie-Hellman Key Agreement Algorithm,
		// the following code will extract the values.
		String key = genDhParams();
		String[] values = key.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();
		   // DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
		    // Get the generated public and private keys
		    PrivateKey privateKey = keypair.getPrivate();
		    PublicKey publicKey = keypair.getPublic();
		    System.out.println(publicKey);
		    // Send the public key bytes to the other party...
		    byte[] publicKeyBytes = publicKey.getEncoded();

		    // Retrieve the public key bytes of the other party
		    //publicKeyBytes = ...;

		    // Convert the public key bytes into a PublicKey object
		    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
		    KeyFactory keyFact = KeyFactory.getInstance("DH");
		    publicKey = keyFact.generatePublic(x509KeySpec);
		    
		    // 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);
		    //System.out.println(publicKey);
		    // Specify the type of key to generate;
		    // see Listing All Available Symmetric Key Generators
		    String algorithm = "DES";
		    
		    // Generate the secret key
		    SecretKey secretKey = ka.generateSecret(algorithm);
		    
		   // System.out.println(secretKey);
		    // Use the secret key to encrypt/decrypt data;
		    // see Encrypting a String with DES
		} catch (java.security.InvalidKeyException e) {
		} catch (java.security.spec.InvalidKeySpecException e) {
		} catch (java.security.InvalidAlgorithmParameterException e) {
		} catch (java.security.NoSuchAlgorithmException e) {
		}
	}
}





from this above code, I will get the DH secret key(secretKey) and I want to change that into 128 bits AES secret key. how can i do that.? the AES code is as follow. its like DH secret key into AES 128 bits secret key..please help me with it..Thank you.

import java.security.*;
   import javax.crypto.*;
   import javax.crypto.spec.*;
   import java.io.*;

   /**
   * This program generates a AES key, retrieves its raw bytes, and
   * then reinstantiates a AES key from the key bytes.
   * The reinstantiated key is used to initialize a AES cipher for
   * encryption and decryption.
   */

   public class AES {

     /**
     * Turns array of bytes into string
     *
     * @param buf	Array of bytes to convert to hex string
     * @return	Generated hex string
     */
     public static String asHex (byte buf[]) {
      StringBuffer strbuf = new StringBuffer(buf.length * 2);
      int i;

      for (i = 0; i < buf.length; i++) {
       if (((int) buf[i] & 0xff) < 0x10)
	    strbuf.append("0");

       strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
      }

      return strbuf.toString();
     }

     public static void main(String[] args) throws Exception {

       String message="This is just an example";

       // Get the KeyGenerator

       KeyGenerator kgen = KeyGenerator.getInstance("AES");
       kgen.init(128); // 192 and 256 bits may not be available


       // Generate the secret key specs.
       SecretKey skey = kgen.generateKey();
       byte[] raw = skey.getEncoded();
       String key = asHex(raw);
       SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
       System.out.println(skeySpec);

       // Instantiate the cipher

       Cipher cipher = Cipher.getInstance("AES");

       cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

       byte[] encrypted =
         cipher.doFinal((args.length == 0 ?
          "This is just an example" : args[0]).getBytes());
       System.out.println("encrypted string: " + asHex(encrypted));

       cipher.init(Cipher.DECRYPT_MODE, skeySpec);
       byte[] original =
         cipher.doFinal(encrypted);
       String originalString = new String(original);
       System.out.println("Original string: " +
         originalString + " " + asHex(original));
     }
   }




Is This A Good Question/Topic? 0
  • +

Replies To: DiffieHellman secret to AES secret key?

#2 Ghlavac  Icon User is offline

  • D.I.C Addict

Reputation: 84
  • View blog
  • Posts: 519
  • Joined: 14-January 09

Re: DiffieHellman secret to AES secret key?

Posted 21 July 2012 - 11:10 AM

I am reasonably sure they're different kinds of keys, however on the off chance that they're interchangeable (Not sure why you'd want to) you should probably look into SecretKeyFactory or w/e if I remember correctly

The second post here may provide slight insight into how to do this.

http://www.dreaminco...y-cryptography/

But its been a long while since I've done it.
Was This Post Helpful? 0
  • +
  • -

#3 potatopapabear  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 20-July 12

Re: DiffieHellman secret to AES secret key?

Posted 21 July 2012 - 10:35 PM

View PostGhlavac, on 21 July 2012 - 11:10 AM, said:

I am reasonably sure they're different kinds of keys, however on the off chance that they're interchangeable (Not sure why you'd want to) you should probably look into SecretKeyFactory or w/e if I remember correctly

The second post here may provide slight insight into how to do this.

http://www.dreaminco...y-cryptography/

But its been a long while since I've done it.


My assignment's requirement is like this. after you have created the secret key using DH, then turn that secret key into 128 AES key which will be used to encrypt and decrypt messages..But I still dont know how to do that, as in how to link those two codes together. I really have to use both DH and AES..:(
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1