public class DH {
private int priKey;
private static int dhP = 99991;
private static int dhG = 5;
public DH() {
Random random = new Random();
priKey = random.nextInt(10);
System.out.println("DH 生成的私鑰為 " + priKey);
}
/**
* 獲取DH算法的公鑰
*/
public int getPubKey() {
return startPow(dhG, priKey).divideAndRemainder(new BigInteger(String.valueOf(dhP)))[1].intValue();
}
/**
* 獲取DH算法的共享密鑰
*/
public int getCommonKey(int pubKeyS) {
//此處的divideAndRemainder 計(jì)算兩個(gè)BigInteger之間的相除,獲得由數(shù)組構(gòu)成的商和余數(shù)
return startPow(pubKeyS, priKey).divideAndRemainder(new BigInteger(String.valueOf(dhP)))[1].intValue();
}
/**
* 計(jì)算冪次方。因?yàn)橛?jì)算整數(shù)的冪次方可造成最終的數(shù)值超過(guò)Int最大的范圍,導(dǎo)致計(jì)算錯(cuò)誤。所以此處使用BigInteger來(lái)計(jì)算冪次方
*/
private BigInteger startPow(int a, int b) {
if (b == 0) {
return new BigInteger(String.valueOf(1));
} else {
return pow(new BigInteger(String.valueOf(a)),b);
}
}
private BigInteger pow(BigInteger a, int b) {
if (b != 1)
//multiply 代表乘法。此處使用遞歸計(jì)算a的b次方冪
return a.multiply(pow(a, b - 1));
else
return a;
}
}
密鑰交換算法DH,計(jì)算密鑰值越界解決方式
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 姓名:朱睿琦 學(xué)號(hào):15180288015 參考:https://baike.baidu.com/item/Dif...
- 1、DH算法的簡(jiǎn)介 DH,全稱為“Diffie-Hellman”,他是一種確保共享KEY安全穿越不安全網(wǎng)絡(luò)的方法,...
- what's Diffie–Hellman key exchange 維基定義: 是一種安全協(xié)議。它可以讓雙方在完...
- 1、DH密鑰交換概述 Diffie-Hellman由Whitfield Diffie和Martin Hellman...