PyCrypto在.NET RSACryptoServiceProvider中签名消息和验证签名

时间:2012-04-13 12:29:21

标签: .net cryptography digital-signature pycrypto 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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

看两行:

  

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

     

返回rsa.VerifyData(hash_as_bytes,“SHA1”,sig_as_bytes)

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