Java笔记-DH密钥交换
Posted IT1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java笔记-DH密钥交换相关的知识,希望对你有一定的参考价值。
DH密钥交换主要是两个公式的编写,即:
·公钥计算公式;
·密钥计算公式;
生成随机数作为私钥
截图如下:
源码如下:
DH.java
package cn.it1995.tool;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class DH {
private static final int dhP = 45;
private static final int dhG = 9;
private int mPriKey;
//构造函数随机私钥
public DH(){
Random r = new Random();
mPriKey = r.nextInt(20);
System.out.println("dh priKey is : " + mPriKey);
}
//公钥计算公式计算出公钥
public int getPublicKey(){
return (int) (Math.pow(dhG, mPriKey) % dhP);
}
//使用对方公钥与自己私钥生成密钥
//在把结果转256字节,AES密钥需要128字节或256字节
public byte[] getSecretKey(long publicKey){
int buf = (int) (Math.pow(publicKey, mPriKey) % dhP);
return sha256(buf);
}
//转换成byte[256]类型,作为AES密钥
private byte[] sha256(int data){
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(DataSecret.int2Byte(data));
return messageDigest.digest();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return new byte[]{-1};
}
}
DataSecret.java
package cn.it1995.tool;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class DataSecret {
public static byte[] encode(byte[] txt) throws UnsupportedEncodingException {
return Base64.encodeBase64(txt);
}
public static byte[] decode(String txt){
return Base64.decodeBase64(txt);
}
public static byte[] int2Byte(int data){
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt(data);
return byteBuffer.array();
}
}
Main.java
public static void main(String[] args) throws UnsupportedEncodingException {
//查密钥
DH dhC = new DH();
DH dhS = new DH();
int publicKeyC = dhC.getPublicKey();
int publicKeyS = dhS.getPublicKey();
byte[] secretC = dhC.getSecretKey(publicKeyS);
byte[] secretS = dhS.getSecretKey(publicKeyC);
System.out.println("client's secrete is : ");
for(byte i : secretC){
System.out.print(i + " ");
}
System.out.println("\\nserver's secrete is : ");
for(byte i : secretS){
System.out.print(i + " ");
}
}
以上是关于Java笔记-DH密钥交换的主要内容,如果未能解决你的问题,请参考以下文章