XMLSignatureHandler { static void addSignature(SignableXMLObject signable, PrivateKey key, X509Certificate cert, SigEntryType type, String sigDigestAlg) throws CertificateEncodingException { if (type == SigEntryType.NONE) { return; } if (sigDigestAlg == null) { throw new IllegalArgumentException("Signature Digest Algorithm must not be null."); } Signature sig = new SignatureBuilder().buildObject(); BasicX509Credential credential = new BasicX509Credential(cert); credential.setPrivateKey(key); sig.setSigningCredential(credential); String keyAlg = key.getAlgorithm(); if ("EC".equalsIgnoreCase(keyAlg) || "ECDSA".equalsIgnoreCase(keyAlg)) { checkForECSignatures(sigDigestAlg, sig); } else if ("RSA".equalsIgnoreCase(keyAlg)) { checkForRSASignatures(sigDigestAlg, sig); } else if ("DSA".equalsIgnoreCase(keyAlg)) { checkForDSASignatures(sigDigestAlg, sig); } else { throw new IllegalArgumentException("Unsupported key algorithm " + keyAlg + ", use RSA, DSA, ECDSA or EC"); } sig.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); KeyInfo keyInfo = new KeyInfoBuilder().buildObject(); X509Data x509Data = new X509DataBuilder().buildObject(); if (type == SigEntryType.CERTIFICATE) { addCertificate(cert, x509Data); } else if (type == SigEntryType.ISSUERSERIAL) { addIssuerSerial(cert, x509Data); } keyInfo.getX509Datas().add(x509Data); sig.setKeyInfo(keyInfo); signable.setSignature(sig); if ("SHA256".equals(sigDigestAlg) || "SHA256-PSS".equals(sigDigestAlg)) { ((SAMLObjectContentReference)sig.getContentReferences() .get(0)).setDigestAlgorithm(EncryptionConstants.ALGO_ID_DIGEST_SHA256); } } private  XMLSignatureHandler();  static final String GIVEN_DIGEST_ALGORITHM; }
@Test void testWhenAddSignatureCalledWithUnknownDigestAlgoThenThrowIllegalArgumentException() throws Exception { X509Certificate cert = Utils.readCert(XMLSignatureHandlerTest.class.getResourceAsStream("/EidasSignerTest_x509.cer")); PrivateKey pk = Utils.readPKCS12(XMLSignatureHandlerTest.class.getResourceAsStream(TEST_P12_RSA), "123456".toCharArray()) .getKey(); Assertions.assertThrows(IllegalArgumentException.class, () -> XMLSignatureHandler.addSignature(signableXMLObject, pk, cert, XMLSignatureHandler.SigEntryType.CERTIFICATE, "SHB-256")); }
@Test void testWhenDigestAlgoNullThenThrowIllegalArgumentException() throws Exception { X509Certificate cert = Utils.readCert(XMLSignatureHandlerTest.class.getResourceAsStream("/EidasSignerTest_x509.cer")); PrivateKey pk = Utils.readPKCS12(XMLSignatureHandlerTest.class.getResourceAsStream(TEST_P12_RSA), "123456".toCharArray()) .getKey(); Assertions.assertNull(signableXMLObject.getSignature()); Assertions.assertThrows(IllegalArgumentException.class, () -> XMLSignatureHandler.addSignature(signableXMLObject, pk, cert, XMLSignatureHandler.SigEntryType.CERTIFICATE, null)); }