java dh密钥交换_java-信息安全(八)-迪菲-赫尔曼(DH)密钥交换

概述

信息安全基本概念:

DH(Diffie–Hellman key exchange,迪菲-赫尔曼密钥交换)

DH

是一种安全协议,,一种确保共享KEY安全穿越不安全网络的方法,它是OAKLEY的一个组成部分。

这个机制的巧妙在于需要安全通信的双方可以用这个方法确定对称密钥。然后可以用这个密钥进行加密和解密。但是注意,这个密钥交换协议/算法只能用于密钥的交换,而不能进行消息的加密和解密。双方确定要用的密钥后,要使用其他对称密钥操作加密算法实际加密和解密消息。

Oakley算法是对Diffie-Hellman密钥交换算法的优化,它保留了后者的优点,同时克服了其弱点. Oakley算法具有五个重要特征: 它采用称为cookie程序的机制来对抗阻塞攻击. 它使得双方能够协商一个全局参数集合. 它使用了现时来保证抵抗重演攻击. 它能够交换Diffie-Hellman公开密钥. 它对Diffie-Hellman交换进行鉴别以对抗中间人的攻击.

流程分析

1.甲方构建密钥对儿,将公钥公布给乙方,将私钥保留;双方约定数据加密算法;乙方通过甲方公钥构建密钥对儿,将公钥公布给甲方,将私钥保留。

76df4465c3f3eb7316c2ac40ca78f200.png

2.甲方使用私钥、乙方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥加密数据,发送给乙方加密后的数据;乙方使用私钥、甲方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥对数据解密。

e7ca284513f694570c8c9d1674e3b9dd.png

3.乙方使用私钥、甲方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥加密数据,发送给甲方加密后的数据;甲方使用私钥、乙方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥对数据解密。

4c3536d8ce1c06a0ef851142ca07c2d0.png

代码实现

48304ba5e6f9fe08f3fa1abda7d326ab.png

package com.jd.order.util.encryption;

import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;

import java.util.Map;

import javax.crypto.Cipher;

import javax.crypto.KeyAgreement;

import javax.crypto.SecretKey;

import javax.crypto.interfaces.DHPrivateKey;

import javax.crypto.interfaces.DHPublicKey;

import javax.crypto.spec.DHParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**

* DH密码交换协议

*

* @author 木子旭

* @since 2017年3月17日上午9:18:14

* @version %I%,%G%

*/

public class DHCoder {

public static final String ALGORITHM = "DH";

/**

* 默认密钥字节数

*

*

 
 

* DH

* Default Keysize 1024

* Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).

*

*/

private static final int KEY_SIZE = 1024;

/**

* DH加密下需要一种对称加密算法对数据加密,这里我们使用DES,也可以使用其他对称加密算法。

*/

public static final String SECRET_ALGORITHM = "DES";

private static final String PUBLIC_KEY = "DHPublicKey";

private static final String PRIVATE_KEY = "DHPrivateKey";

/**

* 初始化甲方密钥

*

* @return

* @throws Exception

*/

public static Map initKey() throws Exception {

KeyPairGenerator keyPairGenerator = KeyPairGenerator

.getInstance(ALGORITHM);

keyPairGenerator.initialize(KEY_SIZE);

KeyPair keyPair = keyPairGenerator.generateKeyPair();

// 甲方公钥

DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();

// 甲方私钥

DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();

Map keyMap = new HashMap(2);

keyMap.put(PUBLIC_KEY, publicKey);

keyMap.put(PRIVATE_KEY, privateKey);

return keyMap;

}

/**

* 初始化乙方密钥

*

* @param key

* 甲方公钥

* @return

* @throws Exception

*/

public static Map initKey(String key) throws Exception {

// 解析甲方公钥

byte[] keyBytes = decryptBASE64(key);

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

// 由甲方公钥构建乙方密钥

DHParameterSpec dhParamSpec = ((DHPublicKey) pubKey).getParams();

KeyPairGenerator keyPairGenerator = KeyPairGenerator

.getInstance(keyFactory.getAlgorithm());

keyPairGenerator.initialize(dhParamSpec);

KeyPair keyPair = keyPairGenerator.generateKeyPair();

// 乙方公钥

DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();

// 乙方私钥

DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();

Map keyMap = new HashMap(2);

keyMap.put(PUBLIC_KEY, publicKey);

keyMap.put(PRIVATE_KEY, privateKey);

return keyMap;

}

/**

* 加密

*

* @param data

* 待加密数据

* @param publicKey

* 甲方公钥

* @param privateKey

* 乙方私钥

* @return

* @throws Exception

*/

public static byte[] encrypt(byte[] data, String publicKey,

String privateKey) throws Exception {

// 生成本地密钥

SecretKey secretKey = getSecretKey(publicKey, privateKey);

// 数据加密

Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

return cipher.doFinal(data);

}

/**

* 解密

*

* @param data

* 待解密数据

* @param publicKey

* 乙方公钥

* @param privateKey

* 乙方私钥

* @return

* @throws Exception

*/

public static byte[] decrypt(byte[] data, String publicKey,

String privateKey) throws Exception {

// 生成本地密钥

SecretKey secretKey = getSecretKey(publicKey, privateKey);

// 数据解密

Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, secretKey);

return cipher.doFinal(data);

}

