DH,全称为“Diffie-Hellman”,他是一种确保共享KEY安全穿越不安全网络的方法,也就是常说的密钥一致协议。由公开密钥密码体制的奠定人Diffie和Hellman所提出的一种思想。java
简单的说就是容许两名用户在公开媒体上交换信息以生成“一致”的、能够共享的密钥。也就是由甲方产出一对密钥(公钥、私钥),乙方依照甲方公钥产生乙方密钥对(公钥、私钥)。算法
以此为基线,做为数据传输保密基础,同时双方使用同一种对称加密算法构建本地密钥(SecretKey)对数据加密。这样,在互通了本地密钥(SecretKey)算法后,甲乙双方公开本身的公钥,使用对方的公钥和刚才产生的私钥加密数据,同时可使用对方的公钥和本身的私钥对数据解密。不仅仅是甲乙双方两方,能够扩展为多方共享数据通信,这样就完成了网络交互数据的安全通信!数组
整个通讯过程当中g、g^a、g^b是公开的,但因为g、a、b都是整数,经过g和g^a获得a仍是比较容易的,b也是如此,因此最终的“密钥”g^(a*b)仍是能够被计算出来的。因此实际的过程还须要在基本原理上加入新的计算——模运算。安全
(g^b%p)^a%p=(g^a%p)^b%p 证实:网络
若是a=2:工具
整个通讯过程当中g、p、g^a%p、g^b%p是公开的,这时经过g、p、g^a%p获得a比较难,一样经过g、p、g^b%p获得b比较难,因此最终的密钥是比较安全的。测试
以g=五、p=2三、g^a%p=8计算a为例,a=log(5, (8+23*n)),这个只能将n的可能值逐个带入公式试验才能获得a的值。若是a、p是比较大的数那么计算更加困难。优化
须要注意的是,为了防止应用优化算法计算上述问题,质数p不是随便选择的,须要符合必定的条件。随机数a、b的生成算法也必需注意,应使结果尽量随机,不能出现可预测的规律,不然会使破解变的容易。google
package com.test.dh; import com.google.common.collect.Maps; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.*; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Map; /** * Created by xiang.li on 2015/3/4. * DH 加解密工具类 */ public class DH { /** * 定义加密方式 */ private static final String KEY_DH = "DH"; /** * 默认密钥字节数 */ private static final int KEY_SIZE = 1024; /** * DH加密下须要一种对称加密算法对数据加密,这里咱们使用DES,也可使用其余对称加密算法 */ private static final String KEY_DH_DES = "DES"; private static final String KEY_DH_PUBLICKEY = "DHPublicKey"; private static final String KEY_DH_PRIVATEKEY = "DHPrivateKey"; /** * 初始化甲方密钥 * @return */ public static Map<String, Object> init() { Map<String, Object> map = null; try { KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_DH); generator.initialize(KEY_SIZE); KeyPair keyPair = generator.generateKeyPair(); // 甲方公钥 DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic(); // 甲方私钥 DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate(); map = Maps.newHashMap(); map.put(KEY_DH_PUBLICKEY, publicKey); map.put(KEY_DH_PRIVATEKEY, privateKey); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return map; } /** * 初始化乙方密钥 * @param key 甲方密钥 * @return */ public static Map<String, Object> init(String key) { Map<String, Object> map = null; try { // 解析甲方密钥 byte[] bytes = decryptBase64(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_DH); PublicKey publicKey = factory.generatePublic(keySpec); // 由甲方公钥构建乙方密钥 DHParameterSpec spec = ((DHPublicKey) publicKey).getParams(); KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_DH); generator.initialize(spec); KeyPair keyPair = generator.generateKeyPair(); // 乙方公钥 DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic(); // 乙方私钥 DHPrivateKey dhPrivateKey = (DHPrivateKey) keyPair.getPrivate(); map = Maps.newHashMap(); map.put(KEY_DH_PUBLICKEY, dhPublicKey); map.put(KEY_DH_PRIVATEKEY, dhPrivateKey); } catch (Exception e) { e.printStackTrace(); } return map; } /** * DH 加密 * @param data 带加密数据 * @param publicKey 甲方公钥 * @param privateKey 乙方私钥 * @return */ public static byte[] encryptDH(byte[] data, String publicKey, String privateKey) { byte[] bytes = null; try { // 生成本地密钥 SecretKey secretKey = getSecretKey(publicKey, privateKey); // 数据加密 Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, secretKey); bytes = cipher.doFinal(data); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return bytes; } /** * DH 解密 * @param data 待解密数据 * @param publicKey 乙方公钥 * @param privateKey 甲方私钥 * @return */ public static byte[] decryptDH(byte[] data, String publicKey, String privateKey) { byte[] bytes = null; try { // 生成本地密钥 SecretKey secretKey = getSecretKey(publicKey, privateKey); // 数据解密 Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, secretKey); bytes = cipher.doFinal(data); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return bytes; } /** * 取得私钥 * @param map * @return */ public static String getPrivateKey(Map<String, Object> map) { String str = ""; try { Key key = (Key) map.get(KEY_DH_PRIVATEKEY); str = encryptBase64(key.getEncoded()); } catch (Exception e) { e.printStackTrace(); } return str; } /** * 取得公钥 * @param map * @return */ public static String getPublicKey(Map<String, Object> map) { String str = ""; try { Key key = (Key) map.get(KEY_DH_PUBLICKEY); str = encryptBase64(key.getEncoded()); } catch (Exception e) { e.printStackTrace(); } return str; } /** * 构建本地密钥 * @param publicKey 公钥 * @param privateKey 私钥 * @return */ private static SecretKey getSecretKey(String publicKey, String privateKey) { SecretKey secretKey = null; try { // 初始化公钥 byte[] publicBytes = decryptBase64(publicKey); KeyFactory factory = KeyFactory.getInstance(KEY_DH); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); PublicKey localPublicKey = factory.generatePublic(keySpec); // 初始化私钥 byte[] privateBytes = decryptBase64(privateKey); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateBytes); PrivateKey localPrivateKey = factory.generatePrivate(spec); KeyAgreement agreement = KeyAgreement.getInstance(factory.getAlgorithm()); agreement.init(localPrivateKey); agreement.doPhase(localPublicKey, true); // 生成本地密钥 secretKey = agreement.generateSecret(KEY_DH_DES); } catch (Exception e) { e.printStackTrace(); } return secretKey; } /** * BASE64 解密 * @param key 须要解密的字符串 * @return 字节数组 * @throws Exception */ public static byte[] decryptBase64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } /** * BASE64 加密 * @param key 须要加密的字节数组 * @return 字符串 * @throws Exception */ public static String encryptBase64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } /** * 测试方法 * @param args */ public static void main(String[] args) { // 生成甲方密钥对 Map<String, Object> mapA = init(); String publicKeyA = getPublicKey(mapA); String privateKeyA = getPrivateKey(mapA); System.out.println("甲方公钥:\n" + publicKeyA); System.out.println("甲方私钥:\n" + privateKeyA); // 由甲方公钥产生本地密钥对 Map<String, Object> mapB = init(publicKeyA); String publicKeyB = getPublicKey(mapB); String privateKeyB = getPrivateKey(mapB); System.out.println("乙方公钥:\n" + publicKeyB); System.out.println("乙方私钥:\n" + privateKeyB); String word = "abc"; System.out.println("原文: " + word); // 由甲方公钥,乙方私钥构建密文 byte[] encWord = encryptDH(word.getBytes(), publicKeyA, privateKeyB); // 由乙方公钥,甲方私钥解密 byte[] decWord = decryptDH(encWord, publicKeyB, privateKeyA); System.out.println("解密: " + new String(decWord)); } }