且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS验证数字签名

更新时间:2023-12-01 11:44:16

回答有点晚,但我有同样的问题。

Maybe this answer is a little late but I had the same problem.

事实证明,Java处理哈希为你,但iOS不。

It turns out that Java handles the hashing for you, but iOS does not.

因此,如果你有一个名为 plainText 的纯文本,你可以在Java上生成一个签名,这样做:

So if you have a plaintext called plainText you might generate a signature on it in Java doing this:

public static byte[] sign(PrivateKey key, byte[] plainText) {
    try {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(key);
        signature.update(plainText);
        return signature.sign();
    } catch (Exception e) {
        return null;
    }
}

但是要在iOS中验证它,使用如下的明文散列:

But then to verify it in iOS you need to manually take a hash of the plaintext like so:

+ (BOOL)verifySignature:(uint8_t*)signature signatureLen:(size_t)sLen
            withPlainText:(uint8_t*)plainText plainTextLen:(size_t)pLen
            andKey:(SecKeyRef)key {
    uint8_t hash[32];
    CC_SHA256(plainText, pLen, hash);
    OSStatus returnCode = SecKeyRawVerify(key,
                                          kSecPaddingPKCS1SHA256,
                                          hash,
                                          32,
                                          signature,
                                          sLen);
    return returnCode == 0;
}

在上述方法中,签名是由Java方法生成的字节。

In the above method, signature is the bytes generated by the Java method.

当然,你可能不想硬编码参数,如哈希函数使用(和哈希的长度) 。

Of course, you may not want to hardcode parameters such as the the hash function used (and length of hash).