2

我已经编写了以下代码来在 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 代码,它似乎工作正常。

任何帮助,可能出了什么问题?

4

1 回答 1

1

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

于 2012-07-07T00:26:23.033 回答