Guest User

Untitled

a guest
Jul 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import java.math.*;
  2. import java.util.*;
  3.  
  4. class DHKey {
  5. BigInteger value;
  6.  
  7. DHKey (BigInteger val) {
  8. value = val;
  9. }
  10. }
  11.  
  12. class DHData {
  13. BigInteger value;
  14.  
  15. DHData (BigInteger val) {
  16. this.value = val;
  17. }
  18.  
  19. public static DHData init(BigInteger val) {
  20. return new DHData(val);
  21. }
  22. }
  23.  
  24. class DHConfig {
  25. BigInteger p;
  26. BigInteger g;
  27.  
  28. DHConfig () {
  29. Random r = new Random();
  30. this.p = BigInteger.probablePrime(100, r);
  31. this.g = BigInteger.probablePrime(100, r);
  32. }
  33.  
  34. public static DHConfig init () {
  35. return new DHConfig();
  36. }
  37. }
  38.  
  39. class DHClient {
  40. private DHKey privateKey;
  41. public DHKey publicKey;
  42.  
  43. private DHConfig config;
  44.  
  45. DHClient (DHConfig config) {
  46. this.config = config;
  47.  
  48. this.privateKey = new DHKey (new BigInteger(4, new Random()));
  49. this.publicKey = new DHKey (this.modPow(config.g, this.config.p, this.privateKey.value));
  50.  
  51. }
  52.  
  53. public DHKey getPublicKey () {
  54. return this.publicKey;
  55. }
  56.  
  57. public DHData decodeKey (DHKey receivedKey) {
  58. return DHData.init(this.modPow(receivedKey.value, this.config.p, this.privateKey.value));
  59. }
  60.  
  61. public BigInteger modPow (BigInteger first, BigInteger second, BigInteger exp) {
  62. return first.modPow(exp, second);
  63. }
  64. }
  65.  
  66.  
  67. class DHDriver {
  68. public static void main(String[] args) {
  69. DHConfig config = DHConfig.init();
  70. DHClient one = new DHClient(config);
  71. DHClient two = new DHClient(config);
  72.  
  73. System.out.println(two.decodeKey(one.getPublicKey()).value);
  74. System.out.println(one.decodeKey(two.getPublicKey()).value);
  75. }
  76. }
Add Comment
Please, Sign In to add comment