Java笔记-DH密钥交换
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                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密钥交换的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Java笔记-AnnotationCon
- 下一篇: Nginx笔记-反向代理中配置WebSo
