# Importing and exporting RSA/DSA/EC keys
Date: 2024-08-16

#### 2024-08-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 03 42
    [26] 00 04 74 f7 cb ff 0e 4b 06 6b 07 36 e1 f4 8e c9 12 8e ef 53 83 d6 e6 ff b4
    [51] 6e 53 91 fa 66 26 e1 87 3a 76 75 a8 de a6 e4 44 94 a9 5a 08 f8 f9 e2 53 21
    [76] c7 a6 f5 66 8c b2 14 f7 11 66 14 6a 3c 2a c8 f0

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: f5be94510d749dc504bbc1df74cac698
    sha256: 2b06640c36b39990367e9c1e07fba155572c56eaf9bb909f9cc55b6e806f8f2d

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-----
    MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEdPfL/w5LBmsHNuH0jskSju9Tg9bm
    /7RuU5H6Zibhhzp2dajepuRElKlaCPj54lMhx6b1ZoyyFPcRZhRqPCrI8A==
    -----END PUBLIC KEY-----

    cat(write_pem(key, password = NULL))

    -----BEGIN PRIVATE KEY-----
    MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg57GCOqHMK10XhrNr
    tso27gafZrbQCCBv2XbF66g+iPahRANCAAR098v/DksGawc24fSOyRKO71OD1ub/
    tG5TkfpmJuGHOnZ1qN6m5ESUqVoI+PniUyHHpvVmjLIU9xFmFGo8Ksjw
    -----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-----
    MIHrMFYGCSqGSIb3DQEFDTBJMDEGCSqGSIb3DQEFDDAkBBDe8rCn3TZryKBJ1x4e
    vnjmAgIIADAMBggqhkiG9w0CCQUAMBQGCCqGSIb3DQMHBAhLRSIhQvvSRQSBkNTd
    YAomH8liHKNUsNCQWhy67MaqBRXqSg1+rCGKGVCaTrjYPsLuM2cc2E9asQOMMhJc
    uW3CywnjQjf4Phbf4gv0GMNcHFxP7VVoT2cz5TYUXWU9hz6NIJvcqUA78ca12v9G
    fV/jdux4WalCSQ1rRmrAd4c4hU6IDrXlfD7vUFEqTn4u1ClKhI4jSAVlgCjEEw==
    -----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 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHT3y/8OSwZrBzbh9I7JEo7vU4PW5v+0blOR+mYm4Yc6dnWo3qbkRJSpWgj4+eJTIcem9WaMshT3EWYUajwqyPA="

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: f5be94510d749dc504bbc1df74cac698
    sha256: 2b06640c36b39990367e9c1e07fba155572c56eaf9bb909f9cc55b6e806f8f2d

### 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": "dPfL_w5LBmsHNuH0jskSju9Tg9bm_7RuU5H6Zibhhzo",
        "y": "dnWo3qbkRJSpWgj4-eJTIcem9WaMshT3EWYUajwqyPA"
    }

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: f5be94510d749dc504bbc1df74cac698
    sha256: 2b06640c36b39990367e9c1e07fba155572c56eaf9bb909f9cc55b6e806f8f2d