RSA加密算法java简单实现方法(必看)
简单完整的代码,通过这个代码你将对RSA加密算法在Java中的实现方法有一个初步的了解,这个类,你可以直接使用,水平高的,就自己修改完善下代码。
packagesecurity;
importjava.security.*;
importjava.security.spec.*;
importjava.security.interfaces.*;
importjavax.crypto.spec.*;
importjavax.crypto.interfaces.*;
importjava.io.*;
importjava.math.*;
publicclassRSADemo{
publicRSADemo(){
}
publicstaticvoidgenerateKey(){
try{
KeyPairGeneratorkpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPairkp=kpg.genKeyPair();
PublicKeypbkey=kp.getPublic();
PrivateKeyprkey=kp.getPrivate();
//保存公钥
FileOutputStreamf1=newFileOutputStream("pubkey.dat");
ObjectOutputStreamb1=newObjectOutputStream(f1);
b1.writeObject(pbkey);
//保存私钥
FileOutputStreamf2=newFileOutputStream("privatekey.dat");
ObjectOutputStreamb2=newObjectOutputStream(f2);
b2.writeObject(prkey);
}catch(Exceptione){
}
}
publicstaticvoidencrypt()throwsException{
Strings="HelloWorld!";
//获取公钥及参数e,n
FileInputStreamf=newFileInputStream("pubkey.dat");
ObjectInputStreamb=newObjectInputStream(f);
RSAPublicKeypbk=(RSAPublicKey)b.readObject();
BigIntegere=pbk.getPublicExponent();
BigIntegern=pbk.getModulus();
System.out.println("e="+e);
System.out.println("n="+n);
//获取明文m
byteptext[]=s.getBytes("UTF-8");
BigIntegerm=newBigInteger(ptext);
//计算密文c
BigIntegerc=m.modPow(e,n);
System.out.println("c="+c);
//保存密文
Stringcs=c.toString();
BufferedWriterout=
newBufferedWriter(
newOutputStreamWriter(newFileOutputStream("encrypt.dat")));
out.write(cs,0,cs.length());
out.close();
}
publicstaticvoiddecrypt()throwsException{
//读取密文
BufferedReaderin=
newBufferedReader(
newInputStreamReader(newFileInputStream("encrypt.dat")));
Stringctext=in.readLine();
BigIntegerc=newBigInteger(ctext);
//读取私钥
FileInputStreamf=newFileInputStream("privatekey.dat");
ObjectInputStreamb=newObjectInputStream(f);
RSAPrivateKeyprk=(RSAPrivateKey)b.readObject();
BigIntegerd=prk.getPrivateExponent();
//获取私钥参数及解密
BigIntegern=prk.getModulus();
System.out.println("d="+d);
System.out.println("n="+n);
BigIntegerm=c.modPow(d,n);
//显示解密结果
System.out.println("m="+m);
byte[]mt=m.toByteArray();
System.out.println("PlainTextis");
for(inti=0;i<mt.length;i++){
System.out.print((char)mt[i]);
}
}
publicstaticvoidmain(Stringargs[]){
try{
generateKey();
encrypt();
decrypt();
}catch(Exceptione){
System.out.println(e.toString());
}
}
}
以上这篇RSA加密算法java简单实现方法(必看)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。