# Convert numeric value of RSA key to a .key file

After reading about RSA encryption in wikipedia I managed to create two number, a number d which is the private number, and a number n which is the public number.

But when I tried to use these keys to encrypt and decrypt php seems to prefer functions such as openssl_public_encrypt and libraries like phpseclib which seem to need a .key file or a .pem file or a .cem file... Which when I views them looked nothing like a number.

I'm a beginner and I do this kind of stuff because it fascinates me a lot.

So why don't they look like numbers?And how can I convert my numeric value a key to such a value?

In general an RSA private key consists of at least d and n, but this century it is usually stored with added CRT (Chinese Remainder Theorem) parameters as described in Wikipedia and specified more exactly in PKCS1 (Public Key Cryptography Standard 1) which was actually issued by the company RSA (later acquired by EMC and then Dell) but is more conveniently and stably available as several Internet RFCs, currently 8017 at 3.2.

(Native) phpseclib supports several formats for key files.

The first two are de-facto defined by OpenSSL, a widely used open source implementation since about 1995 (originally as SSLeay) of SSL/TLS protocols including the cryptography for those protocols including RSA.

A plain (unencrypted) PEM file simply consists of the PKCS1 RSAPrivateKey structure encoded in ASN.1 DER or BER converted to base64 and wrapped to lines shorter than 80 chars, with delimiter lines -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY---- added.

An encrypted PEM file consists of the same PKCS1 ASN.1 encoding first encrypted with Password-Based Encryption, then PEMized similarly: base64 plus BEGIN/END lines but adding some RFC822-style headers defining the encryption. This is documented in the man page for the function PEM_write_RSAPrivateKey also on the web for the current release.

The PuTTY format is also Password-Based Encrypted, with encodings of the public and private parts separated in a format defined by PuTTY, an implementation of SSH protocol which like SSL/TLS includes RSA. AFAICT it is not documented, but PuTTY is open source and the source file sshpubk.c effectively defines this format.

The XMLSig/XMLenc format is defined by public standards and using (unsurprisingly) XML. This might be best for your purpose, since it simply contains the various numbers as base64 of canonical big-endian, tagged using XML.

The OpenSSL binding isn't clearly specified but presumably supports the PEM formats supported by OpenSSL; in addition to the two PKCS1 formats described above, this includes plain and encrypted formats defined by PKCS8 which is basically an ASN.1 wrapper around PKCS1, optionally with Password-Based Encryption, similarly available as RFC 5208 optionally combined with PKCS5 and sometimes PKCS12.