Date: 2025-02-03

# Fun with bignum: how RSA encryption works

#### 2025-02-03

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: 41d04ddc156fb51d5752e1c7c7d91517
    ## sha256: b4c91dbb88dfa8ccf6d4accb5b74f250b6019b832355a89ef41c0204c4578afa

    (pubkey <- key$pubkey)

    ## [512-bit rsa public key]
    ## md5: 41d04ddc156fb51d5752e1c7c7d91517
    ## sha256: b4c91dbb88dfa8ccf6d4accb5b74f250b6019b832355a89ef41c0204c4578afa

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] 12322691924814280299065125504002164963827938383053910042641609734954209625013418120432570766226383521174726317014186630718085048549515593699757540109013101
    ## $p
    ## [b] 114689525515530080937100482496088796491173192185024904336770299028816759416279
    ## $q
    ## [b] 107443917562861200983124993697972311056923743336007549277295036413569178512219
    ## $d
    ## [b] 10235221858297837070351253594310967084333640933847133576013488959247942397997975548953614255002546035084755227585606124577778540613400059455139774742557493
    ## $dp
    ## [b] 100763052774138372679208823742958890598673439931970474187205655549998324464499
    ## $dq
    ## [b] 44363220917207441576565334535714645729898477114795676998391804405926148138313
    ## $qi
    ## [b] 58537062115441922170827935360594247857370220501628283892658556210665904970394

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

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

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

    base64_encode(c)

    ## [1] "XwmsNk0X2/xckR6Go7eiU0SBQuJXrF4VrqnRgnDEudX2OBx9y0xxSEmBLEy0MywieRUxiCBLJB2EvsgdJ9eMOg=="

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.