1

In my REST API I am getting multipart files with a request. I get a JSON file, and p7s file, which is a signature of that JSON file. I have the public certificate which was used to sign it.

I need to verify JSON file with jsonSig file.

Code I have written by now is:

public void getFiles(@RequestParam("json") MultipartFile json,
                                        @RequestParam("json-sig") MultipartFile jsonSig) throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, InvalidKeyException, SignatureException {

    String certificate = CERTIFIFATE;
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    byte[] base64Bytes = Base64.getDecoder().decode(certificate);
    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(base64Bytes));

    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initVerify(x509Certificate.getPublicKey());
    signature.update(json.getBytes());
    InputStream bytessss = jsonSig.getInputStream();
    boolean isCorrect = signature.verify(jsonSig.getBytes());

I get an error in the last line:

java.security.SignatureException: Signature length not correct: got 6793 but was expecting 256] with root cause

I probably need to extract just a certificate from jsonSig, but I have no clue how to do that.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • A PKCS7/CMS signature -- and CAdES is basically just CMS with added constraints -- is per Doug Adams almost completely unlike the raw cryptographic signature your code would handle. If you can use bouncycastle see https://stackoverflow.com/questions/17043569/pkcs7-verify-digital-signature-in-java?rq=1 (already suggested as Related) plus link there. – dave_thompson_085 Oct 26 '22 at 23:36
  • Thank you very much, it helped me to go into good direction but luckily that requirement was removed from my project and I couldn't test it and make it work. – Adam Jedrzejko Oct 27 '22 at 15:13

0 Answers0