Search in sources :

Example 1 with CanonicalizationMethod

use of javax.xml.crypto.dsig.CanonicalizationMethod in project cas by apereo.

the class AbstractSamlObjectBuilder method signSamlElement.

/**
 * Sign SAML element.
 *
 * @param element the element
 * @param privKey the priv key
 * @param pubKey  the pub key
 * @return the element
 */
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
    try {
        final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
        final Class<?> clazz = Class.forName(providerName);
        final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
        final List<Transform> envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
        // Create the SignatureMethod based on the type of key
        final SignatureMethod signatureMethod;
        final String algorithm = pubKey.getAlgorithm();
        switch(algorithm) {
            case "DSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
                break;
            case "RSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
                break;
            default:
                throw new IllegalArgumentException("Error signing SAML element: Unsupported type of key");
        }
        final CanonicalizationMethod canonicalizationMethod = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
        // Create the SignedInfo
        final SignedInfo signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));
        // Create a KeyValue containing the DSA or RSA PublicKey
        final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
        final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
        // Create a KeyInfo and add the KeyValue to it
        final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
        // Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
        final Element w3cElement = toDom(element);
        // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
        final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
        dsc.setNextSibling(xmlSigInsertionPoint);
        // Marshal, generate (and sign) the enveloped signature
        final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
        signature.sign(dsc);
        return toJdom(w3cElement);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Transform(javax.xml.crypto.dsig.Transform)

Example 2 with CanonicalizationMethod

use of javax.xml.crypto.dsig.CanonicalizationMethod in project santuario-java by apache.

the class ClassLoaderTest method testProviderMultipleLoaders.

@SuppressWarnings("resource")
@org.junit.Test
public void testProviderMultipleLoaders() throws Exception {
    String baseDir = System.getProperty("basedir");
    String fs = System.getProperty("file.separator");
    File file0 = new File(baseDir + fs + "build" + fs + "classes" + fs);
    File file1 = new File(baseDir + fs + "build" + fs + "test" + fs);
    URL[] urls = new URL[2];
    urls[0] = file0.toURI().toURL();
    urls[1] = file1.toURI().toURL();
    URLClassLoader uc1 = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
    // load security provider using current class loader
    final Provider provider = new XMLDSigRI();
    AccessController.doPrivileged((java.security.PrivilegedAction<Object>) () -> Security.addProvider(provider));
    // get the provider from java.security.Security using URLClassLoader.
    // Need to use introspection to invoke methods to avoid using the
    // current class loader
    String factoryName = "javax.xml.crypto.dsig.XMLSignatureFactory";
    Class<?> factoryClass = uc1.loadClass(factoryName);
    Method factoryMethod = factoryClass.getDeclaredMethod("getInstance", new Class[] { String.class });
    Class<?> methodParameterClass = uc1.loadClass("javax.xml.crypto.dsig.spec.C14NMethodParameterSpec");
    Method canonicalizationMethod = factoryClass.getDeclaredMethod("newCanonicalizationMethod", new Class[] { String.class, methodParameterClass });
    Object factory = factoryMethod.invoke(null, "DOM");
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        canonicalizationMethod.invoke(factory, new Object[] { CanonicalizationMethod.EXCLUSIVE, null });
    }
    long end = System.currentTimeMillis();
    long elapsed = end - start;
    LOG.debug("Elapsed: {}", elapsed);
}
Also used : CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Method(java.lang.reflect.Method) URL(java.net.URL) Provider(java.security.Provider) URLClassLoader(java.net.URLClassLoader) File(java.io.File) XMLDSigRI(org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI)

Example 3 with CanonicalizationMethod

use of javax.xml.crypto.dsig.CanonicalizationMethod in project OpenOLAT by OpenOLAT.

the class XMLDigitalSignatureUtil method signEmbedded.

/**
 * Produce a signed a XML file. The signature is added in the XML file.
 *
 * @param xmlFile The original XML file
 * @param xmlSignedFile The signed XML file
 * @param x509Cert
 * @param privateKey
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws NoSuchAlgorithmException
 * @throws GeneralSecurityException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws TransformerException
 */
