iOS verify digital signature

我的未来我决定 提交于 2019-12-01 12:19:22

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

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

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;
    }
}

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;
}

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!