Skip to content

Instantly share code, notes, and snippets.

@paragonie-scott
Created May 24, 2017 18:11
Show Gist options
  • Save paragonie-scott/3ea5ea4b03eba8c66122386d0d7e9c70 to your computer and use it in GitHub Desktop.
Save paragonie-scott/3ea5ea4b03eba8c66122386d0d7e9c70 to your computer and use it in GitHub Desktop.
RSA Encryption Homomorphism
<?php
/* Key generation */
$keypair = openssl_pkey_new([
"digest_alg" => "sha512",
"private_key_type" => OPENSSL_KEYTYPE_RSA,
'private_key_bits' => 1024
]);
$secret = null;
if (!openssl_pkey_export($keypair, $secret)) {
die(openssl_error_string());
}
$details = openssl_pkey_get_details($keypair);
$public = $details['key'];
/* Select a random message */
$message = random_bytes(128);
/* Multiply ciphertext by this factor */
$mult = gmp_init('3', 10);
$ciphertext = '';
openssl_public_encrypt($message, $ciphertext, $public, OPENSSL_NO_PADDING);
$cipherNumber = gmp_init(bin2hex($ciphertext), '16');
// $cipherPrime = $ciphertext;
$cipherMult = gmp_mul($cipherNumber, $mult);
$cipherPrimeHex = gmp_strval($cipherMult, '16');
if (mb_strlen($cipherPrimeHex, '8bit') & 1 === 1) {
$cipherPrimeHex = '0' . $cipherPrimeHex;
}
$cipherPrime = hex2bin($cipherPrimeHex);
$decrypted = '';
if (!openssl_private_decrypt($cipherPrime, $decrypted, $secret, OPENSSL_NO_PADDING)) {
die(openssl_error_string());
}
/* Verify plaintext was multiplied */
var_dump([
'before' => bin2hex($message),
'after ' => bin2hex($decrypted)
]);
array(2) {
["before"]=>
string(256) "2bc92edc3c4ef2ac334411e15f3692577443e038dbd91e01563cbc134ee80e260826955ccf1bbe5c3f0eb1048ca6c546d3c02525b6cc4d9d193680444ac7f76417cbf982b04e30d815716de12ead1d94c4ccc2125f48b232c7ff2319793ea39105a43ce1c86be69474e6ad86fab0247f2db0198c317d115aebc47c5157096ed7"
["after "]=>
string(256) "827f23db4f947b7ee89f028505c41e191df901e32f4de8d77a23c7c1ad18e177994740f328797c5075794ee76eb6149b8df8080a82210f3c0dfcb560e707b384b50e7a8d18c8826e703c9a51470822516ab0610fd8edfce05ec30996e73ac2796337f8592907d1a2fd22b9b6512134d3adc242372b1530f8c216a0705ea14a0b"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment