Search in sources :

Example 1 with KeyName

use of org.apache.xml.security.keys.content.KeyName in project santuario-java by apache.

the class BaltimoreEncTest method findKey.

/**
 * Method findKey
 *
 * Given an encryptedData structure, return the key that will decrypt
 * it
 *
 * @param encryptedData EncryptedData to get key for
 */
private Key findKey(EncryptedData encryptedData) throws Exception {
    KeyInfo ki = encryptedData.getKeyInfo();
    Key key = null;
    Key kek = null;
    if (ki == null) {
        return null;
    }
    // First check for a known key name
    KeyName keyName = ki.itemKeyName(0);
    if (keyName != null) {
        return mapKeyName(keyName.getKeyName());
    }
    // Decrypt any encryptedKey structures
    EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
    if (encryptedKey == null) {
        return null;
    }
    KeyInfo kiek = encryptedKey.getKeyInfo();
    if (kiek == null) {
        return null;
    }
    KeyName kekKeyName = kiek.itemKeyName(0);
    if (kekKeyName != null) {
        kek = mapKeyName(kekKeyName.getKeyName());
    } else {
        X509Data certData = kiek.itemX509Data(0);
        XMLX509Certificate xcert = certData.itemCertificate(0);
        X509Certificate cert = xcert.getX509Certificate();
        if (cert != null && cert.getSerialNumber().toString().equals(rsaCertSerialNumber)) {
            kek = rsaKey;
        }
    }
    if (kek != null) {
        XMLCipher cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.UNWRAP_MODE, kek);
        key = cipher.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm());
    }
    return key;
}
Also used : KeyName(org.apache.xml.security.keys.content.KeyName) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) KeyInfo(org.apache.xml.security.keys.KeyInfo) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) XMLCipher(org.apache.xml.security.encryption.XMLCipher) X509Data(org.apache.xml.security.keys.content.X509Data) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate)

Example 2 with KeyName

use of org.apache.xml.security.keys.content.KeyName in project santuario-java by apache.

the class SignatureVerificationTest method testHMACSignatureVerificationWrongKey.

@Test
public void testHMACSignatureVerificationWrongKey() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    byte[] hmacKey = "secret".getBytes(StandardCharsets.US_ASCII);
    SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key);
    // Add KeyInfo
    KeyInfo keyInfo = sig.getKeyInfo();
    KeyName keyName = new KeyName(document, "SecretKey");
    keyInfo.add(keyName);
    // XMLUtils.outputDOM(document, System.out);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    byte[] badKey = "secret2".getBytes(StandardCharsets.US_ASCII);
    key = new SecretKeySpec(badKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    properties.setSignatureVerificationKey(key);
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
    try {
        StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
        fail("Failure expected on a bad key");
    } catch (XMLStreamException ex) {
        Assert.assertTrue(ex.getCause() instanceof XMLSecurityException);
        Assert.assertEquals("INVALID signature -- core validation failed.", ex.getCause().getMessage());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) KeyName(org.apache.xml.security.keys.content.KeyName) SecretKey(javax.crypto.SecretKey) XMLStreamException(javax.xml.stream.XMLStreamException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) KeyInfo(org.apache.xml.security.keys.KeyInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) XMLSignature(org.apache.xml.security.signature.XMLSignature) Test(org.junit.Test)

Example 3 with KeyName

use of org.apache.xml.security.keys.content.KeyName in project santuario-java by apache.

the class SignatureVerificationTest method testHMACSignatureVerification.

@Test
public void testHMACSignatureVerification() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    byte[] hmacKey = "secret".getBytes(StandardCharsets.US_ASCII);
    SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key);
    // Add KeyInfo
    KeyInfo keyInfo = sig.getKeyInfo();
    KeyName keyName = new KeyName(document, "SecretKey");
    keyInfo.add(keyName);
    // XMLUtils.outputDOM(document, System.out);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(key);
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
    document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
    // Check the SecurityEvents
    checkSecurityEvents(securityEventListener, "http://www.w3.org/2001/10/xml-exc-c14n#", "http://www.w3.org/2000/09/xmldsig#sha1", "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    checkSignedElementSecurityEvents(securityEventListener);
    checkSignatureToken(securityEventListener, null, key, SecurityTokenConstants.KeyIdentifier_KeyName);
    SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
    KeyNameTokenSecurityEvent keyNameSecurityToken = securityEventListener.getSecurityEvent(SecurityEventConstants.KeyNameToken);
    String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
    String x509TokenCorrelationID = keyNameSecurityToken.getCorrelationID();
    List<SecurityEvent> signatureSecurityEvents = new ArrayList<>();
    List<SecurityEvent> signedElementSecurityEvents = new ArrayList<>();
    List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
    for (int i = 0; i < securityEvents.size(); i++) {
        SecurityEvent securityEvent = securityEvents.get(i);
        if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
            signedElementSecurityEvents.add(securityEvent);
        } else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
            signatureSecurityEvents.add(securityEvent);
        }
    }
    Assert.assertEquals(4, signatureSecurityEvents.size());
    Assert.assertEquals(3, signedElementSecurityEvents.size());
    Assert.assertEquals(securityEventListener.getSecurityEvents().size(), signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) KeyInfo(org.apache.xml.security.keys.KeyInfo) SecretKeySpec(javax.crypto.spec.SecretKeySpec) XMLSignature(org.apache.xml.security.signature.XMLSignature) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyName(org.apache.xml.security.keys.content.KeyName) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 4 with KeyName

