Date: 2022-05-24

# Importing and exporting RSA/DSA/EC keys

#### 2022-05-24

The `openssl` package implements a modern interface to libssl and libcrypto for R. It builds on the new `EVP` api which was introduced in OpenSSL 1.0 and provides a unified API to the various methods and formats. OpenSSL supports three major public key crypto systems:

- RSA : Most popular method. Supports both encryption and signatures.
- DSA : Digital Signature Algorithm. Mostly for signatures, not very popular anymore.
- ECDSA : Elliptic Curve DSA. Supports signatures and encryption via Diffie Hellman. Gaining popularity.

For each type there are several common formats for storing keys and certificates:

- DER: binary format, serialized ASN.1 structure
- PEM: base64 encoded DER + header wrapped in `===`
- SSH: single line of base64 with a header. Only for pubkeys.
- JWK: JSON Web key. Stores key data in a JSON object

The openssl package automatically detects the format when possible. However being able to recognize the various formats can be useful.

### The DER format

DER is the standard binary format using by protocols for storing and exchanging keys and certificates. It consists of a serialized ASN.1 structure which hold the key’s (very large) prime numbers.

    key <- ec_keygen()
    pubkey <- key$pubkey
    bin <- write_der(pubkey)
    print(bin)

     [1] 30 59 30 13 06 07 2a 86 48 ce 3d 02 01 06 08 2a 86 48 ce 3d 03 01 07 03 42
    [26] 00 04 f8 d2 ee ea 51 09 5d bc c5 1d d7 22 8f 44 a8 e9 c5 a9 0d b5 38 0e 8d
    [51] 58 67 e9 e4 bb 76 5f 49 6d fa 4b 38 17 45 07 bf 65 27 93 84 d6 a7 13 ec 33
    [76] db b4 89 9b 04 80 01 d9 a6 2b a9 26 2d 23 62 6b

To read a DER key use `read_key` or `read_pubkey` with `der = TRUE`.

    read_pubkey(bin, der = TRUE)

    [256-bit ecdsa public key]
    md5: 860b767da000d9b7fd9e7360ec91cf31
    sha256: 4898b4e8676aa99b3d50cfc53fddcdb06fc39e6971838a86ce31200f4c110479

Users typically don’t need to worry about the key’s underlying primes, but have a look at `key$data` if you are curious.

### The PEM format

In practice the user rarely encounters DER because it is mainly for internal use. When humans exchange keys and certificates they typically use the PEM format. PEM is simply base64 encoded DER data, plus a header. The header identifies the key (and possibly encryption) type.

    cat(write_pem(pubkey))

    -----BEGIN PUBLIC KEY-----
    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+NLu6lEJXbzFHdcij0So6cWpDbU4
    Do1YZ+nku3ZfSW36SzgXRQe/ZSeThNanE+wz27SJmwSAAdmmK6kmLSNiaw==
    -----END PUBLIC KEY-----

    cat(write_pem(key, password = NULL))

    -----BEGIN PRIVATE KEY-----
    MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg24nhKvgwtndxZrvG
    YWKjv3RzHdQqpsEfEEDTqkIKoB2hRANCAAT40u7qUQldvMUd1yKPRKjpxakNtTgO
    jVhn6eS7dl9JbfpLOBdFB79lJ5OE1qcT7DPbtImbBIAB2aYrqSYtI2Jr
    -----END PRIVATE KEY-----

The PEM format allows for protecting private keys with a password. R will prompt you for the password when reading such a protected key.

    cat(write_pem(key, password = "supersecret"))

    -----BEGIN ENCRYPTED PRIVATE KEY-----
    MIHjME4GCSqGSIb3DQEFDTBBMCkGCSqGSIb3DQEFDDAcBAgk05QNKRbOFAICCAAw
    DAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQIj3cnvtPspNAEgZAkovJRCmwBBXQ/
    ZMXN/ZvS8e7sAgz6ik93HTWXxpT3cxew5KTCGqfzWRliYDw1au2NMZ8oPwfnxfrZ
    ABdI+badlVYtnSODzVyKVOcosZRaZWNVE/rsCgaC2xltcb3LApjq2cZelJNuREst
    Di1lKJBPKBAv2MDiUg6T9LHlrJnTA6MFSQQCI7gzWOsBI993xq8=
    -----END ENCRYPTED PRIVATE KEY-----

### The OpenSSH format

For better or worse, OpenSSH uses a custom format for public keys. The advantage of this format is that it fits on a single line which is nice for e.g. your `~/.ssh/known_hosts` file. There is no special format for private keys, OpenSSH uses PEM as well.

    str <- write_ssh(pubkey)
    print(str)

    [1] "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPjS7upRCV28xR3XIo9EqOnFqQ21OA6NWGfp5Lt2X0lt+ks4F0UHv2Unk4TWpxPsM9u0iZsEgAHZpiupJi0jYms="

The `read_pubkey` function will automatically detect if a file contains a `PEM` or `SSH` key.

    read_pubkey(str)

    [256-bit ecdsa public key]
    md5: 860b767da000d9b7fd9e7360ec91cf31
    sha256: 4898b4e8676aa99b3d50cfc53fddcdb06fc39e6971838a86ce31200f4c110479

### The JSON Web Key (JWK) format

Yet another recent format to store RSA or EC keys are JSON Web Keys (JWK). JWK is part of the Javascript Object Signing and Encryption (JOSE) specification. The `write_jwk` and `read_jwk` functions are implemented in a separate package which uses the `openssl` package.

    library(jose)
    json <- write_jwk(pubkey)
    jsonlite::prettify(json)

    {
        "kty": "EC",
        "crv": "P-256",
        "x": "-NLu6lEJXbzFHdcij0So6cWpDbU4Do1YZ-nku3ZfSW0",
        "y": "-ks4F0UHv2Unk4TWpxPsM9u0iZsEgAHZpiupJi0jYms"
    }

Keys from `jose` and `openssl` are the same.

    mykey <- read_jwk(json)
    identical(mykey, pubkey)

    [1] TRUE

    print(mykey)

    [256-bit ecdsa public key]
    md5: 860b767da000d9b7fd9e7360ec91cf31
    sha256: 4898b4e8676aa99b3d50cfc53fddcdb06fc39e6971838a86ce31200f4c110479