/**

* 构建密钥

*

* @param publicKey

* 公钥

* @param privateKey

* 私钥

* @return

* @throws Exception

*/

private static SecretKey getSecretKey(String publicKey, String privateKey)

throws Exception {

// 初始化公钥

byte[] pubKeyBytes = decryptBASE64(publicKey);

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);

PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

// 初始化私钥

byte[] priKeyBytes = decryptBASE64(privateKey);

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyBytes);

Key priKey = keyFactory.generatePrivate(pkcs8KeySpec);

KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory

.getAlgorithm());

keyAgree.init(priKey);

keyAgree.doPhase(pubKey, true);

// 生成本地密钥

SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM);

return secretKey;

}

/**

* 取得私钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPrivateKey(Map keyMap)

throws Exception {

Key key = (Key) keyMap.get(PRIVATE_KEY);

return encryptBASE64(key.getEncoded());

}

/**

* 取得公钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPublicKey(Map keyMap)

throws Exception {

Key key = (Key) keyMap.get(PUBLIC_KEY);

return encryptBASE64(key.getEncoded());

}

public static byte[] decryptBASE64(String data) {

return Base64.decodeBase64(data);

}

public static String encryptBASE64(byte[] data) {

return new String(Base64.encodeBase64(data));

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

测试代码

48304ba5e6f9fe08f3fa1abda7d326ab.png

package com.jd.order.util.encryption;

import static org.junit.Assert.assertEquals;

import java.util.Map;

import org.junit.Test;

public class DHCoderTest {

@Test

public void test() throws Exception {

// 生成甲方密钥对儿

Map aKeyMap = DHCoder.initKey();

String aPublicKey = DHCoder.getPublicKey(aKeyMap);

String aPrivateKey = DHCoder.getPrivateKey(aKeyMap);

System.err.println("甲方公钥:\r" + aPublicKey);

System.err.println("甲方私钥:\r" + aPrivateKey);

// 由甲方公钥产生本地密钥对儿

Map bKeyMap = DHCoder.initKey(aPublicKey);

String bPublicKey = DHCoder.getPublicKey(bKeyMap);

String bPrivateKey = DHCoder.getPrivateKey(bKeyMap);

System.err.println("乙方公钥:\r" + bPublicKey);

System.err.println("乙方私钥:\r" + bPrivateKey);

System.err.println("乙方构建加密,甲方解密 ");

String aInput = "abc ";

System.err.println("原文: " + aInput);

// 乙方构建密钥消息,使用甲方公钥,乙方私钥构建密文

byte[] aCode = DHCoder.encrypt(aInput.getBytes(), aPublicKey,

bPrivateKey);

// 甲方解密乙方加密消息,使用乙方公钥,甲方私钥解密

byte[] aDecode = DHCoder.decrypt(aCode, bPublicKey, aPrivateKey);

String aOutput = (new String(aDecode));

System.err.println("解密: " + aOutput);

assertEquals(aInput, aOutput);

System.err.println(" ===============反过来加密解密================== ");

System.err.println("甲方构建加密,乙方解密 ");

String bInput = "def ";

System.err.println("原文: " + bInput);

// 甲方构建密钥消息,由乙方公钥,甲方私钥构建密文

byte[] bCode = DHCoder.encrypt(bInput.getBytes(), bPublicKey,

aPrivateKey);

// 乙方解密甲方加密消息,使用甲方公钥,乙方私钥解密

byte[] bDecode = DHCoder.decrypt(bCode, aPublicKey, bPrivateKey);

String bOutput = (new String(bDecode));

System.err.println("解密: " + bOutput);

assertEquals(bInput, bOutput);

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

结果输出

48304ba5e6f9fe08f3fa1abda7d326ab.png

甲方公钥:

MIIBpjCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoCAgIAA4GEAAKBgCI1eq1qourLxvb5kEdUTM2sSuZcGpgUtGOuZdyH4iOzRwyMAD+Ae5TXastomBXdGxVyOVgNhOgj915rYsYIRMdzAxP/RADeTQ2scdcFRM6PzoTihrTLL5LDseZe6G67P9hfEuR+M1FKwuXlEi712LWblLD+404NNKPKRj5be/kO

甲方私钥:

MIIBZwIBADCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/Y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1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoCAgIABEMCQQCp+LEg3WYOYkFP8Cyl05O5y69ilJ99KO8NpdIjnqoD0uK9gl6GzWr2HVtXHs6KDRSJQFcKaOvldhfp9rVPQdiA

乙方构建加密,甲方解密

原文: abc

解密: abc

===============反过来加密解密==================

甲方构建加密,乙方解密

原文: def

解密: def

48304ba5e6f9fe08f3fa1abda7d326ab.png

参考文章

百度百科,维基百科

http://snowolf.iteye.com/blog/382422,等

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值