在Android中签名数据并在python中验证它

时间:2012-07-07 00:02:23

标签: java android python digital-signature

我已经编写了以下代码来在android中签名数据:

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.RSAPublicKeySpec;

import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

        try{
        String m ="This is my message";
        System.out.println(m);

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair kp = keyPairGen.generateKeyPair();
        PrivateKey priKey = kp.getPrivate();
        PublicKey pubKey = kp.getPublic();


        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(pubKey, RSAPublicKeySpec.class);

        System.out.println("WITH toString: ");
        System.out.println("Mod :" + publicKeySpec.getModulus().toString());
        System.out.println("Exp :" + publicKeySpec.getPublicExponent().toString());
        System.out.println("PublicKey:" + pubKey.toString());




        System.out.println("PublicKey:" + pubKey);
        System.out.println("PublicKey Base64:" +MyBase64.encode(pubKey.getEncoded()));

        Signature instance = Signature.getInstance("SHA1withRSA");
        instance.initSign(priKey);
        instance.update(m.getBytes());
        byte[] signature = instance.sign();
        System.out.println("Signature: " + MyBase64.encode(signature));
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

我将adb logcat中的值粘贴到python中,我在python中验证它:

mod=#I paste mod here
exp=#I paste exp here
signature=#I paste signature here

message="This is my message"

publicKey = RSA.construct((mod,exp))
print 'PublicKey Base64: ' + publicKey.exportKey()
print str(publicKey)
test = SHA.new(message)
verifier = PKCS1_v1_5.new(publicKey)
signature_base = base64.b64decode(signature)
print "Verification: " + str(verifier.verify(test, signature_base))

我发现MyBase64.encode(pubKey.getEncoded())(在java中)与publicKey.exportKey()(在python中)相同

但是,验证总是会导致错误。

如果我使用javac运行它,java代码似乎工作正常。

任何帮助,可能出现的问题?

1 个答案:

答案 0 :(得分:1)

通常这样的错误与额外的空格潜入数据字符串有关。在计算哈希值之前尝试剥离它。