# Fun with bignum: how RSA encryption works

#### 2017-11-10

Primitive types such as `int` or `double` store numbers in exactly one or two bytes, with finite precision. This suffices for most applications, but cryptographic methods require arithmetic on much larger numbers and without loss of precision. Therefore OpenSSL provides a bignum data type which holds arbitrary sized integers and implements all basic arithmetic and comparison operators such as `+`, `-`, `*`, `^`, `%%`, `%/%`, `==`, `!=`, `<`, `<=`, `>` and `>=`.

One special case, the modular exponent `a^b %% m` can be calculated using `bignum_mod_exp` when `b` is too large for calculating `a^b`.

    # create a bignum
    y <- bignum("123456789123456789")
    z <- bignum("D41D8CD98F00B204E9800998ECF8427E", hex = TRUE)

    # size grows
    print(y * z)

    ## [b] 34808613111804879213872650915812112647840354642904626774

    # Basic arithmetic
    div <- z %/% y
    mod <- z %% y
    z2 <- div * y + mod
    stopifnot(z2 == z)
    stopifnot(div < z)

RSA involves a public key and a private key. The public key should be known by everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted in a reasonable amount of time using the private key. In RSA, this asymmetry is based on the practical difficulty of factoring the product of two large prime numbers.

### RSA key generation

An RSA key-pair is generated as follows (adapted from wikipedia):

- Choose two distinct prime numbers \(p\) and \(q\). Keep these secret.
- Compute the product \(n = p*q\). This \(n\) value is public and used as the modulus.
- Compute \(\phi(n) = (p − 1)(q − 1)\).
- Choose an integer \(e\) smaller than \(\phi(n)\) such that \(e\) and \(\phi(n)\) are coprime. OpenSSL always uses \(65537\).
- Compute a value for \(d\) such that \((d * e)\pmod{\phi(n)} = 1\).

OpenSSL has a key generator that does these things for us.

    (key <- rsa_keygen(512))

    ## [512-bit rsa private key]
    ## md5: a5e38c66ad18c78516e79777050b2bce

    (pubkey <- key$pubkey)

    ## [512-bit rsa public key]
    ## md5: a5e38c66ad18c78516e79777050b2bce

Usually we would use `rsa_encrypt` and `rsa_decrypt` to perform the encryption:

    msg <- charToRaw("hello world")
    ciphertext <- rsa_encrypt(msg, pubkey)
    rawToChar(rsa_decrypt(ciphertext, key))

    ## [1] "hello world"

Let’s look at how this works under the hood.

### How RSA encryption works

The `data` field of the private key extracts the underlying bignum integers:

    key$data

    ## $e
    ## [b] 65537
    ## $n
    ## [b] 10031635092209121498674987861649022163771061565130441373555584537047455688991931937563110507506652959265182705476941444174840580049331773111276155053075917
    ## $p
    ## [b] 112481050639317229656723018120659623829736571015511322021617837187076258724819
    ## $q
    ## [b] 89185111938335771293328323333111422985697062149139368049232365065924632677343
    ## $d
    ## [b] 6886694454027199678759881881737814611139109676622117091683160716943132564863007715345245794849719693156483947830169207322284232384798025277322134502462181
    ## $dp
    ## [b] 52192635456942444021864702092699683547649253468753517900993308037581656588213
    ## $dq
    ## [b] 45611141749503334703121678031583617867946479577226668887897236368991499663495
    ## $qi
    ## [b] 42778411805854319073840593976044429381982792060412061328990784688718929883751

You can verify that the equations above hold for this key. The public key is simply a subset of the key which only contains \(n\) and \(e\):

    pubkey$data

    ## $e
    ## [b] 65537
    ## $n
    ## [b] 10031635092209121498674987861649022163771061565130441373555584537047455688991931937563110507506652959265182705476941444174840580049331773111276155053075917

In order to encrypt a message into ciphertext we have to treat the message data as an integer. The message cannot be larger than the key size. For example convert the text `hello world` into an integer:

    m <- bignum(charToRaw("hello world"))
    print(m)

    ## [b] 126207244316550804821666916

To encrypt this message \(m\) into ciphertext \(c\) we calculate \(c = m^e\pmod n\). Using the public key from above:

    e <- pubkey$data$e
    n <- pubkey$data$n
    c <- (m ^ e) %% n
    print(c)

    ## [b] 4370010721699116474550336125846788313299380632320359442581524355012000986228559746077196379218623802065771428038722241551035284544273266543217347538455894

This is number represents out encrypted message! It is usually exchanged using base64 notation for human readability:

    base64_encode(c)

    ## [1] "U3Aq3qtS0/JAoDfLUbHNDBDZcOhb8MbWpql2Q5xTS+QtfO2YYOb9BRjvA3VkN1pimy3EE0htPLP1aE0fQmQNVg=="

The ciphertext can be decrypted using \(d\) from the corresponding private key via \(m = c^d \pmod{n}\). Note that `c^d` is too large to calculate directly so we need to use `bignum_mod_exp` instead.

    d <- key$data$d
    out <- bignum_mod_exp(c, d, n)
    rawToChar(out)

    ## [1] "hello world"

The only difference with the actual `rsa_encrypt` and `rsa_decrypt` functions is that these add some additional padding to the data.