use of org.apache.xml.security.keys.content.KeyName in project santuario-java by apache.

the class BobKeyResolver method engineCanResolve.

/**
 * Method engineCanResolve
 *
 * @param element
 * @param BaseURI
 * @param storage
 */
public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {
    if (element == null) {
        return false;
    }
    LOG.debug("Can I resolve " + element.getTagName());
    boolean isKeyName = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
    try {
        if (isKeyName) {
            _kn = new KeyName(element, "");
            if (_kn.getKeyName().equals("bob")) {
                return true;
            }
        }
    } catch (Exception e) {
    // Do nothing
    }
    return false;
}
Also used : KeyName(org.apache.xml.security.keys.content.KeyName) KeyResolverException(org.apache.xml.security.keys.keyresolver.KeyResolverException)

Example 5 with KeyName

use of org.apache.xml.security.keys.content.KeyName in project santuario-java by apache.

the class KeyUtils method prinoutKeyInfo.

/**
 * Method prinoutKeyInfo
 *
 * @param ki
 * @param os
 * @throws XMLSecurityException
 */
public static void prinoutKeyInfo(KeyInfo ki, PrintStream os) throws XMLSecurityException {
    for (int i = 0; i < ki.lengthKeyName(); i++) {
        KeyName x = ki.itemKeyName(i);
        os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\"");
    }
    for (int i = 0; i < ki.lengthKeyValue(); i++) {
        KeyValue x = ki.itemKeyValue(i);
        PublicKey pk = x.getPublicKey();
        os.println("KeyValue Nr. " + i);
        os.println(pk);
    }
    for (int i = 0; i < ki.lengthMgmtData(); i++) {
        MgmtData x = ki.itemMgmtData(i);
        os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\"");
    }
    for (int i = 0; i < ki.lengthX509Data(); i++) {
        X509Data x = ki.itemX509Data(i);
        os.println("X509Data(" + i + ")=\"" + (x.containsCertificate() ? "Certificate " : "") + (x.containsIssuerSerial() ? "IssuerSerial " : "") + "\"");
    }
}
Also used : KeyName(org.apache.xml.security.keys.content.KeyName) KeyValue(org.apache.xml.security.keys.content.KeyValue) MgmtData(org.apache.xml.security.keys.content.MgmtData) PublicKey(java.security.PublicKey) X509Data(org.apache.xml.security.keys.content.X509Data)

Aggregations

KeyName (org.apache.xml.security.keys.content.KeyName)5 SecretKey (javax.crypto.SecretKey)3 KeyInfo (org.apache.xml.security.keys.KeyInfo)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 XMLStreamReader (javax.xml.stream.XMLStreamReader)2 DOMSource (javax.xml.transform.dom.DOMSource)2 StreamResult (javax.xml.transform.stream.StreamResult)2 X509Data (org.apache.xml.security.keys.content.X509Data)2 XMLSignature (org.apache.xml.security.signature.XMLSignature)2 Test (org.junit.Test)2 Document (org.w3c.dom.Document)2 Key (java.security.Key)1 PrivateKey (java.security.PrivateKey)1 PublicKey (java.security.PublicKey)1 X509Certificate (java.security.cert.X509Certificate)1