java dh密钥交换_java-信息安全(八)-迪菲-赫尔曼(DH)密钥交换
概述
信息安全基本概念:
DH(Diffie–Hellman key exchange,迪菲-赫尔曼密钥交换)
DH
是一种安全协议,,一种确保共享KEY安全穿越不安全网络的方法,它是OAKLEY的一个组成部分。
这个机制的巧妙在于需要安全通信的双方可以用这个方法确定对称密钥。然后可以用这个密钥进行加密和解密。但是注意,这个密钥交换协议/算法只能用于密钥的交换,而不能进行消息的加密和解密。双方确定要用的密钥后,要使用其他对称密钥操作加密算法实际加密和解密消息。
Oakley算法是对Diffie-Hellman密钥交换算法的优化,它保留了后者的优点,同时克服了其弱点. Oakley算法具有五个重要特征: 它采用称为cookie程序的机制来对抗阻塞攻击. 它使得双方能够协商一个全局参数集合. 它使用了现时来保证抵抗重演攻击. 它能够交换Diffie-Hellman公开密钥. 它对Diffie-Hellman交换进行鉴别以对抗中间人的攻击.
流程分析
1.甲方构建密钥对儿,将公钥公布给乙方,将私钥保留;双方约定数据加密算法;乙方通过甲方公钥构建密钥对儿,将公钥公布给甲方,将私钥保留。
2.甲方使用私钥、乙方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥加密数据,发送给乙方加密后的数据;乙方使用私钥、甲方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥对数据解密。
3.乙方使用私钥、甲方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥加密数据,发送给甲方加密后的数据;甲方使用私钥、乙方公钥、约定数据加密算法构建本地密钥,然后通过本地密钥对数据解密。
代码实现
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));
}
}
测试代码
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);
}
}
结果输出
甲方公钥:
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/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6Ewo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O3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoCAgIABEMCQQCp+LEg3WYOYkFP8Cyl05O5y69ilJ99KO8NpdIjnqoD0uK9gl6GzWr2HVtXHs6KDRSJQFcKaOvldhfp9rVPQdiA
乙方构建加密,甲方解密
原文: abc
解密: abc
===============反过来加密解密==================
甲方构建加密,乙方解密
原文: def
解密: def
参考文章
百度百科,维基百科
http://snowolf.iteye.com/blog/382422,等
java dh密钥交换_java-信息安全(八)-迪菲-赫尔曼(DH)密钥交换相关推荐
- DH算法 | 迪菲-赫尔曼Diffie–Hellman 密钥交换及RSA(学习笔记)
DH算法 | 迪菲-赫尔曼Diffie–Hellman 密钥交换(学习笔记),来自B站: [不懂数学没关系]DH算法 | 迪菲-赫尔曼Diffie–Hellman 密钥交换_哔哩哔哩_bilibili ...
- 密钥交换算法: 迪菲-赫尔曼算法
概述 迪菲-赫尔曼算法用于通信双方交换密钥. 还记得之前介绍HTTPS协议的时候, 提到需要先通过对方公钥来进行密钥的交换, 然后再通过密钥对通信内容进行加密. 迪菲-赫尔曼算法就是用于交换密钥的. ...
- Diffe_Hellman(迪菲-赫尔曼)算法
Diffe_Hellman算法 1.Diffe_Hellman算法概念 Diffe_Hellman(迪菲-赫尔曼)算法也叫DH算法是Whitefield Diffie和Martin Hellman在1 ...
- Diffie-Hellman(迪菲-赫尔曼)秘钥交换协议
1. 协议背景 对称密码体制: Bob利用对称密钥K对信息进行加密并将加密结果发送给Alice,Alice收到信息之后,用同样的密钥进行解密. 问题1:Alice是如何知道对称密钥K的?------即 ...
- 2015年图灵奖--惠特菲尔特·迪菲和马丁·赫尔曼简介
大家好,我是执念斩长河.今天讲述的是2015年图灵奖获得者惠特菲尔特·迪菲和马丁·赫尔曼,图灵奖奖励他们为密码学做出开拓贡献.读完本篇博问大家可以收获的是: 赫尔曼的博士论文 迪菲是赫尔曼的助手 经典 ...
- 歪写数学史(数学界的花木兰——苏菲﹒热尔曼)
已经第十六章了,我终于可以荣幸的介绍这个系列中的第一位女性主人公,来自时尚之都同时也是数学家聚居地法国巴黎的---苏菲﹒热尔曼.在本章中我将用first name苏菲而不是last name热尔曼来称 ...
- 数学界的花木兰——苏菲﹒热尔曼
阿基米德聚精会神的在地上勾画着几何图形,对闯进来的罗马士兵充耳不闻,在用几种语言提问都没有得到任何回答后,罗马士兵被阿基米德的狂傲彻底激怒了,于是挥刀向这位伟大的数学家砍去......,看到这里,小苏 ...
- java默认值_Java中八种基本数据类型的默认值
通过一段代码来测试一下 8种基本数据类型的默认值 package dierge; public class Ceshi { int a; double b; boolean c; char d; fl ...
- java string封装类_java中八种基本数据类型以及它们的封装类,String类型的一些理解...
在我们面试或者考试过程中经常会考到八种基本数据类型以及它们的封装类,那么有哪八种基本数据类型呢?它们的封装类又是什么呢? 首先,八种基本数据类型分别是:int.short.float.double.l ...
最新文章
- 通过WebViewJavascriptBridge实现OC与JS交互
- VS2010 + CUDA7.5 + GPU编译OpenCV2.4.9
- 网易云音乐TFBOYS线上演唱会破纪录,稳定线上体验如何实现?
- linux投屏快捷键,Linux基本指令(持续更新中..)
- activiti高亮显示图片_第 09 篇:让博客支持 Markdown 语法和代码高亮
- 从shiro源码角度学习工厂方法设计模式
- Could not find artifact org.olap4j:olap4j:pom:0.9.7.309-JS-3 in alimaven
- mirror - 映射在远端节点上的档案
- 苹果iOS系统源码思考:对象的引用计数存储在哪里?--从runtime源码得到的启示...
- 手机测试用例-多媒体测试用例
- 代码的坏味道之十三 :Speculative Generality(夸夸其谈未来性)
- 虚拟机非正常关闭,里面的服务器重启报错:Error, some other host already uses address...
- VCP回声调试参数说明
- 成功解决:curl: (7) Failed connect to github-production-release-asset-2e65be.s3.amazonaws.com:443; 拒绝连接
- 热评云厂商:蓝汛4.0亿元,如何扭转乾坤看转型与创新
- Nature | 奇病毒(Mirusviruses)将疱疹病毒与巨型病毒联系起来
- win10 and Ubuntu双系统 install
- 图片教程+html,html图片教程
- Android开发 BaseExpandableListAdapter的使用
- 以产品当笔,与世界对话——《俞军-产品方法论》