简体   繁体   中英

Java Python Message Signature and Verification

My server is coded in Python and I am making a java client for this server.

I am Signing a message(data) using:

public static byte[] Sign(PrivateKey privateKey, byte[] data) throws Exception{
        System.out.println("Signing the key inside RSACrypto#Sign");
        Signature dsa = Signature.getInstance("SHA1withRSA");

        SecureRandom secureRandom =null;
        dsa.initSign(privateKey,secureRandom);
        dsa.update(data);
        return dsa.sign();
}

This returns a byteArray(named signed_data) , now I am encoding this signature using Base64.encodeBase64 and converting the byteArray(named my_byte_array) so formed into string using :

String str = new String(my_byte_array)

and sending this string to Server.

On server side, I receive this string , then Server verifies the signature using:

publicKey.verify(str(data), (long(base64.b64decode(my_byte_array)),))

using library http://gdata-python-client.googlecode.com/hg/pydocs/gdata.Crypto.PublicKey.RSA.html

when I try to print my_byte_array on both side they are same, and so is signed_data and base64.b64decode(my_byte_array)

but I am getting this error:

ValueError: invalid literal for long() with base 10: '\x8b\xa1\xbb\x19fO\xea\xe7\xa4B\xd4\xd2\xa1\xe3\xb9\xd0\x89n\xa2\xfe\xb5\xedsL\x02\xba\xad\x12!qjp\x0c%+Z\t\xa7\x12\x08\x90\xfaTk\xca\xd0\xae\xd8\xa9\xfa\xbb]>9\x1c\x80\xd0

As far as I can think, this error is arising because Java signs the message into byte and python expects it to be in Long.

Is there a way to solve this problem?

You have actually 2 problems.

The first one is that - according to the Java Cryptograpy Architecture API - the SHA1withRSA algorithm involves PKCS#1 v1.5 padding. At the Python side, you must use the same padding scheme to verify the signature; that can be achieved with PyCrypto's PKCS#1 v1.5 signature module ( Crypto.Signature.PKCS1_v1_5 ).

The second problem is the one you point out: the verify method of an RSA PyCrypto object oddly requires the signature to be encoded as an integer. However, by using the module I mentioned above, the problem will go away, since it accepts byte strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM