疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

RSA算法的实现方法——Java版放送


 

  一开始不知道有BigInteger这个大数类,居然自己去实现了一个,写了大数加法后,才发现有现成的T_T
  
  以下是引用片段:
  packagersa;
  importjava.math.BigInteger;
  
  publicclassRSA{
  privatelongp,q,e,d,n;
  publicRSA(){
  intpIndex=(int)(Math.random()*10);
  intqIndex;
  inteIndex;
  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();
  }
  privatelongcalculateD(){
  longt0=0,t1=1,t2=-1;
  longr0=(p-1)*(q-1),m=r0,r1=e,r2=-1;
  do{
  longq=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){
  return0;
  }
  else{
  returnt2;
  }
  }
  
  publiclonggetE(){
  returne;
  }
  publiclonggetN(){
  returnn;
  }
  publiclonggetD(){
  returnd;
  }
  publicBigIntegerencode(BigIntegerdata){
  returnpow(data,d).mod(newBigInteger(n+""));
  }
  publicBigIntegerdecode(BigIntegercode){
  returnpow(code,e).mod(newBigInteger(n+""));
  }
  publicBigIntegerpow(BigIntegerdata,longp){
  data=data.pow((int)p);
  returndata;
  }
  publicstaticvoidmain(Stringargs[]){
  RSArsa=newRSA();
  
  BigIntegerdata=newBigInteger("222222");
  longoldtime=System.currentTimeMillis();
  BigIntegercode=rsa.encode(data);
  longnewtime=System.currentTimeMillis();
  doublecodetime=((double)(newtime-oldtime))/1000;
  oldtime=System.currentTimeMillis();
  BigIntegerdecode=rsa.decode(code);
  newtime=System.currentTimeMillis();
  doubledecodetime=((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);
  
  }
  
  }
  
  
  
  (转载)