7 1. *p := large random prime*
8 2. *q := large random prime*
10 4. *f := (p - 1) * (q - 1)* (this step may differ in other versions)
11 5. *e := 65537* (most common, other constants exist)
12 6. *d := solve for x: 1 = (x * e) mod f*
13 7. *public key := (n,e)*
18 1. *m := message encoded as a number < n*
19 2. *encrypted := m^e mod n*
23 1. *m := encrypted^d mod n*
24 2. *decrypted := decode message from number m*
28 Here is a stupidly simple [C](c.md) code demonstrating the algorithm, for simplicity we use laughably small primes, we only consider 4 character string as a message and make other simplifications.
32 #define e 65537 // often used constant
34 typedef unsigned long long u64;
36 void generateKeys(u64 prime1, u64 prime2, u64 *privateKey, u64 *publicKey)
38 u64 f = (prime1 - 1) * (prime2 - 1);
40 *publicKey = prime1 * prime2;
43 while (*privateKey) // brute force solve the equation
45 if (((*privateKey) * e) % f == 1)
52 u64 powerMod(u64 n, u64 power, u64 mod) // helper func, returns n^power % mod
56 for (int i = 0; i < power; ++i)
57 result = (result * n) % mod;
62 u64 encryptNum(u64 n, u64 publicKey)
64 return powerMod(n,e,publicKey);
67 u64 decryptNum(u64 n, u64 publicKey, u64 privateKey)
69 return powerMod(n,privateKey,publicKey);
78 const char *str = "bich"; // we'll only consider 4 char string
80 puts("generating keys, wait...");
82 generateKeys(prime1,prime2,&priv,&pub);
84 printf("prime1 = %llu\nprime2 = %llu\nprivate key = %llu\npublic key = %llu\n",
85 prime1,prime2,priv,pub);
87 u64 data = str[0] | (str[1] << 7) | (str[2] << 14) | (str[3] << 21);
89 printf("string to encode: \"%s\"\n",str);
90 printf("string as numeric data: %lld\n",data);
94 puts("Data is too big, choose bigger primes or smaller data.");
98 puts("encrypting...");
100 u64 encrypted = encryptNum(data,pub);
101 printf("encrypted: %lld\n",encrypted);
103 puts("decrypting...");
105 data = decryptNum(encrypted,pub,priv);
106 printf("decrypted: %lld\n",data);
108 printf("retrieved string: \"%c%c%c%c\"\n",data & 0x7f,(data >> 7) & 0x7f,
109 (data >> 14) & 0x7f,(data >> 21) & 0x7f);
115 The program prints out:
118 generating keys, wait...
121 private key = 323099873
122 public key = 601528397
123 string to encode: "bich"
124 string as numeric data: 219739362
129 retrieved string: "bich"