rsa加密與解密算法
實驗名稱:RSA算法
實驗類型: 設計性實驗
適用對象: 信息安全
一、實驗目的
學習RSA算法,通過編程實現RSA算法,掌握RSA產生公鑰和私鑰的方法,加深對RSA加密體制的了解,為深入學習密碼學奠定基礎。
二、實驗要求
分析RSA算法的功能需求,詳細設計實現RSA算法的數據結構和流程,給出測試用例和測試步驟,得出測試和結論。RSA算法的實現程序必須提供加密和解密兩個接口:int encrypt()和int decrypt()。當加密或者解密成功時返回CRYPT_OK,失敗時返回CRYPT_ERROR。
三、實驗原理
詳見書本中關于RSA算法的描述。下圖可作為參考
四、實驗所需儀器、設備、材料(試劑)
運行Windows或Linux操作系統的PC機,具有gcc(Linux)、java、VC(Windows)等C或java語言編譯環境。
java中實現rsa算法
代碼為:
package rsa;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Random;
public class rsa {
private static final BigInteger temp = null;
private BigInteger p;
private BigInteger q;
private BigInteger n;
private BigInteger t;
private BigInteger e;
private BigInteger d;
BigInteger s=new BigInteger("1");
public void getpq() throws IOException{
Random rand=new Random();
System.out.println("請輸入隨機數的位數");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
String st=stdi.readLine();
int length=Integer.parseInt(st);
System.out.println(length);
this.p= temp.probablePrime(length,rand);
this.q=temp.probablePrime(length,rand);
System.out.println("大素數p的值為:"+p);
System.out.println("大素數q的值為:"+q);
this.n=p.multiply(q);
this.t=(p.subtract(s)).multiply(q.subtract(s));
}
public void geted() throws IOException{
System.out.println("請輸入隨機數e,作為加密密鑰,要求0<e<t,gcd(e,t)=1");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String str=stdin.readLine();
this.e=new BigInteger(str);
System.out.println("加密密鑰為:"+e);
(this.d)=e.modInverse(t);
System.out.println("解密密鑰為:"+d);
}
public void jiami() throws IOException{
System.out.println("請輸入明文:");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
String str=stdi.readLine();
BigInteger P=new BigInteger(str);
BigInteger C=P.modPow(e, n);
System.out.println("得到的密文是:"+C);
}
public void jiemi() throws IOException{
System.out.println("請輸入密文:");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
String str=stdi.readLine();
BigInteger C=new BigInteger(str);
BigInteger P=C.modPow(d, n);
System.out.println("得到的名文是:"+P);
}
public static void main(String[] args) throws IOException {
rsa rs=new rsa();
rs.getpq();
rs.geted();
rs.jiami();
rs.jiemi();
}
}