Question

I need to sign the string with private Key using RSA phpseclib and then verify it in C# . I have seen many examples of how to encrypt in C# and decrypt in php, but none of how to sign string in php and verify in .NET.

here is php code:

include('Crypt/RSA.php');

$info = "Something";
$PrivateKey= "<RSAKeyValue><Modulus>3C5QWo4H+............"; //long string
$unsignedString = base64_encode($info);
$signedString = HashAndSignBytes($info, $PrivateKey);
file_put_contents('file.txt', $unsignedString."\n".$signedString);

function HashAndSignBytes($stringToSign, $Key) {
  $rsa = new Crypt_RSA();
  $rsa->loadKey($Key); // private key
  $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  $signature = $rsa->sign($stringToSign);
  return base64_encode($signature);
}

and here is my attempt to read the file and verify it in C#:

const string publicKey = @"<RSAKeyValue><Modulus>3C5QWo4H.....";
TextReader reader = new StreamReader(path, Encoding.ASCII);
var unsignedString = reader.ReadLine();
var signedString = reader.ReadLine();
reader.Close();

if (VerifySignedHash(unsignedString,signedString, publicKey)) {
  //some code
}

private bool VerifySignedHash(string stringToVerify, string signedString, string publicKey)
    {
        var byteConverter = new ASCIIEncoding();
        var dataToVerify = Convert.FromBase64String(stringToVerify);
        var signedData = Convert.FromBase64String(signedString);
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the 
            // key from RSAParameters.
            var rsaAlg = new RSACryptoServiceProvider();
            rsaAlg.FromXmlString(publicKey);

            // Verify the data using the signature.  Pass a new instance of SHA1CryptoServiceProvider
            // to specify the use of SHA1 for hashing.
            return rsaAlg.VerifyData(dataToVerify, new SHA1CryptoServiceProvider(), signedData);

        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    } 

verfication fails...

Was it helpful?

Solution

In your "signing" code, you base64encode the original string, then write that string to the output file. However, on the C# side, you read that value into unsignedString, but never reverse the base64 encoding.

The end result is that you're trying to verify the bytes of the base64Encoded string, not the data itself, so the VerifyData step fails.

Think that's your problem.

Modifying the following line might solve the problem:

var dataToVerify = Convert.FromBase64String(stringToVerify);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top