rsa加密与解密算法

实验名称:RSA算法

实验类型:设计性实验

适用对象:信息安全

一、实验目的

学习RSA算法,通过编程实现RSA算法,掌握RSA产生公钥和私钥的方法,加深对RSA加密体制的了解,为深入学习密码学奠定基础。

二、实验要求

分析RSA算法的功能需求,详细设计实现RSA算法的数据结构和流程,给出测试用例和测试步骤,得出测试和结论。RSA算法的实现程序必须提供加密和解密两个接口:intencrypt()和intdecrypt()。当加密或者解密成功时返回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();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值