JAVA RSA算法加密实现 eclipse

RSA算法加密实现

一、实验目的
学习经典的RSA公钥加密算法的基本原理和特点,能够编写简单的代码实现RSA公钥加密和私钥解密的过程。
二、实验要求
1. 熟悉RSA公私钥加密算法。
2. 掌握如何使用Java BigInteger类,简单实现教科书式的RSA公私钥加密算法。
3. 了解JDK提供的RSA算法的使用。
三、开发环境
JDK 1.7以上,Java开发环境(本实验采用Windows + eclipse作为实验环境),要求参与实验的同学按照对称加密提供的方法,提前安装好JDK。
四、实验内容
【1-1】RSA算法的实现
1、实现RSA公私钥生成算法。
根据教科书可知,RSA的公钥为 ,私钥为 。其中 且 为两个大素数。 且 。因此,可先选取两个大素数,并根据上述关系选取公私钥。相关代码如下:

import java.math.BigInteger;
import java.util.Random;

public class RSAInstance {
	BigInteger n;
	BigInteger e;
	BigInteger d;
	
	public void initKeys() {
		// 随机选取两个大素数p,q 长度大致在1024位,置信度1-(1/2)^(500)
		BigInteger p = new BigInteger(1024, 500, new Random());
		BigInteger q = new BigInteger(1024, 500, new Random());
		
		// 强制要求p q不等,否则会遭受开平方攻击
		assert(p.compareTo(q) != 0);
		
		// 计算n和欧拉函数(n)
		n = p.multiply(q);
		BigInteger fin = (p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)));
		
		// 随机选取e 同时计算d
		// 为了保证一定互素,我们直接选一个素数e
		e = new BigInteger(512, 500, new Random());
		d = e.modInverse(fin);
		
		// 输出结果
		System.out.println("n : " + n);
		System.out.println("e : " + e);
		System.out.println("d : " + d);
		
		return;
	}
	
}

【1-2】RSA算法的完整参考代码

import java.math.BigInteger;
import java.util.Random;


public class RSAInstance {
	BigInteger n;
	BigInteger e;
	BigInteger d;
	
	public void initKeys() {
		// 随机选取两个大素数p,q 长度大致在1024位,素数置信度1-(1/2)^(500)
		BigInteger p = new BigInteger(1024, 500, new Random());
		BigInteger q = new BigInteger(1024, 500, new Random());
		
		// 强制要求p q不等,否则会遭受开平方攻击
		assert(p.compareTo(q) != 0);
		
		// 计算n和欧拉函数(n)
		n = p.multiply(q);
		BigInteger fin = (p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)));
		
		// 随机选取e<fin且和fin互素, 同时计算d
		// 为了保证一定互素,我们直接选一个素数e
		e = new BigInteger(512, 500, new Random());
		d = e.modInverse(fin);
		
		// 输出结果
		System.out.println("n : " + n);
		System.out.println("e : " + e);
		System.out.println("d : " + d);
		
		return;
	}
	
	// 加密算法
	public BigInteger encrypt(BigInteger m) {
		return m.modPow(e, n);
	}
	
	// 解密算法
	public BigInteger decrypt(BigInteger c) {
		return c.modPow(d, n);
	}
	
	// Main方法,测试RSA对的加密和解密
	public static void main(String args[]) {
		// 创建RSA算法实例,生成公私钥对
		RSAInstance rsa = new RSAInstance();
		rsa.initKeys();
		
		// 加密消息m, 其中m = 12345678 
		BigInteger m = new BigInteger("12345678");
		BigInteger c = rsa.encrypt(m);
		System.out.println("E(12345678)    = " + c);		
		// 解密
		System.out.println("D(E(12345678)) = " + rsa.decrypt(c));
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_45056216/article/details/106590879
今日推荐