RSA Key Generation - Problem

Implement a simplified RSA key generation, encryption, and decryption system. RSA is a public-key cryptosystem that uses the mathematical properties of large prime numbers.

Your task:

  • Generate two distinct prime numbers p and q within a given range
  • Calculate n = p × q (the modulus)
  • Calculate φ(n) = (p-1) × (q-1) (Euler's totient function)
  • Find a public exponent e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1
  • Calculate the private exponent d such that (d × e) mod φ(n) = 1
  • Encrypt a given message using the public key (e, n)
  • Decrypt the encrypted message using the private key (d, n)

Return an object containing the generated keys and the encryption/decryption results.

Input & Output

Example 1 — Basic RSA with Small Primes
$ Input: minPrime = 10, maxPrime = 20, message = 42
Output: {"p":11,"q":13,"n":143,"phi_n":120,"e":7,"d":103,"encrypted":123,"decrypted":42}
💡 Note: Found primes p=11, q=13. Calculated n=143, φ(n)=120. Used e=7, found d=103. Encrypted 42 to 123, decrypted back to 42.
Example 2 — Larger Prime Range
$ Input: minPrime = 5, maxPrime = 15, message = 25
Output: {"p":5,"q":7,"n":35,"phi_n":24,"e":5,"d":5,"encrypted":15,"decrypted":25}
💡 Note: Found primes p=5, q=7. With n=35 and φ(n)=24, e=5 works and d=5. Message 25 encrypts to 15, decrypts back to 25.
Example 3 — Single Digit Message
$ Input: minPrime = 3, maxPrime = 10, message = 2
Output: {"p":3,"q":5,"n":15,"phi_n":8,"e":3,"d":3,"encrypted":8,"decrypted":2}
💡 Note: Small primes p=3, q=5 give n=15, φ(n)=8. Using e=3 and d=3, message 2 encrypts to 8 and decrypts correctly.

Constraints

  • 2 ≤ minPrime ≤ maxPrime ≤ 100
  • 1 ≤ message < n (where n is the product of chosen primes)
  • Range must contain at least 2 prime numbers

Visualization

Tap to expand
INPUT: Prime Range10111213Green = Prime, Red = CompositeminPrime = 10maxPrime = 20message = 42Selected: p=11, q=13ALGORITHM: Key Generation1Calculate n = p × q = 1432Calculate φ(n) = (p-1)(q-1) = 1203Find e: gcd(e, φ(n)) = 1 → e = 74Find d: (d×e) mod φ(n) = 1 → d = 103Public Key: (e=7, n=143)Private Key: (d=103, n=143)Extended Euclidean AlgorithmRESULT: EncryptionENCRYPT: 42^7 mod 143Ciphertext: 123DECRYPT: 123^103 mod 143Original: 42Message successfullyencrypted and decrypted!Fast Modular ExponentiationKey Insight:RSA security relies on the computational difficulty of factoring large numbers.While n = p × q is easy to calculate, finding p and q from n is exponentially hard!TutorialsPoint - RSA Key Generation | Optimized Approach
Asked in
Google 45 Amazon 38 Microsoft 42 Meta 30 Apple 25
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen