You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3KB

  1. // p = 5, q = 11
  2. // RSA-Modul N = p * q = 55
  3. // Phi(N) = Phi(p)*Phi(q) | weil eigenschaft eulersche phi funktion und p,q teilerfremd
  4. // = (p-1)*(q-1) | p,q primzahlen, daher nur durch 1 und sich selbst teilbar und alle anderen teilerfremd
  5. // = 4*10 = 40
  6. // e: 1 < e < Phi(N) und ggT(e, Phi(N)) = 1
  7. // e elem aus {3,..} => e = 3
  8. // (e,N) = (3, 55) public key
  9. // -----
  10. // d: e*d kongr 1 mod Phi(N) => e*d mod Phi(N) = 1
  11. // 3*d mod 40 = 1
  12. // Durch probieren: d=27 => (27, 55) private key
  13. //
  14. // ----
  15. // Verschlüsseln
  16. // 13
  17. // c = m^e (mod N) => 13^3 (mod 55) = 52 = c
  18. // ----
  19. // Entschlüsseln
  20. // m = c^d (mod N) => 52^27 (mod 55) = 13 = m
  21. import java.math.BigInteger;
  22. public class RSA {
  23. private int bitLength;
  24. private BigInteger p;
  25. private BigInteger q;
  26. private BigInteger n;
  27. private BigInteger phiP;
  28. private BigInteger phiQ;
  29. private BigInteger phiN;
  30. private BigInteger e;
  31. private BigInteger d;
  32. public RSA (int bitLength) {
  33. this.bitLength = bitLength;
  34. this.p = Prime.generate(bitLength);
  35. this.q = Prime.generate(bitLength);
  36. this.n = p.multiply(q);
  37. this.phiP = p.subtract(BigInteger.ONE);
  38. this.phiQ = q.subtract(BigInteger.ONE);
  39. this.phiN = phiP.multiply(phiQ);
  40. }
  41. private void findPublicKey () {
  42. BigInteger check;
  43. do {
  44. this.e = Prime.generate(this.bitLength*2/3);
  45. check = this.e.gcd(phiN);
  46. } while (!check.equals(BigInteger.ONE));
  47. }
  48. private void findPrivateKey () {
  49. this.d = e.modInverse(phiN);
  50. }
  51. private void endKeyCreation () {
  52. this.p = BigInteger.ZERO;
  53. this.q = BigInteger.ZERO;
  54. this.phiP = BigInteger.ZERO;
  55. this.phiQ = BigInteger.ZERO;
  56. this.phiN = BigInteger.ZERO;
  57. }
  58. public void createKeys() {
  59. this.findPublicKey();
  60. this.findPrivateKey();
  61. this.endKeyCreation();
  62. }
  63. public BigInteger getPublicKey () {
  64. return e;
  65. }
  66. public BigInteger getPrivateKey () {
  67. return d;
  68. }
  69. public BigInteger getRSAModule() {
  70. return n;
  71. }
  72. static BigInteger cipher (BigInteger message, BigInteger key, BigInteger module) {
  73. return message.modPow(key, module);
  74. }
  75. }