Date: 2021-04-30

# Fun with bignum: how RSA encryption works

#### 2021-04-30

Primitive types such as `int` or `double` store numbers in exactly 4 or 8 bytes, with finite precision. This suffices for most applications, but cryptography requires arithmetic on very large numbers, without loss of precision. Therefore OpenSSL uses 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`, even 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: b71e2d9ef93ab262dfc3229286baa3db

    (pubkey <- key$pubkey)

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

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] 10988763512914053609129625494419572235848750201139678569244159456628964521627756481457165933153030539904939616060144598000664331321665142458375877546346159
    ## $p
    ## [b] 112105610610405211692908539629710254131816974810581885682250558439479273146159
    ## $q
    ## [b] 98021530350543568917230983332053474733284372558083582597521086756833694800001
    ## $d
    ## [b] 6589368101896781860402294159103937764875109238362882464756186924730483188663517466137792997556368910914618423467155239620029393661171425112335683787273473
    ## $dp
    ## [b] 66741300474330227880772883878303934959810533075735438510526420779607897833951
    ## $dq
    ## [b] 19270174054906439750516562998766757228186152189425040483794828597205324073473
    ## $qi
    ## [b] 333939924285757651991354366564015378608203218994727397805334955879079518160

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] 10988763512914053609129625494419572235848750201139678569244159456628964521627756481457165933153030539904939616060144598000664331321665142458375877546346159

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] 1357530341088342621234001964285506960663573443806271101574662441548649319974318133999248828199780226377848037088766058472744045930995192526214170376381666

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

    base64_encode(c)

    ## [1] "Get4V4jaLfdpVenpguPTCxf2dfNECZQCLbpsayjGalpR3w5BRgqGLGlmabY1+R400rDeuHCyFb7RrZWfee+k4g=="

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.