# Importing and exporting RSA/DSA/EC keys
Date: 2024-09-19

#### 2024-09-19

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 57 f9 66 14 df 4a d7 de 96 e1 47 15 74 f7 3d 45 92 57 cb 10 59 8f 4a
    [51] 30 94 8b 8e f5 68 cf e8 69 68 7c 9a 01 0a 03 87 22 e4 7b d1 35 41 5b 9b 71
    [76] 7a ab 80 80 9e ab 82 92 94 e2 1f 3a 3b 23 7b 11

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: af2665235263f96301de9d9f010bd81f
    sha256: 91c0d38bb3989fedc73c2a05d42ec6472d835caa6cd7cbc0f14233f882e9f22b

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-----
    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV/lmFN9K196W4UcVdPc9RZJXyxBZ
    j0owlIuO9WjP6GlofJoBCgOHIuR70TVBW5txequAgJ6rgpKU4h86OyN7EQ==
    -----END PUBLIC KEY-----

    cat(write_pem(key, password = NULL))

    -----BEGIN PRIVATE KEY-----
    MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgFXoJwUEfEkynl/c/
    fnusjIPW2LW+lfb9HDldjLKfFiChRANCAARX+WYU30rX3pbhRxV09z1FklfLEFmP
    SjCUi471aM/oaWh8mgEKA4ci5HvRNUFbm3F6q4CAnquCkpTiHzo7I3sR
    -----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-----
    MIHrMFYGCSqGSIb3DQEFDTBJMDEGCSqGSIb3DQEFDDAkBBDkz2izLVka5QxrQyP2
    RteeAgIIADAMBggqhkiG9w0CCQUAMBQGCCqGSIb3DQMHBAjxF7XvUl7MDgSBkMJh
    VjN11Ic7Al1tk0aQUdM1p13rnbyV4PNXloY1CTyM3dOwDR3h6Z/UWJ8oTO6QOnTe
    lfU0MDF7YOuFX8GmG1zek7cqLY9N/OcYBXTVTbdjBPJEHYCqh8nWBlNKOVFwpHY8
    ywDAJ0ZGBRMKfqcqVZZmDdEjhy4B5hBx9mYNRw5uHf1MqILNHaEgewSH7D9q7A==
    -----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 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFf5ZhTfStfeluFHFXT3PUWSV8sQWY9KMJSLjvVoz+hpaHyaAQoDhyLke9E1QVubcXqrgICeq4KSlOIfOjsjexE="

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: af2665235263f96301de9d9f010bd81f
    sha256: 91c0d38bb3989fedc73c2a05d42ec6472d835caa6cd7cbc0f14233f882e9f22b

### 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": "V_lmFN9K196W4UcVdPc9RZJXyxBZj0owlIuO9WjP6Gk",
        "y": "aHyaAQoDhyLke9E1QVubcXqrgICeq4KSlOIfOjsjexE"
    }

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: af2665235263f96301de9d9f010bd81f
    sha256: 91c0d38bb3989fedc73c2a05d42ec6472d835caa6cd7cbc0f14233f882e9f22b