I own 2 websites, example.com
and domain.com
. I want to securely transfer data from example.com
to domain.com
. I was looking at this question which is trying to answer my main question of how to send data securely from one website to another. However, the answer's are very old.
I am wondering how I can send do this. I have the below code which basically has the encryption keys saved locally on both websites and encrypts/decrypts data based on that. However, if someone managed to guess the key, they can decrypt all the messages. Is the way I have stated below a secure method to transfer data? Or is there a better way?
function encrypt($key, $data) {
$encryption_key = base64_decode( $key );
if ($encryption_key === FALSE) {
return FALSE;
}
$iv = openssl_cipher_iv_length('aes-256-cbc');
if ($iv === FALSE) {
return FALSE;
}
$iv = openssl_random_pseudo_bytes($iv);
if ($iv === FALSE) {
return FALSE;
}
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
if ($encrypted === FALSE) {
return FALSE;
}
return base64_encode($encrypted . '::' . $iv);
}
function decrypt($key, $data) {
$encryption_key = base64_decode( $key );
if ($encryption_key === FALSE) {
return FALSE;
}
$decoded_data = base64_decode($data);
if ($decoded_data === FALSE) {
return FALSE;
}
list($encrypted_data, $iv) = array_pad(explode('::', $decoded_data, 2),2,null);
$decryption = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
if ($decryption === FALSE) {
return FALSE;
}
return $decryption;
}
So this is what would be used, and I would send the encrypted data via POST request using cURL to domain.com
// On example.com (aka sending data)
$example_key = 'key_is_123';
$data = "My secret is that I like apples";
$encrypted_msg = encrypt($example_key, $data);
echo("Sending encrypted message:\n$encrypted_msg\n\n");
// Send $encrypted_msg message via a POST request using cURL to domain.com
// On domain.com (aka receiving data)
$domain_key = $example_key;
$decrypted_msg = decrypt($domain_key, $encrypted_msg);
echo("Recieved messaged and decrypted message:\n$decrypted_msg");