第二周作业

来源:互联网 发布:为什么说网络三大邪书 编辑:程序博客网 时间:2024/05/16 09:09
package suanfa1;


import java.util.Random;


public class RSA {
static long n = 0;
static long t = 0;
static long e = 0;
static long d = 0;
public static void main(String []args){
CreateLock(7,13);
CreateKey();
int secret = CreateSecret(22);
LookSecret(secret);

}

//2.1 判断质量数
public static int isPrime(long a){
double max = Math.sqrt(a);
for(int index=2;index<=max;index++){
if(a%index==0){
return 0;
}
}
return 1;
 
}
//2.2 随机生成长整数
public static long createRndInteger(int n){
int max_result = (int) Math.pow(2,n);
int min_result = (int) Math.pow(2,n-1);
Random random = new Random();
long result = random.nextInt(max_result-min_result)+min_result;
return result;
}
 //2.3 随机生成一个长质数
static long createRndPrime(int n){
/*
 * 注释:
 * 由于除了2外,所有偶数都不可能是质数的道理
 * 可设计为随机数r范围是从1-2的(n-1)次方,然后通过r*2-1就可以保证生成的r
 * 一定是奇数,从而免除了对偶数的判断,减少了判断的次数。
 * */
 
//得出2的(n-1)次方的范围,-1是为了后面+1防止结果为0
int max_result = (int) createRndInteger(n-1)-1;
Random random = new Random();
//check代表判断是否是质数,result是随机数r*2-1产生的值
int check = 0;
int result = 0;
//如果result不是质数,则不断循环
while(check==0){
int r = random.nextInt(max_result)+1;
result = r*2-1;
check = isPrime(result);
}
return result;
}
 
//2.4公开密钥生成算法
static void CreateLock(int p,int q){
n = p*q;
t = (p-1)*(q-1);
e = CreateE(t);
System.out.println("公钥<"+n+","+e+">");
}
//生成互质数
static int CreateE(long N){
Random random = new Random();
int e = 0;
while(true){
e=random.nextInt((int)N-1)+1;
double max = Math.sqrt(e);
for(int index=2;index<=max;index++){
if(N%index==0){
return e;
}
}
}

}
//2.5保密钥匙生成算法
static void CreateKey(){

while(d*e%t!=1){
d++;
}
System.out.println("私钥<"+n+","+d+">");
}
//2.6 RSA加密
static int CreateSecret(int m){
int secret = (int) (Math.pow(m, e)%n);
System.out.println("加密信息为"+secret);
return secret;
}

//2.7 RSA解密
static int LookSecret(int secret){
int content = (int) (Math.pow(secret, d)%n);
System.out.println("解密信息为"+content);
return content;
}

}




0 0
原创粉丝点击