I have a zip file which I'm signing using c# code with Bouncy castle. The generated signature file is identical ( I have compared output string as well as binary code) to signature file generated with openssl using following command
openssl dgst -sha256 -sign content_private_key.pem -out content.zip.sig content.zip
But when I verify signature file (generated using c# code) using openssl it shows "Verification Failure error in dgst" error. Whereas signature file generated using openssl gets verified successfully.
Command I'm using for verification is
openssl dgst -sha256 -verify content_public_key.pem -signature content.zip.sig content.zip
What could be the issue ?
Here is the C# code I'm using to sign the data
/// <summary>
/// Method to generate signature file
/// </summary>
private void GenerateSignatureFile(string sourceFile)
{
try
{
var bytesToSign = File.ReadAllBytes(sourceFile);
var sig = Sign(bytesToSign);
var fileContent = Encoding.GetEncoding(1252).GetString(sig);
using (var sw = File.CreateText(Path.Combine(_projectLocation, _sigFileName)))
{
sw.Write(fileContent);
}
}
catch (Exception ex)
{
LoggingService.Log(ex.Message);
var errorWhileCreatingSignatureFile = Resource.ResourceManager.GetString("ErrorWhileCreatingSignatureFile");
throw new Exception(errorWhileCreatingSignatureFile, ex);
}
}
public byte[] Sign(byte[] bytes)
{
var key = ReadPrivateKey();
/* Make the key */
var keyParameter = new RsaKeyParameters(key.IsPrivate, ((RsaPrivateCrtKeyParameters)key).Modulus, ((RsaPrivateCrtKeyParameters)key).Exponent);
/* Init alg */
ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");
/* Populate key */
sig.Init(true, key);
/* Calc the signature */
sig.BlockUpdate(bytes, 0, bytes.Length);
return sig.GenerateSignature();
}
private AsymmetricKeyParameter ReadPrivateKey()
{
AsymmetricCipherKeyPair keyPair;
using (var reader = new StringReader(_privateKey))
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return keyPair.Private;
}