Advertisement
Es7evam

Java RSA

May 17th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. import java.math.*;
  2. import java.security.SecureRandom;
  3.  
  4. class myRSA{
  5.     public static void main(String[] args){
  6.         String msg = "Paz e felicidade a todos";
  7.         String msgcifrada = null;
  8.         String msgdecifrada = null;
  9.         BigInteger n, d, e;
  10.         int bitlen = 2048;
  11.  
  12.         //Escolha de forma aleatória dois números primos grandes p e q
  13.         SecureRandom r = new SecureRandom();
  14.         BigInteger p = new BigInteger(bitlen / 2, 100, r);
  15.         BigInteger q = new BigInteger(bitlen / 2, 100, r);
  16.  
  17.         //Compute n = p * q
  18.         n = p.multiply(q);
  19.  
  20.         //Compute a função totiente phi(n) = (p -1) (q -1)
  21.         BigInteger m = (p.subtract(BigInteger.ONE))
  22.                        .multiply(q.subtract(BigInteger.ONE));
  23.  
  24.         //Escolha um inteiro  "e"  , 1 < "e" < phi(n) ,  "e" e phi(n) sejam primos entre si.
  25.         e = new BigInteger("3");
  26.         while(m.gcd(e).intValue() > 1) e = e.add(new BigInteger("2"));
  27.  
  28.         // d seja inverso multiplicativo de "e"
  29.         d = e.modInverse(m);
  30.  
  31.         System.out.println("p:"+p);
  32.         System.out.println("q:"+q);
  33.         System.out.println("n:"+n);
  34.         System.out.println("e:"+e);
  35.         System.out.println("d:"+d);
  36.  
  37.         //mensagem cifrada - RSA_encrypt()
  38.         msgcifrada = new BigInteger(msg.getBytes()).modPow(e, n).toString();
  39.         System.out.println("msg cifrada: "+ msgcifrada);
  40.  
  41.         //mensagem decifrada - RSA_decrypt()
  42.         msgdecifrada = new String(new BigInteger(msgcifrada).modPow(d, n).toByteArray());
  43.         System.out.println("msg decifrada: " +msgdecifrada);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement