Hayfa chouchene
Hayfa chouchene

Reputation: 1

RSA Keys signature generation using SHA256 matching algorithm with php_openssl to verify signature

I am encountering difficulties with verifying a digital signature sent from my frontend application to my Laravel backend via an API request. According to the documentation, the process involves several steps:

  1. Convert the parameters to a JSON string.
  2. Hash the JSON string using the SHA256 algorithm.
  3. Digitally sign the hashed value using the private key (not to be confused with the base64 private key).
  4. Encode the obtained digital signature in base64 to derive the value of base64signature.

I've implemented the signature generation process in my frontend app using the following code snippet:

const generateSignature2 = (data: string, privateKeyPem: string): string =\> {
// Convert PEM-formatted private key to Forge RSA private key
const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
// Create SHA-256 hash of the data
const md = forge.md.sha256.create();
md.update(data, "raw");
const digest = md.digest();

// Sign the hash using RSA private key
const signature = privateKey.sign(md);
console.log("signature ", signature);
// Convert signature bytes to Base64
const signatureBase64 = forge.util.encode64(signature);

return signatureBase64;
}

and here is my backend function to verify the recieved signature

public static function VerifyDigitalSignature($data,$base_64_digital_signature,$public_key){
$isVerified = openssl_verify($data, base64_decode($base_64_digital_signature),$public_key);
return $isVerified;
}

Here is the function that is firts called in my backend to check rsa login

 public function validateRsaLogin(Request $request){
        $parameters=json_encode($request->post('Parameters'),JSON_UNESCAPED_SLASHES);
        $data=hash('SHA256',$parameters);
    
        $signature=RsaKeys::VerifyDigitalSignature($data,$request->header('base64signature'),base64_decode($request->header('base64publickey')));
        if($signature===1){
           return true;
        }elseif($signature===0){
          return false;
        }elseif($signature===-1||$signature===false){
         return -1;
        }

        return true;
    }

but this does not recognize the signature, any idea how can i fix this ? the docs says that i should be using SHA-256

. 2/ The Json string is then hased with sha256 algorithm.

Upvotes: 0

Views: 158

Answers (0)

Related Questions