It doesn't make sense to try to verify all the certificates in the chain against a single public key. Most of them won't have been signed by it, so the procedure is bound to fail, and throw an exception to the caller.
You need to review what it is you're supposed to do in this method. See the Javadoc. You're trying to establish a certificate path from this chain to a trusted root certificate.
In this case the trusted root certificate is presumably the one you loaded from the file.
What you should be doing therefore is:
- Look for that certificate in the chain, and if not found
- Verify the last certificate in the chain against this public key, as that is the topmost signer, and that's the only one you need to trust. The rest of them are trusted by their respective sucessors in the chain, and none of their successors are this trusted root certificate, by (1).
- If the certificate is found in the chain, verify the previous certificate. i.e. the one signed by this certificate, with this public key.
It isn't clear to me whether you need to also verify each certificate in the chain, except the last, with the next one's public key, but it can't hurt.
EDIT You should also implement the suggestion in this answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…