Date: 2025-02-03

# Importing and exporting RSA/DSA/EC keys

#### 2025-02-03

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 15 c0 e2 7e 6e bf 90 cf c3 60 c3 c8 83 0d cc f8 91 cc f4 3a ea 66 a2
    [51] 71 37 99 97 01 b6 de b8 dd e7 a2 e9 dd 61 e5 49 b8 e3 f3 a6 31 ec 7a bd b6
    [76] 83 43 bc 62 e5 39 26 3d 07 6d 93 7e e1 51 39 80

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: 37d37b4589dd22c4c9229d846fe75be4
    sha256: 80141804b076cadcda0fab84c5a8a2fb6a38eb4742ec9ff96ddb238ae77aa6bd

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-----
    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFcDifm6/kM/DYMPIgw3M+JHM9Drq
    ZqJxN5mXAbbeuN3noundYeVJuOPzpjHser22g0O8YuU5Jj0HbZN+4VE5gA==
    -----END PUBLIC KEY-----

    cat(write_pem(key, password = NULL))

    -----BEGIN PRIVATE KEY-----
    MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgaXHM9DeZUL2N/Ajs
    yMs7mIziZ9nBvrkBxjh3+ic4NIyhRANCAAQVwOJ+br+Qz8Ngw8iDDcz4kcz0Oupm
    onE3mZcBtt643eei6d1h5Um44/OmMex6vbaDQ7xi5TkmPQdtk37hUTmA
    -----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-----
    MIHrMFYGCSqGSIb3DQEFDTBJMDEGCSqGSIb3DQEFDDAkBBCFShD+VoPfO6qeEAAP
    824hAgIIADAMBggqhkiG9w0CCQUAMBQGCCqGSIb3DQMHBAh9sLc0lbo9LgSBkO/t
    2TGn5lizHodzFmiBmrQUFP6+nrpOxevTvzMZnlPaz3d5G8vZHh5USOnS8alx/oHf
    dlzUfT2HyHgUlAvIBkO12wmpzenwPA4m8nosKAwni5o0lAuB5qI5gP1WCIstJHSU
    kSd4bQrRVsUWlMJ/QGvciiiXZYTiKB6Cq3kPh5gyOnb5FTe9z9aFwHRq0KLY/Q==
    -----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 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBXA4n5uv5DPw2DDyIMNzPiRzPQ66maicTeZlwG23rjd56Lp3WHlSbjj86Yx7Hq9toNDvGLlOSY9B22TfuFROYA="

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: 37d37b4589dd22c4c9229d846fe75be4
    sha256: 80141804b076cadcda0fab84c5a8a2fb6a38eb4742ec9ff96ddb238ae77aa6bd

### 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": "FcDifm6_kM_DYMPIgw3M-JHM9DrqZqJxN5mXAbbeuN0",
        "y": "56Lp3WHlSbjj86Yx7Hq9toNDvGLlOSY9B22TfuFROYA"
    }

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: 37d37b4589dd22c4c9229d846fe75be4
    sha256: 80141804b076cadcda0fab84c5a8a2fb6a38eb4742ec9ff96ddb238ae77aa6bd