当前位置: 移动技术网 > IT编程>开发语言>Java > RSA加密算法java简单实现方法(必看)

RSA加密算法java简单实现方法(必看)

2019年07月22日  | 移动技术网IT编程  | 我要评论

简单完整的代码,通过这个代码你将对rsa加密算法在java中的实现方法有一个初步的了解,这个类,你可以直接使用,水平高的,就自己修改完善下代码。

package security;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.io.*;
import java.math.*;
public class rsademo {
	public rsademo() {
	}
	public static void generatekey() {
		try {
			keypairgenerator kpg = keypairgenerator.getinstance("rsa");
			kpg.initialize(1024);
			keypair kp = kpg.genkeypair();
			publickey pbkey = kp.getpublic();
			privatekey prkey = kp.getprivate();
			// 保存公钥
			fileoutputstream f1 = new fileoutputstream("pubkey.dat");
			objectoutputstream b1 = new objectoutputstream(f1);
			b1.writeobject(pbkey);
			// 保存私钥
			fileoutputstream f2 = new fileoutputstream("privatekey.dat");
			objectoutputstream b2 = new objectoutputstream(f2);
			b2.writeobject(prkey);
		} catch (exception e) {
		}
	}
	public static void encrypt() throws exception {
		string s = "hello world!";
		// 获取公钥及参数e,n
		fileinputstream f = new fileinputstream("pubkey.dat");
		objectinputstream b = new objectinputstream(f);
		rsapublickey pbk = (rsapublickey) b.readobject();
		biginteger e = pbk.getpublicexponent();
		biginteger n = pbk.getmodulus();
		system.out.println("e= " + e);
		system.out.println("n= " + n);
		// 获取明文m
		byte ptext[] = s.getbytes("utf-8");
		biginteger m = new biginteger(ptext);
		// 计算密文c
		biginteger c = m.modpow(e, n);
		system.out.println("c= " + c);
		// 保存密文
		string cs = c.tostring();
		bufferedwriter out =
			new bufferedwriter(
				new outputstreamwriter(new fileoutputstream("encrypt.dat")));
		out.write(cs, 0, cs.length());
		out.close();
	}
	public static void decrypt() throws exception {
		// 读取密文
		bufferedreader in =
			new bufferedreader(
				new inputstreamreader(new fileinputstream("encrypt.dat")));
		string ctext = in.readline();
		biginteger c = new biginteger(ctext);
		// 读取私钥
		fileinputstream f = new fileinputstream("privatekey.dat");
		objectinputstream b = new objectinputstream(f);
		rsaprivatekey prk = (rsaprivatekey) b.readobject();
		biginteger d = prk.getprivateexponent();
		// 获取私钥参数及解密
		biginteger n = prk.getmodulus();
		system.out.println("d= " + d);
		system.out.println("n= " + n);
		biginteger m = c.modpow(d, n);
		// 显示解密结果
		system.out.println("m= " + m);
		byte[] mt = m.tobytearray();
		system.out.println("plaintext is ");
		for (int i = 0; i < mt.length; i++) {
			system.out.print((char) mt[i]);
		}
	}
	public static void main(string args[]) {
		try {
			generatekey();
			encrypt();
			decrypt();
		} catch (exception e) {
			system.out.println(e.tostring());
		}
	}
}

以上这篇rsa加密算法java简单实现方法(必看)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网