Java大整數類BigInteger實現模重複平方算法

RSA的核心計算就是計算a^e mod m,其中,a,e可隨機生成,m爲大整數。

常規使用的int和long無法表示超大整數,因此使用Java的BigInteger來實現計算a^e mod m:

public static BigInteger mod(BigInteger a,BigInteger e,BigInteger m) {
		BigInteger kex = new BigInteger("1");
		String binary = e.toString(2);
		 for (int i = binary.length() - 1 ; i >= 0 ; i--){
			 if (binary.charAt(i) == '1'){
				 kex = (kex.multiply(a)).remainder(m);
				 a = (a.multiply(a)).remainder(m);
			 }else {
				a=(a.multiply(a)).remainder(m);
			}
		 }
		return kex;
	}

 

發佈了109 篇原創文章 · 獲贊 35 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章