Java examples for Security:Key
Generating a Secret Key Using the Diffie-Hellman Key Agreement Algorithm
import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; import javax.crypto.spec.DHParameterSpec; public class Main { public static void main(String[] args) throws Exception { String[] values = "this is a test".split(" "); BigInteger p = new BigInteger(values[0]); BigInteger g = new BigInteger(values[1]); int l = Integer.parseInt(values[2]); try {/*w w w. jav a 2s .c om*/ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); DHParameterSpec dhSpec = new DHParameterSpec(p, g, l); keyGen.initialize(dhSpec); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); publicKeyBytes = null;// your key; X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); publicKey = keyFact.generatePublic(x509KeySpec); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(privateKey); ka.doPhase(publicKey, true); String algorithm = "DES"; SecretKey secretKey = ka.generateSecret(algorithm); } catch (java.security.InvalidKeyException e) { } catch (java.security.spec.InvalidKeySpecException e) { } catch (java.security.InvalidAlgorithmParameterException e) { } catch (java.security.NoSuchAlgorithmException e) { } } }