@Test public void testValidatePublicKey () throws Exception { final AuthorizationRequest request = makeRequest (); final Document doc = this.builder.buildFromRequest ( request ); this.signer.sign ( this.kp, doc ); System.out.println ( "Key: " + this.kp.getPrivate () ); final RequestValidator validator1 = new RequestValidator ( KeySelector.singletonKeySelector ( this.kp.getPublic () ) ); final RequestValidator validator2 = new RequestValidator ( new KeyValueKeySelector () ); Assert.assertTrue ( "XML Core Validation (Public Key)", validator1.validate ( doc ).isValid () ); Assert.assertTrue ( "XML Core Validation (KeyValueKeySelector)", validator2.validate ( doc ).isValid () ); }
@Test public void newKeySelector_keyValue() throws Exception { // given String response = Strings .textFileToString("javares/openamResponse.xml"); Document document = XMLConverter.convertToDocument( replaceX509WithKeyValueData(response), true); NodeList nl = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); // when KeySelector keySelector = factory.newKeySelector(nl.item(0)); // then assertTrue(keySelector instanceof KeyValueKeySelector); }
@Test public void newKeySelector_firstFound() throws Exception { // given String response = Strings .textFileToString("javares/openamResponse.xml"); Document document = XMLConverter.convertToDocument( addKeyValueAfterX509Data(response), true); NodeList nl = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); // when KeySelector keySelector = factory.newKeySelector(nl.item(0)); // then assertTrue(keySelector instanceof X509KeySelector); }
public KeySelector newKeySelector(Node nodeSignature) throws DigitalSignatureValidationException { Node nodeKeyinfo = getKeyInfoNode(nodeSignature); if (nodeKeyinfo == null) { throw new DigitalSignatureValidationException( "No KeyInfo element found in SAML assertion"); } NodeList children = nodeKeyinfo.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (SamlXmlTags.NODE_KEY_VALUE.equals(node.getLocalName())) { return new KeyValueKeySelector(); } else if (SamlXmlTags.NODE_X509DATA.equals(node.getLocalName())) { return new X509KeySelector(keystore); } } throw new DigitalSignatureValidationException( "Only RSA/DSA KeyValue and are X509Data supported"); }
@Override public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context) throws KeySelectorException { for (final Object object : keyInfo.getContent()) { final XMLStructure info = (XMLStructure) object; if (info instanceof X509Data) { final X509Data x509Data = (X509Data) info; for (final Object certificado : x509Data.getContent()) { if (certificado instanceof X509Certificate) { final X509Certificate x509Certificate = (X509Certificate) certificado; if (this.algEquals(method.getAlgorithm(), x509Certificate.getPublicKey().getAlgorithm())) { return new KeySelectorResult() { @Override public Key getKey() { return x509Certificate.getPublicKey(); } }; } } } } } throw new KeySelectorException("N\u00e3o foi localizada a chave do certificado."); }
static KeyAccessor getKeyAccessor() { KeyAccessor accessor = new KeyAccessor() { @Override public KeySelector getKeySelector(Message message) throws Exception { return KeySelector.singletonKeySelector(getKeyFromKeystore()); } @Override public KeyInfo getKeyInfo(Message mess, Node messageBody, KeyInfoFactory keyInfoFactory) throws Exception { return null; } }; return accessor; }
@Override public KeySelectorResult select ( final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context ) throws KeySelectorException { if ( keyInfo == null ) { throw new KeySelectorException ( "Null KeyInfo object!" ); } final SignatureMethod sm = (SignatureMethod)method; final List<?> list = keyInfo.getContent (); for ( int i = 0; i < list.size (); i++ ) { final XMLStructure xmlStructure = (XMLStructure)list.get ( i ); if ( xmlStructure instanceof KeyValue ) { try { final PublicKey pk = ( (KeyValue)xmlStructure ).getPublicKey (); // make sure algorithm is compatible with method if ( algEquals ( sm.getAlgorithm (), pk.getAlgorithm () ) ) { return new SimpleKeySelectorResult ( pk ); } } catch ( final KeyException ke ) { throw new KeySelectorException ( ke ); } } } throw new KeySelectorException ( "No KeyValue element found!" ); }
@Override public KeySelectorResult select ( final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context ) throws KeySelectorException { if ( keyInfo == null ) { throw new KeySelectorException ( "Null KeyInfo object!" ); } final SignatureMethod sm = (SignatureMethod)method; final List<?> list = keyInfo.getContent (); for ( final Object l : list ) { final XMLStructure xmlStructure = (XMLStructure)l; if ( xmlStructure instanceof X509Data ) { for ( final Object o : ( (X509Data)xmlStructure ).getContent () ) { KeySelectorResult result = null; if ( o instanceof X509Certificate ) { result = findPublicKey ( (X509Certificate)o, sm ); } if ( result != null ) { return result; } } } } throw new KeySelectorException ( "No KeyValue element found!" ); }
@Override public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod algorithmMethod, XMLCryptoContext context) throws KeySelectorException { if (keyInfo == null) { throw new KeySelectorException("Null KeyInfo object!"); } @SuppressWarnings("unchecked") List<XMLStructure> list = keyInfo.getContent(); for (XMLStructure xmlStructure : list) { if (xmlStructure instanceof X509Data) { X509Data x509Data = (X509Data) xmlStructure; @SuppressWarnings("rawtypes") List content = x509Data.getContent(); for (int i = 0; i < content.size(); i++) { Object x509Content = content.get(i); if (x509Content instanceof X509Certificate) { X509Certificate certificate = (X509Certificate) x509Content; try { return getPublicKeyFromKeystore(certificate, (SignatureMethod) algorithmMethod); } catch (KeyStoreException e) { throw new KeySelectorException(e); } } } } } throw new KeySelectorException("No X509Data element found."); }
@Override public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod algorithmMethod, XMLCryptoContext context) throws KeySelectorException { if (keyInfo == null) { throw new KeySelectorException("Null KeyInfo object!"); } @SuppressWarnings("unchecked") List<XMLStructure> list = keyInfo.getContent(); for (XMLStructure xmlStructure : list) { if (xmlStructure instanceof KeyValue) { PublicKey publicKey = null; try { publicKey = ((KeyValue) xmlStructure).getPublicKey(); } catch (KeyException ke) { throw new KeySelectorException(ke); } if (algorithmCompatibleWithMethod( algorithmMethod.getAlgorithm(), publicKey.getAlgorithm())) { return new SimpleKeySelectorResult(publicKey); } } } throw new KeySelectorException("No RSA/DSA KeyValue element found"); }
/** * Creates a <code>DOMSignContext</code> with the specified key selector, * parent and next sibling nodes. The marshalled <code>XMLSignature</code> * will be inserted as a child element of the specified parent node and * immediately before the specified next sibling node. * * @param ks the key selector * @param parent the parent node * @param nextSibling the next sibling node * @throws NullPointerException if <code>ks</code>, <code>parent</code> or * <code>nextSibling</code> is <code>null</code> */ public DOMSignContext(KeySelector ks, Node parent, Node nextSibling) { if (ks == null) { throw new NullPointerException("key selector cannot be null"); } if (parent == null) { throw new NullPointerException("parent cannot be null"); } if (nextSibling == null) { throw new NullPointerException("nextSibling cannot be null"); } setKeySelector(ks); this.parent = parent; this.nextSibling = nextSibling; }
private void init(Node node, KeySelector ks) { if (node == null) { throw new NullPointerException("node is null"); } this.node = node; super.setKeySelector(ks); if (System.getSecurityManager() != null) { super.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); } }
static void test_create_signature_x509_ski() throws Exception { System.out.println("* Generating signature-x509-ski.xml"); KeyInfo ski = kifac.newKeyInfo(Collections.singletonList (kifac.newX509Data(Collections.singletonList ("keyid".getBytes("ASCII"))))); test_create_signature_external(dsaSha1, ski, signingKey, KeySelector.singletonKeySelector(validatingKey), false); System.out.println(); }
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE)); NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new RuntimeException("Couldn't find 'Signature' element"); } Element element = (Element) nl.item(0); byte[] keyBytes = Base64.getDecoder().decode(validationKey); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(spec); KeySelector ks = KeySelector.singletonKeySelector(key); DOMValidateContext vc = new DOMValidateContext(ks, element); // disable secure validation mode vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // set a dummy dereferencer to be able to get content by references vc.setURIDereferencer(dereferencer); XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); XMLSignature signature = factory.unmarshalXMLSignature(vc); // run validation signature.validate(vc); }
private void test_create_signature_enveloping( SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks ) throws Exception { // create reference Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null); // create SignedInfo SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref)); Document doc = db.newDocument(); // create Objects Element webElem = doc.createElementNS(null, "Web"); Text text = doc.createTextNode("up up and away"); webElem.appendChild(text); XMLObject obj = fac.newXMLObject(Collections.singletonList (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null); // create XMLSignature XMLSignature sig = fac.newXMLSignature (si, ki, Collections.singletonList(obj), null, null); DOMSignContext dsc = new DOMSignContext(signingKey, doc); dsc.setDefaultNamespacePrefix("dsig"); sig.sign(dsc); TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement()); // XMLUtils.outputDOM(doc.getDocumentElement(), System.out); DOMValidateContext dvc = new DOMValidateContext (ks, doc.getDocumentElement()); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); assertTrue(sig.equals(sig2)); assertTrue(sig2.validate(dvc)); }
@org.junit.Test public void test_signature_enveloping_hmac_sha1() throws Exception { String file = "signature-enveloping-hmac-sha1.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("secret".getBytes("ASCII") ); SignatureValidator validator = new SignatureValidator(dir); boolean coreValidity = validator.validate(file, ks); assertTrue("Signature failed core validation", coreValidity); }
@org.junit.Test public void test_signature_enveloping_hmac_sha1_40() throws Exception { String file = "signature-enveloping-hmac-sha1-40.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("secret".getBytes("ASCII") ); try { SignatureValidator validator = new SignatureValidator(dir); validator.validate(file, ks); fail("Expected HMACOutputLength exception"); } catch (XMLSignatureException xse) { System.out.println(xse.getMessage()); // pass } }
private void test_create_signature_enveloping( SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks ) throws Exception { // create reference Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null); // create SignedInfo SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref)); Document doc = db.newDocument(); // create Objects Element webElem = doc.createElementNS(null, "Web"); Text text = doc.createTextNode("up up and away"); webElem.appendChild(text); XMLObject obj = fac.newXMLObject(Collections.singletonList (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null); // create XMLSignature XMLSignature sig = fac.newXMLSignature (si, ki, Collections.singletonList(obj), null, null); DOMSignContext dsc = new DOMSignContext(signingKey, doc); dsc.setDefaultNamespacePrefix("dsig"); sig.sign(dsc); TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement()); DOMValidateContext dvc = new DOMValidateContext (ks, doc.getDocumentElement()); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); assertTrue(sig.equals(sig2)); assertTrue(sig2.validate(dvc)); }
private void test_xmldsig11(String test, KeySelector ks, String vendor) throws Exception { String file = vendor + File.separator + test + ".xml"; // System.out.println("Validating " + file); boolean coreValidity = validator.validate(file, ks); assertTrue(file + " failed core validation", coreValidity); }
@org.junit.Test public void test_create_signature_x509_ski() throws Exception { KeyInfo ski = kifac.newKeyInfo(Collections.singletonList (kifac.newX509Data(Collections.singletonList ("keyid".getBytes("ASCII"))))); test_create_signature_external(dsaSha1, ski, signingKey, KeySelector.singletonKeySelector(validatingKey), false); }
private void test_create_signature_enveloping (SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks, boolean b64) throws Exception { // create reference Reference ref; if (b64) { ref = fac.newReference("#object", sha1, Collections.singletonList (fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null); } else { ref = fac.newReference("#object", sha1); } // create SignedInfo SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref)); Document doc = db.newDocument(); // create Objects XMLObject obj = fac.newXMLObject(Collections.singletonList (new DOMStructure(doc.createTextNode("some text"))), "object", null, null); // create XMLSignature XMLSignature sig = fac.newXMLSignature (si, ki, Collections.singletonList(obj), null, null); DOMSignContext dsc = new DOMSignContext(signingKey, doc); sig.sign(dsc); TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement()); DOMValidateContext dvc = new DOMValidateContext (ks, doc.getDocumentElement()); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); assertTrue(sig.equals(sig2)); assertTrue(sig2.validate(dvc)); }
@org.junit.Test public void test_signature_hmac_sha1_40_c14n_comments_detached() throws Exception { String file = "signature-hmac-sha1-40-c14n-comments-detached.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("test".getBytes("ASCII") ); try { validator.validate(file, ks); fail("Expected HMACOutputLength Exception"); } catch (XMLSignatureException xse) { //System.out.println(xse.getMessage()); // pass } }
@org.junit.Test public void test_signature_hmac_sha1_40_exclusive_c14n_comments_detached() throws Exception { String file = "signature-hmac-sha1-40-exclusive-c14n-comments-detached.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("test".getBytes("ASCII") ); try { validator.validate(file, ks); fail("Expected HMACOutputLength Exception"); } catch (XMLSignatureException xse) { //System.out.println(xse.getMessage()); // pass } }
@org.junit.Test public void test_signature_hmac_sha1_exclusive_c14n_comments_detached() throws Exception { String file = "signature-hmac-sha1-exclusive-c14n-comments-detached.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("test".getBytes("ASCII") ); boolean coreValidity = validator.validate(file, ks, ud); assertTrue("Signature failed core validation", coreValidity); }
@org.junit.Test public void test_signature_hmac_sha1_exclusive_c14n_enveloped() throws Exception { String file = "signature-hmac-sha1-exclusive-c14n-enveloped.xml"; KeySelector ks = new KeySelectors.SecretKeySelector ("test".getBytes("ASCII") ); boolean coreValidity = validator.validate(file, ks); assertTrue("Signature failed core validation", coreValidity); }
@org.junit.Test public void testsetngetKeySelector() throws Exception { defContext.setKeySelector(null); assertNull(defContext.getKeySelector()); KeySelector ks = KeySelector.singletonKeySelector(KEYS[0]); defContext.setKeySelector(ks); assertEquals(defContext.getKeySelector(), ks); }