I have a CLI tool that writes encrypted data to the local filesystem that is never transmitted over the network.
I am able to encrypt the data using a password-protected SSH key, but since the generated key is assymetric (RSA), it can only encrypt/decrypt data that is shorter than the key, which is not ideal for my use case:
I generate the SSH key:
$config = [
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
"encrypt_key" => true,
"encrypt_key_cipher" => OPENSSL_CIPHER_AES_256_CBC
];
openssl_pkey_export( openssl_pkey_new( $config ), $privateKeyOut, $password );
if ( ! file_put_contents( $_SERVER['HOME'] . '/.ssh/fookey.pem', $privateKeyOut ) ) {
throw new \RuntimeException( 'Could not write private key.' );
}
Then I encrypt/decrypt as follows:
public function encrypt( string $plain_text ): string {
$key = openssl_pkey_get_private( file_get_contents( $_SERVER['HOME'] . '/.ssh/fookey.pem' ), App::getVar( 'enc_password' ) );
$success = openssl_private_encrypt( $plain_text, $cipher_text, $key );
if ( ! $success ) {
throw new \RuntimeException( 'Encrypt failed.' );
}
return base64_encode( $cipher_text );
}
public function decrypt( string $cipher_text ): string {
$key = openssl_pkey_get_private( file_get_contents( $_SERVER['HOME'] . '/.ssh/fookey.pem' ), App::getVar( 'enc_password' ) );
$success = openssl_private_decrypt( base64_decode( $cipher_text ), $plain_text, $key );
if ( ! $success ) {
throw new \RuntimeException( 'Decrypt failed.' );
}
return $plain_text;
}
PS: The value of App::getVar( 'enc_password' )
is provided by the user through an interactive input when he runs the script.
Is it possible to tweak this script to use a Symmetric encryption key instead, that can encrypt/decrypt large inputs?