[英]Verify a detached pgp signature in c#
这就是我所拥有的:
我需要从代码中执行的操作:检查 update.zip 是否经过调整。 因此检查签名,确认文件 update.zip.sha256sum 是可以的,所以我可以使用其中的 sha256 与我计算的比较。 都很基本。 问题是:verify 方法总是返回 false。 从桌面应用程序执行此操作是可行的,因此文件肯定没问题。
我做了什么:当然我在这里阅读了所有类似的问题,特别是这个。 我还阅读了所有充气城堡文档。 那是快速和容易的 - 没有。
最后,我使用了其中一个示例,即..\crypto\test\src\openpgp\examples\DetachedSignatureProcessor.cs 下的一个
所以这是(失败的)代码:
private static bool VerifySignature(string fileName, Stream inputStream, Stream keyIn)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);
PgpSignatureList p3 = null;
PgpObject o = pgpFact.NextPgpObject();
p3 = (PgpSignatureList)o;
PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
PgpUtilities.GetDecoderStream(keyIn));
Stream dIn = GetStream(fileName);
PgpSignature sig = p3[0];
PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);
sig.InitVerify(key);
int ch;
while ((ch = dIn.ReadByte()) >= 0)
{
sig.Update((byte)ch);
}
dIn.Close();
if (sig.Verify())
{
Console.WriteLine("signature verified.");
return true;
}
else
{
Console.WriteLine("signature verification failed.");
return false;
}
}
public static Stream GetStream(string stringData)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(stringData);
writer.Flush();
stream.Position = 0;
return stream;
}
代码运行愉快,但总是选择“签名验证失败”。 路线。
我不确定是我错过了一些步骤还是我使用了错误的成分。 我使用的3个是纯文本sha256sum文件(fileName),签名文件sha256sum.asc(inputStream)和公钥(keyIN)。
最后我解决了。 但不要问哪个步骤有所作为;-)
public static bool VerifySignature(string fileName, Stream inputStream, Stream keyIn)
{
PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(keyIn);
PgpPublicKey pubicKey = pgpPubRingCollection.GetPublicKey(4100000000000000000); //once I knew the right one, I put it here directly as it won't change anyway
Stream signaturStrom = PgpUtilities.GetDecoderStream(inputStream);
PgpObjectFactory pgpWTFactory = new PgpObjectFactory(signaturStrom);
PgpSignature signtr = ((PgpSignatureList)pgpWTFactory.NextPgpObject())[0];
signtr.InitVerify(pubicKey);
try
{
Stream dIn = ReadStream(fileName); // get stream from ext. file
int ch;
while ((ch = dIn.ReadByte()) >= 0)
{
signtr.Update((byte)ch);
}
dIn.Close();
}
catch (Exception ex)
{
return false;
}
if (signtr.Verify())
{
Console.WriteLine("signature verified.");
return true;
}
else
{
Console.WriteLine("signature verification failed.");
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.