public class DH {
public static void main(String[] args)throws Exception{
//初始化发送方密钥----------------------------------------------------------------
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("DH");
keyPairGenerator.initialize(1024);
KeyPair senderKeyPair=keyPairGenerator.generateKeyPair();
byte[] senderPbkEnc=senderKeyPair.getPublic().getEncoded();//得到发送方公钥的 byte数组形式;>>>>>>>>>>>>>>>>>-传递给接受方
//使用发送方密钥中的参数 初始化接收方的密钥载体------------------------------------------------
KeyFactory keyFactory=KeyFactory.getInstance("DH");
X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(senderPbkEnc); //根据发送方给定的编码密钥创建一个符合编码标准的 X509EncodedKeySpec
PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec); //密钥工厂根据 标准密钥规范的编码 生成公钥
DHParameterSpec dhParameterSpec=DHPublicKey.class.cast(publicKey).getParams(); //从公钥中获取参数
KeyPairGenerator keyPairGenerator2=KeyPairGenerator.getInstance("DH");
keyPairGenerator2.initialize(1024);
keyPairGenerator2.initialize(dhParameterSpec); //利用发送方传递的公钥中获取的参数 初始化密钥生成器
KeyPair receiverkeyPair=keyPairGenerator2.generateKeyPair(); //生成秘钥
PrivateKey receiverPrivateKey=receiverkeyPair.getPrivate(); //获得私钥
//获得公钥bytes 此公钥用于传递给发送方
byte[] receiverPbkBytes=receiverkeyPair.getPublic().getEncoded();//>>>>>>>>>>>>>>>>>>>>>>传递给发送方
//构建接收方密钥
KeyAgreement keyAgreement=KeyAgreement.getInstance("DH");
keyAgreement.init(receiverPrivateKey);
keyAgreement.doPhase(publicKey, true);
SecretKey receiverSecretKey=keyAgreement.generateSecret("DES"); //接收方密钥构建完成
//构建发送方密钥---------------------------------------------------------------
KeyFactory keyFactory2=keyFactory.getInstance("DH");
X509EncodedKeySpec x509EncodedKeySpec2=new X509EncodedKeySpec(receiverPbkBytes);
PublicKey senderPublicKey=keyFactory2.generatePublic(x509EncodedKeySpec2);
KeyAgreement keyAgreement2=KeyAgreement.getInstance("DH");
keyAgreement2.init(senderKeyPair.getPrivate());
keyAgreement2.doPhase(senderPublicKey, true);
SecretKey senderSecretKey =keyAgreement2.generateSecret("DES"); //发送方密钥构建完成
//进行加解密
String str="imooc security";
Cipher cipher=Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, senderSecretKey);
cipher.update(str.getBytes());
byte[] bs=cipher.doFinal();
System.out.println("DH加密后:"+Hex.encodeHexString(bs));
cipher.init(Cipher.DECRYPT_MODE, receiverSecretKey);
System.out.println("解密后:"+new String(cipher.doFinal(bs)));
}
}
String str="imooc security";
Cipher cipher=Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, senderSecretKey);
byte[] bs=cipher.doFinal(str.getBytes());