javax.xml.crypto.KeySelector Java Examples

The following examples show how to use javax.xml.crypto.KeySelector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XML.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * Check the xmldsig signature of the XML document.
 * @param document the document to test
 * @param publicKey the public key corresponding to the key pair the document was signed with
 * @return true if a correct signature is present, false otherwise
 */
public static boolean validSignature(Document document, Key publicKey) {
    Node signatureNode =  document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0);
    KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);

    try {
        String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
        DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureNode);

        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        return signature.validate(valContext);
    } catch (Exception e) {
        Logger.warn("Error validating an XML signature.", e);
        return false;
    }
}
 
Example #2
Source File: SignatureVerifier.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, 
		AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
	if (keyInfo == null)
		throw new KeySelectorException("Null KeyInfo");
	List<?> list = keyInfo.getContent();
	PublicKey pk = null;

	for (int i = 0; i < list.size(); i++) {
		XMLStructure xmlStructure = (XMLStructure) list.get(i);
		if (xmlStructure instanceof KeyValue) {
			try {
				pk = ((KeyValue)xmlStructure).getPublicKey();
			} catch(KeyException ke) {
				throw new KeySelectorException(ke.getMessage());
			}
			break;
		} else if (xmlStructure instanceof X509Data) {
			X509Data x509data = (X509Data)xmlStructure;
			List<?> x509datalist = x509data.getContent();
			for (int j = 0; j < x509datalist.size(); j++) {
				if (x509datalist.get(j) instanceof X509Certificate) {
					X509Certificate cert = (X509Certificate)x509datalist.get(j);
					pk = cert.getPublicKey();
					break;
				}
			}
		}
	}
	if (pk != null) {
		final PublicKey retpk = pk;
		logger.debug("PublicKey from XML=" + pk);
		return new KeySelectorResult() {public Key getKey(){return retpk;}};
	}
	throw new KeySelectorException("Missing KeyValue");
}
 
Example #3
Source File: SignatureRequestBuilderTest.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@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 () );
}
 
Example #4
Source File: DOMSignContext.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: KeyValueKeySelector.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@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!" );
}
 
Example #6
Source File: DOMSignContext.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: GenerationTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example #8
Source File: ErrorHandlerPermissions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #9
Source File: DOMSignContext.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: DOMValidateContext.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: X509KeySelector.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@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!" );
}
 
Example #12
Source File: DOMSignContext.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: GenerationTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example #14
Source File: DOMSignContext.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: DOMValidateContext.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #16
Source File: DOMSignContext.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: DOMSignContext.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: GenerationTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example #19
Source File: GenerationTests.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example #20
Source File: DOMValidateContext.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #21
Source File: DOMSignContext.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #22
Source File: DOMValidateContext.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #23
Source File: DOMValidateContext.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #24
Source File: DOMCryptoContext.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void setKeySelector(KeySelector ks) {
    this.ks = ks;
}
 
Example #25
Source File: DOMCryptoContext.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public KeySelector getKeySelector() {
    return ks;
}
 
Example #26
Source File: GenerationTests.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void test_create_signature_enveloping
        (DigestMethod dm, SignatureMethod sm, KeyInfo ki, Key signingKey,
         KeySelector ks, boolean b64) throws Exception {

        // create reference
        Reference ref;
        if (b64) {
            ref = fac.newReference("#object", dm, Collections.singletonList
                (fac.newTransform(Transform.BASE64,
                 (TransformParameterSpec) null)), null, null);
        } else {
            ref = fac.newReference("#object", dm);
        }

        // create SignedInfo
        SignedInfo si = fac.newSignedInfo(withoutComments, sm,
            Collections.singletonList(ref));

        Document doc = db.newDocument();
        // create Objects
        String text = b64 ? "c29tZSB0ZXh0" : "some text";
        XMLObject obj = fac.newXMLObject(Collections.singletonList
            (new DOMStructure(doc.createTextNode(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);

//        dumpDocument(doc, new FileWriter("/tmp/foo.xml"));

        DOMValidateContext dvc = new DOMValidateContext
            (ks, doc.getDocumentElement());
        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

        if (sig.equals(sig2) == false) {
            throw new Exception
                ("Unmarshalled signature is not equal to generated signature");
        }
        if (sig2.validate(dvc) == false) {
            throw new Exception("Validation of generated signature failed");
        }
    }
 
Example #27
Source File: DOMCryptoContext.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public KeySelector getKeySelector() {
    return ks;
}
 
Example #28
Source File: DOMCryptoContext.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void setKeySelector(KeySelector ks) {
    this.ks = ks;
}
 
Example #29
Source File: DOMCryptoContext.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public void setKeySelector(KeySelector ks) {
    this.ks = ks;
}
 
Example #30
Source File: ValidationTests.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
Test(String file, KeySelector ks) {
    this.file = file;
    this.ks = ks;
}