PyCrypto 对消息进行签名并在 .NET RSACryptoServiceProvider 中验证签名



我正在尝试创建一个签名验证系统,该系统使用我的网站,该系统在带有PyCrypto Engine的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)

我完成了!

解决方案是使用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

看看这两行:

摘要 = MD5.new(message).digest()

返回 rsa。验证数据(hash_as_bytes, "SHA1", sig_as_bytes)

即使您在 .NET 代码中使用MD5CryptoServiceProvider,您仍然要求验证使用SHA1并且这不起作用。尝试将其更改为 MD5

相关内容

  • 没有找到相关文章

最新更新