php Function Openssl_Pkey_Export
Article about php function openssl_pkey_export
The openssl_pkey_export() function returns a resource identifier that has new private and public keys. The new keys can be used with the openssl_sign() and openssl_encrypt() functions.
These functions are used to create and verify digital signatures and encryptions. You need to have a public key available to encrypt data and a private key to decrypt the encrypted data. The public key can be put out on the internet while the private key needs to be protected.
A key is base64 encoded and the result is returned as a string in PEM format. This can then be parsed with a tool like hex2bin in order to get the actual bytes that form the key. This is needed when the keys are being exported for use with a Java library, since it can only take input in byte array form.
The hex2bin method also helps when the keys are being exported for use with Nextcloud encryption. The encryption module uses a specific hex-encoded format for the RSA keys (detailed in this article). This means that the hex2bin method must be used to convert the PEM RSA key to the correct hex-encoded form.
The hex-encoded form can then be used with the openssl_sign() function to generate a digital signature that can be verified by using the private key. This signature can then be attached to the encrypted data and stored in a file, for example the Nextcloud file format described here. The file is split into an 8192 bytes sized header and one or more 8192 bytes sized encrypted blocks. Each block contains the encrypted data and an RSA signature that is derived from a hash of the contents of the file, for example the SHA512 hash of 'HBEGIN:cipher:AES-256-CTR:keyFormat:hash:HEND'.