# Importing and exporting RSA/DSA/EC keys

#### 2019-07-16

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
    [24] 03 42 00 04 4b df c7 5a 39 16 a5 8c f6 10 44 98 58 6c 12 dc e7 a6 05
    [47] f5 1e e1 f0 4f f9 f1 77 32 c4 d3 6f 1b ee a5 ca c8 dc a3 58 12 e0 e3
    [70] 3c c9 54 9c 9e cd 42 2a c5 33 f4 74 a9 ae 26 a0 19 38 c7 da bb 54

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: 9373831d867f2dcc6094568a71fcdf7a

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-----
    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES9/HWjkWpYz2EESYWGwS3OemBfUe
    4fBP+fF3MsTTbxvupcrI3KNYEuDjPMlUnJ7NQirFM/R0qa4moBk4x9q7VA==
    -----END PUBLIC KEY-----

    cat(write_pem(key, password = NULL))

    -----BEGIN PRIVATE KEY-----
    MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgb3+Mn1O2yUs/mGco
    64fUYNnjSU/KiOgoVgfee7cjaLqhRANCAARL38daORaljPYQRJhYbBLc56YF9R7h
    8E/58XcyxNNvG+6lysjco1gS4OM8yVScns1CKsUz9HSpriagGTjH2rtU
    -----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-----
    MIHjME4GCSqGSIb3DQEFDTBBMCkGCSqGSIb3DQEFDDAcBAjo7vfyDtZfOgICCAAw
    DAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQIrLu8BhQ0K1AEgZBDKPVTByX3Rvke
    XTPUosgMA48g4MeNG0FcRIsyg5UBIEB5sAwpXU5HQ7sWYIeGgtgwoPxTgUGYu1NA
    8E/Y1DEBM0KWb2ddRou1UEfkvIKRfKn7g6qzmhqH6WEyjaNkj8JE3JeIqPGM+ZJ/
    4Ts7aU0UKW380aqbwX6ue1uoDFdUI7UuxfMsWhzpXGZIxIOLkO8=
    -----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 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEvfx1o5FqWM9hBEmFhsEtznpgX1HuHwT/nxdzLE028b7qXKyNyjWBLg4zzJVJyezUIqxTP0dKmuJqAZOMfau1Q="

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: 9373831d867f2dcc6094568a71fcdf7a

### 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": "S9_HWjkWpYz2EESYWGwS3OemBfUe4fBP-fF3MsTTbxs",
        "y": "7qXKyNyjWBLg4zzJVJyezUIqxTP0dKmuJqAZOMfau1Q"
    }

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: 9373831d867f2dcc6094568a71fcdf7a