I create a Signature() function for the sender to sign his/her private key and then return the $signature
use phpseclib\Crypt\RSA;
public function Signature(Request $request)
{
$agent_code = $request->agent_code;
$private_key = $request->private_key;
$private_passphrase = $request->private_passphrase;
$string = $agent_code;
$private_key = File::get($private_key);
$rsa = new RSA();
$rsa->setPassword($private_passphrase);
$rsa->loadKey($private_key); // private key
$signature = base64_encode($rsa->sign($string));
return $signature;
}
After that, the $signature is passed to Verify() function for the receiver to verify the signature using his/her public key
public function Verify(Request $request)
{
$agent_code = $request->agent_code;
$public_key = $request->public_key;
$signature = $request->signature;
$string = $agent_code;
$public_key = File::get($public_key);
$rsa = new RSA();
$rsa->loadKey($public_key); // public key
echo $rsa->verify($string, base64_decode($signature)) ? 'verified' : 'unverified';
}
Then, I test both function on Postman
Photo 1 - 3 is for the Signature() function
Photo 4 - 6 is for the Verify() function
Photo 1 : This url will call the Signature() function. The agent_code and private_passphrase param is filled. agent_code is the string to be signed by private key whereas private_passphrase is the passphrase for the private key.
Photo 2 : The private key is attached in body form as file format
Photo 3 : The $signature is returned
Photo 4 : This url will call the Verify() function. The agent_code and signature param is filled. the signature is copied from Signature() function that used to verified by the public key
Photo 5 : The public key is attached in body form as file format
Photo 6 : Invalid signature
error
I have no idea why it return Invalid Signature
, because if I write the signature and verify code in one function, it will echo 'verified' for me. The key pairs is correct and the $signature is copied correctly.
All the guidance and correction is appreciated.
I am converting my comment into an answer.
I believe that your issue is caused by the +
signs in the query parameter(s) - they are being recognized as URL-encoded spaces. If you were using POST instead of GET there would not be any issue.
In order to avoid the problem with URL-encoding caused by the usual Base64 encoding my advice is to use Base64URL encoding. It uses -
instead of +
and _
instead of /
compared to the normal Base64 encoding.