3

我正在开发一项功能,需要我在 PHP 中对短字符串进行数字签名,并在 C# 中验证字符串的签名。

我真的很想在 PHP 中使用openssl_sign,因为它很简单,但我在 Google 上找到的所有信息都表明这不起作用。

一些外部库声称做得很好,但是由于这是一个爱好项目,我宁愿不购买这样的库。

那么这里有什么替代方案呢?需要 C# 和 PHP 之间的完全互操作性。可以使用 OpenSSL 以外的库。

4

5 回答 5

2

我使用Bouncy Castle Crypto APIs做了一些非常相似的事情。看来 PHP openssl_sign 默认使用 SHA1。如果您使用的不是默认值,则需要更改 GetSigner 的算法参数。

string base64pubkey = "<!-- BASE64 representation of your pubkey from open ssl -->";
RsaKeyParameters pubKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(base64pubkey)) as RsaKeyParameters;
byte[] signature = Convert.FromBase64String("<!-- BASE64 representation of your sig -->");
byte[] message = Encoding.ASCII.GetBytes("Something that has been signed");


ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
sig.Init(false, pubKey);
sig.BlockUpdate(message, 0, message.Length);
if (sig.VerifySignature(signature))
{
    Console.WriteLine("all good!");
}
于 2009-09-01T02:26:55.690 回答
1

您可以像这样检查数字签名:

string publicKey = "some key";
// Verifying Step 1: Create the digital signature algorithm object
DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();

// Verifying Step 2: Import the signature and public key.
verifier.FromXmlString(publicKey);

// Verifying Step 3: Store the data to be verified in a byte array
FileStream file = new FileStream(args[0], FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(file2);
byte[] data = reader.ReadBytes((int)file2.Length);

// Verifying Step 4: Call the VerifyData method
if (verifier.VerifyData(data, signature))
    Console.WriteLine("Signature verified");
else
    Console.WriteLine("Signature NOT verified");
reader.Close();
file.Close();
于 2009-05-13T07:34:50.060 回答
0

您是否有理由需要像 SSL 签名这样复杂的东西?你不能只在字符串上使用像 MD5/SHA-1 这样的简单单向哈希吗?如果您正在寻找的只是验证字符串没有被篡改,那就足够了。

于 2009-05-13T06:08:34.553 回答
0

所以看看这个- 这个家伙似乎在 PHP 和 C# 之间进行了非对称签名和加密工作。签名应该不是问题,SHA* 和 MD* 是标准的,因此不太可能不兼容(尽管您应该查看 SHA256,因为 MD* 和 SHA1 由于漏洞而被弃用)

于 2009-05-13T06:13:27.057 回答
0

我们缺少一些关于您为什么需要签名的上下文。你可能不需要。

重要的问题是:您需要从数据中获得哪些保证?

如果您需要做的只是验证数据的完整性,那么哈希就可以完成这项工作。如果您需要验证它的来源,则需要对其进行签名。如果两者都需要,请对其进行哈希处理,将有效负载与哈希连接起来,然后对整个内容进行签名。

关于跨平台库......你真的应该担心它。一个 SHA1 是一个 SHA1 是一个 SHA1,不管是哪个库生成的。生成和验证数字签名也是如此。使用 PHP 中最简单的东西并使用 C# 中最简单的东西。如果它们都设置正确,则无需担心。

于 2009-05-13T06:36:21.653 回答