Implementation of RSA algorithm (Java version)

Source: Internet
Author: User
Tags pow

Package RSA; Import Java.math.BigInteger;

public class RSA {
Private long p,q,e,d,n;
Public RSA () {
int pindex = (int) (Math.random () *10);
int qindex;
int eindex;
do{
Qindex = (int) (Math.random () *10);
}
while (Qindex==pindex);
do{
Eindex = (int) (Math.random () *10);
}
while (eindex==pindex| | Eindex==pindex);
p = 1033;
Q = 2017;
e = 29437;
n = p*q;
D = calculated ();
}
Private long calculated () {
Long T0 = 0,T1 = 1,t2 =-1;
Long R0 = (p-1) * (q-1), m = R0,R1 = e, r2 =-1;
do{
Long q = R0/R1;
r2 = r0-r1*q;
if (r2==0) break;
t2 = t0-t1*q;
while (t2<0) {
T2+=m;
}
if (t2>=m) {
T2%= m;
}
R0 = R1;
r1 = R2;
t0 = t1;
T1 = T2;
}while (r2!=0);
if (r1!=1) {
return 0;
}
else{
return T2;
}
}

Public long Gete () {
return e;
}
Public Long Getn () {
return n;
}
Public Long getd () {
return D;
}
Public BigInteger encode (BigInteger data) {
Return pow (data,d). MoD (New BigInteger (n+ ""));
}
Public BigInteger decode (BigInteger code) {
Return pow (code,e). MoD (New BigInteger (n+ ""));
}
Public BigInteger pow (BigInteger data,long p) {
data = Data.pow ((int) p),
return data;
}
public static void Main (String args[]) {
RSA RSA = new RSA ();

BigInteger data = new BigInteger ("222222");
Long oldtime = System.currenttimemillis ();
BigInteger code = rsa.encode (data);
Long newtime = System.currenttimemillis ();
Double codetime = (double) (newtime-oldtime)/1000;
Oldtime = System.currenttimemillis ();
BigInteger decode = Rsa.decode (code);
NewTime = System.currenttimemillis ();
Double decodetime = (double) (newtime-oldtime)/1000;
System.out.println ("Privatekey:" +RSA.D);
System.out.println ("Publickkey:" +RSA.E);
System.out.println ("N:" +RSA.N);
SYSTEM.OUT.PRINTLN ("Data:" +data);
System.out.println ("Code:" +code+ "Time:" +codetime);
System.out.println ("Decode:" +decode+ "Time:" +decodetime);

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.