public static void signEmbedded(File xmlFile, File xmlSignedFile, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
    Document doc = getDocument(xmlFile);
    // Create the signature factory for creating the signature.
    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> transforms = new ArrayList<Transform>();
    Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    transforms.add(envelopped);
    // Create the canonicalization transform to be applied after the XSLT.
    CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    transforms.add(c14n);
    // Create the Reference to the XML to be signed specifying the hash algorithm to be used
    // and the list of transforms to apply. Also specify the XML to be signed as the current
    // document (specified by the first parameter being an empty string).
    Reference reference = sigFactory.newReference("", sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
    // Create the Signed Info node of the signature by specifying the canonicalization method
    // to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
    SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
    // Create the KeyInfo node containing the public key information to include in the signature.
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    // Get the node to attach the signature.
    Node signatureInfoNode = doc.getDocumentElement();
    // Create a signing context using the private key.
    DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
    // Create the signature from the signing context and key info
    XMLSignature signature = sigFactory.newXMLSignature(si, ki);
    signature.sign(dsc);
    write(doc, xmlSignedFile);
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) Transform(javax.xml.crypto.dsig.Transform)

Example 4 with CanonicalizationMethod

use of javax.xml.crypto.dsig.CanonicalizationMethod in project openolat by klemens.

the class XMLDigitalSignatureUtil method signDetached.

/**
 * Create a separate XML file with the XML Digital Signature.
 *
 * of the specified XML file.
 * @param xmlFile The XML File to sign
 * @param outputSignatureFile Where the Digital Signature is saved
 * @param signatureDoc A DOM which hold the signature (optional but if you give one, the root element must exists)
 * @throws ParserConfigurationException
 * @throws GeneralSecurityException
 * @throws NoSuchAlgorithmException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @throws TransformerException
 */
public static void signDetached(String uri, File xmlFile, File outputSignatureFile, Document signatureDoc, String keyName, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
    Document doc = getDocument(xmlFile);
    // Create the signature factory for creating the signature.
    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> transforms = new ArrayList<Transform>();
    // Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    // transforms.add(envelopped);
    // Create the canonicalization transform to be applied after the XSLT.
    CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    transforms.add(c14n);
    // Create the Reference to the XML to be signed specifying the hash algorithm to be used
    // and the list of transforms to apply. Also specify the XML to be signed as the current
    // document (specified by the first parameter being an empty string).
    Reference reference = sigFactory.newReference(uri, sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
    // Create the Signed Info node of the signature by specifying the canonicalization method
    // to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
    SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
    // Create the KeyInfo node containing the public key information to include in the signature.
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
    List<Object> keyInfoList = new ArrayList<>();
    if (StringHelper.containsNonWhitespace(keyName)) {
        keyInfoList.add(kif.newKeyName(keyName));
    }
    keyInfoList.add(xd);
    KeyInfo ki = kif.newKeyInfo(keyInfoList);
    // Get the node to attach the signature.
    Node signatureInfoNode = doc.getDocumentElement();
    // Create a signing context using the private key.
    DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
    dsc.setBaseURI(uri);
    dsc.setURIDereferencer(new FileURIDereferencer(uri, xmlFile));
    // Create the signature from the signing context and key info
    XMLSignature signature = sigFactory.newXMLSignature(si, ki);
    signature.sign(dsc);
    NodeList nl = doc.getElementsByTagName("Signature");
    if (nl.getLength() == 1) {
        if (signatureDoc != null && signatureDoc.getDocumentElement() != null) {
            Element rootEl = signatureDoc.getDocumentElement();
            rootEl.appendChild(signatureDoc.importNode(nl.item(0), true));
            write(rootEl, outputSignatureFile);
        } else {
            write(nl.item(0), outputSignatureFile);
        }
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) Transform(javax.xml.crypto.dsig.Transform)

Example 5 with CanonicalizationMethod

use of javax.xml.crypto.dsig.CanonicalizationMethod in project openolat by klemens.

the class XMLDigitalSignatureUtil method signEmbedded.

/**
 * Produce a signed a XML file. The signature is added in the XML file.
 *
 * @param xmlFile The original XML file
 * @param xmlSignedFile The signed XML file
 * @param x509Cert
 * @param privateKey
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws NoSuchAlgorithmException
 * @throws GeneralSecurityException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws TransformerException
 */
public static void signEmbedded(File xmlFile, File xmlSignedFile, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
    Document doc = getDocument(xmlFile);
    // Create the signature factory for creating the signature.
    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> transforms = new ArrayList<Transform>();
    Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    transforms.add(envelopped);
    // Create the canonicalization transform to be applied after the XSLT.
    CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    transforms.add(c14n);
    // Create the Reference to the XML to be signed specifying the hash algorithm to be used
    // and the list of transforms to apply. Also specify the XML to be signed as the current
    // document (specified by the first parameter being an empty string).
    Reference reference = sigFactory.newReference("", sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
    // Create the Signed Info node of the signature by specifying the canonicalization method
    // to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
    SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
    // Create the KeyInfo node containing the public key information to include in the signature.
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    // Get the node to attach the signature.
    Node signatureInfoNode = doc.getDocumentElement();
    // Create a signing context using the private key.
    DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
    // Create the signature from the signing context and key info
    XMLSignature signature = sigFactory.newXMLSignature(si, ki);
    signature.sign(dsc);
    write(doc, xmlSignedFile);
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) Transform(javax.xml.crypto.dsig.Transform)

Aggregations

CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)9 SignedInfo (javax.xml.crypto.dsig.SignedInfo)8 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)8 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)8 ArrayList (java.util.ArrayList)7 Reference (javax.xml.crypto.dsig.Reference)7 XMLSignature (javax.xml.crypto.dsig.XMLSignature)7 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)7 Transform (javax.xml.crypto.dsig.Transform)6 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)6 Document (org.w3c.dom.Document)5 Element (org.w3c.dom.Element)5 URIReference (javax.xml.crypto.URIReference)4 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)4 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)4 Node (org.w3c.dom.Node)4 XMLSignContext (javax.xml.crypto.dsig.XMLSignContext)3 NodeList (org.w3c.dom.NodeList)3 File (java.io.File)2 XMLStructure (javax.xml.crypto.XMLStructure)2