Guest User

Untitled

a guest
Mar 24th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package wildarsa;
  7. import java.math.BigInteger;
  8. import java.util.Random;
  9. import java.io.*;
  10. /**
  11. *
  12. * @author wilda
  13. */
  14. public class Wildarsa { private BigInteger p;
  15. private BigInteger q;
  16. private BigInteger N;
  17. private BigInteger phi;
  18. private BigInteger e;
  19. private BigInteger d;
  20. private int bitlength = 1024;
  21. private int blocksize = 256; //blocksize in byte
  22.  
  23. private Random r;
  24. public Wildarsa() {
  25. r = new Random();
  26. p = BigInteger.probablePrime(bitlength, r);
  27. q = BigInteger.probablePrime(bitlength, r);
  28. N = p.multiply(q);
  29.  
  30. phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
  31. e = BigInteger.probablePrime(bitlength/2, r);
  32.  
  33. while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
  34. e.add(BigInteger.ONE);
  35. }
  36. d = e.modInverse(phi);
  37. }
  38.  
  39. public Wildarsa(BigInteger e, BigInteger d, BigInteger N) {
  40. this.e = e;
  41. this.d = d;
  42. this.N = N;
  43. }
  44.  
  45.  
  46. public static void main (String[] args) throws IOException
  47. {
  48. Wildarsa rsa_wilda = new Wildarsa();
  49. DataInputStream in=new DataInputStream(System.in);
  50. String teststring ;
  51. System.out.println("Enter the plain text:");
  52. teststring=in.readLine();
  53. System.out.println("Encrypting String: " + teststring);
  54. System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));
  55.  
  56. // encrypt
  57. byte[] encrypted = rsa_wilda.encrypt(teststring.getBytes());
  58. System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
  59.  
  60. // decrypt
  61. byte[] decrypted = rsa_wilda.decrypt(encrypted);
  62. System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
  63.  
  64. System.out.println("Decrypted String: " + new String(decrypted));
  65.  
  66. }
  67.  
  68. private static String bytesToString(byte[] encrypted) {
  69. String test = "";
  70. for (byte b : encrypted) {
  71. test += Byte.toString(b);
  72. }
  73. return test;
  74. }
  75.  
  76. public byte[] encrypt(byte[] message) {
  77. return (new BigInteger(message)).modPow(e, N).toByteArray();
  78. }
  79.  
  80. public byte[] decrypt(byte[] message) {
  81. return (new BigInteger(message)).modPow(d, N).toByteArray();
  82. }
  83.  
  84. }
Add Comment
Please, Sign In to add comment