3

我正在尝试创建一个签名验证系统,该系统使用我的网站,该网站在带有 PyCrypto 引擎的 Google API 上运行。生成签名的程序非常简单:

from Crypto.PublicKey import RSA
from Crypto.Hash import MD5
def sign(key, message):
   digest = MD5.new(message).digest()
   signature = key.sign( digest, None )[0]
   signature = hex(signature).replace("0x","").replace("L","").upper()
   if len(signature) % 2==1:
      signature = "0" + sig 
   return signature

密钥“密钥”由以下方式提供:

RSA.construct((m, e, d, p, q))

签名以十六进制字符串形式返回,例如:“A12D.......”

.NET 程序是:

    Private Function Verify(ByVal message As String, ByVal sign As String) As Boolean
    Dim md5 As New MD5CryptoServiceProvider
    Dim f As New StreamReader("D:/KEY.XML")
    Dim xml As String = f.ReadToEnd
    f.Close()

    Dim rsa As New RSACryptoServiceProvider
    rsa.FromXmlString(xml)

    Dim msg_as_bytes As Byte() = Encoding.Default.GetBytes(message)
    Dim hash_as_bytes As Byte() = md5.ComputeHash(msg_as_bytes)

    ''Dim sig_as_bytes As Byte() = convtobytes(sign)

    Dim sig_as_bytes As Byte() = New Byte(sign.Length / 2 - 1) {}
    For i As Integer = 1 To sign.Length / 2
        sig_as_bytes(i - 1) = CByte("&H" & Mid(sign, (i - 1) * 2 + 1, 2))
    Next

    Return rsa.VerifyData(hash_as_bytes, "SHA1", sig_as_bytes)
End Function

但它不起作用!为什么??

Pycrypto 和 .NET 接收相同的参数(模数、指数、d、p、q)

4

2 回答 2

4

我完成了!

解决方案是使用 Crypto.Signature.PKCS1_v1_5

from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Util import number
from Crypto.Signature import PKCS1_v1_5

m = 123....
e = 1111....
d = 123....
p = 365...
q = 657...

key = RSA.construct((m, e, d, p, q))

message = "message to be signed"

def assina(message):
    h = SHA.new(message)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    return ByteToHex(signature)

和 .NET 代码进行验证:

Private Function Verify(ByVal message As String, ByVal sign As String) As Boolean
    Dim rsa As New RSACryptoServiceProvider()
    rsa.FromXmlString(_pubKey)

    Dim msg_as_bytes As Byte() = Encoding.Default.GetBytes(message)

    Dim sig_as_bytes As Byte() = New Byte(CInt(sign.Length / 2) - 1) {}

    For i As Integer = 1 To sign.Length / 2
        sig_as_bytes(i - 1) = CByte("&H" & Mid(sign, (i - 1) * 2 + 1, 2))
    Next

    Return rsa.VerifyData(msg_as_bytes, "SHA", sig_as_bytes)
End Function
于 2012-06-23T13:22:37.080 回答
1

看看这两行:

摘要 = MD5.new(消息).digest()

返回 rsa.VerifyData(hash_as_bytes, "SHA1", sig_as_bytes)

即使您MD5CryptoServiceProvider在 .NET 代码中使用 a ,您仍然SHA1会要求使用验证,但这是行不通的。尝试将其更改为MD5.

于 2012-04-13T12:32:41.170 回答