shika92

Blum Blum Shub algorithm [Java]

Dec 16th, 2012
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. /**
  2.  * @author Donato Braico
  3.  * @version 1.0
  4.  */
  5. public class RandomNumber {
  6.    
  7.     static int modp;
  8.     static int modq;
  9.     static int p;
  10.     static int q;
  11.     static long n;
  12.     static long seme;
  13.     static long x;
  14.     static long[] seq;
  15.    
  16.     public static void init (int num) {
  17.         //Default
  18.         modp=4;
  19.         modq=4;
  20.         p=4;
  21.         q=4;
  22.         seme=0;
  23.         seq=new long[num];
  24.     }
  25.    
  26.     /**
  27.      * This method generates pseudo-random numbers using the Blum Blum Shub algorithm
  28.      * @param num - numbers generated
  29.      */
  30.     public static void generate(int num) {
  31.         init(num);
  32.        
  33.         //1 step
  34.         while (modp!=3 || modq!=3) {
  35.             p=(int)Math.round(Math.random()*100000000);
  36.             q=(int)Math.round(Math.random()*100000000);
  37.             modp=p%4;
  38.             modq=q%4;
  39.         }
  40.         n=Math.abs(q*p);
  41.        
  42.        
  43.         //2 step
  44.         while (seme < 1 || seme > (n-1) || !(coprimi(seme,n))) {
  45.         seme=Math.round(Math.random()*100000000);
  46.         }
  47.         x=(long)Math.pow(seme, 2)%n;
  48.        
  49.        
  50.         //3 step
  51.         seq[0]=x;
  52.         for (int i=1; i<num; i++) {
  53.             seq[i]=(long)Math.pow(seq[i-1], 2)%n;
  54.             long z=seq[i]%100;
  55.             System.out.println(z);
  56.         }
  57.     }
  58.    
  59.     /**
  60.      * @param a
  61.      * @param b
  62.      * @return true - if the MCD between a and b is 1;
  63.      */
  64.     private static boolean coprimi (long a, long b) {
  65.         boolean result=false;
  66.         long resto;
  67.        
  68.         if (b==0) {
  69.             if (a==1) {
  70.                 result=true;
  71.             }
  72.         }
  73.         else {
  74.             resto=a%b;
  75.             if (resto==0) {
  76.                 if (b==1) {
  77.                     result=true;
  78.                 }
  79.             }
  80.             else {
  81.                 return(coprimi (b,resto));
  82.             }
  83.         }  
  84.         return result;
  85.     }
Advertisement
Add Comment
Please, Sign In to add comment