signature.verify不返回预期结果

时间:2013-10-31 13:13:16

标签: java c++ c

我正在尝试将一些C代码移植到JAVA代码中,一些安全API需要在C和JAVA中调用,每个参数看起来都是正确的,但我总是得到错误的结果。我真的很沮丧,任何人都可以帮助我吗?

C代码是:

    if (1 != RSA_verify(NID_sha1, md, sizeof(md), sig, sigLen, aikRsa)) {
    fprintf (stderr, "Error, bad RSA signature in quote\n");
    exit (2);
}

通过API从PEM文件中读取aikRsa:

if ((aikRsa = PEM_read_RSA_PUBKEY(key_file, NULL, NULL, NULL)) == NULL) {
    fprintf (stderr, "Unable to read RSA file %s\n", av[1]);
    exit (1);
}

RSA_verify的定义:

int RSA_verify(int type, const unsigned char *m, unsigned int m_len,
unsigned char *sigbuf, unsigned int siglen, RSA *rsa);

PEM_read_RSA_PUBKEY的定义:

RSA *PEM_read_RSA_PUBKEY(FILE *fp, RSA **x,
                                    pem_password_cb *cb, void *u);

等效的JAVA代码:

        Signature signature;
        signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(pubkey); 
        signature.update(md);
        if (!signature.verify(sig)) {
            log.error("signature is not correct\n");
        } else {
            log.info("signature is correct\n");
        }

我在这里将“sig”和“md”与上面C代码中的“sig”和“md”的值进行了比较,它们几乎相同,只是它的无符号字符表示C中的字节,但是在JAVA字节中是总是签名。

pubkey是通过跟随函数获得的,这是我从其他地方获得的示例代码。

public  PublicKey getPemPublicKey(String filename) throws Exception {
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();

    String temp = new String(keyBytes);
    String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");

    Base64 b64 = new Base64();
    byte [] decoded = b64.decode(publicKeyPEM);

    X509EncodedKeySpec spec =
          new X509EncodedKeySpec(decoded);
    //KeyFactory kf = KeyFactory.getInstance(algorithm);
    KeyFactory kf =  KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
    }

C代码总是返回true,JAVA总是返回false,这里有什么问题?感谢任何投入。

0 个答案:

没有答案