Search in sources :

Example 1 with KeyInfoFactory

use of javax.xml.crypto.dsig.keyinfo.KeyInfoFactory in project jdk8u_jdk by JetBrains.

the class Marshal method main.

public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo(Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);
    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception("Should be KeyName element: " + knElem.getLocalName());
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) Element(org.w3c.dom.Element) DOMStructure(javax.xml.crypto.dom.DOMStructure) Document(org.w3c.dom.Document) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)

Example 2 with KeyInfoFactory

use of javax.xml.crypto.dsig.keyinfo.KeyInfoFactory in project poi by apache.

the class SignatureConfig method getKeyInfoFactory.

/**
     * @return the key factory (thread-local)
     */
public KeyInfoFactory getKeyInfoFactory() {
    KeyInfoFactory keyFac = keyInfoFactory.get();
    if (keyFac == null) {
        keyFac = KeyInfoFactory.getInstance("DOM", getProvider());
        setKeyInfoFactory(keyFac);
    }
    return keyFac;
}
Also used : KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)

Example 3 with KeyInfoFactory

use of javax.xml.crypto.dsig.keyinfo.KeyInfoFactory in project poi by apache.

the class KeyInfoSignatureFacet method postSign.

@Override
public void postSign(Document document) throws MarshalException {
    LOG.log(POILogger.DEBUG, "postSign");
    NodeList nl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "Object");
    /*
         * Make sure we insert right after the ds:SignatureValue element, just
         * before the first ds:Object element.
         */
    Node nextSibling = (nl.getLength() == 0) ? null : nl.item(0);
    /*
         * Construct the ds:KeyInfo element using JSR 105.
         */
    KeyInfoFactory keyInfoFactory = signatureConfig.getKeyInfoFactory();
    List<Object> x509DataObjects = new ArrayList<Object>();
    X509Certificate signingCertificate = signatureConfig.getSigningCertificateChain().get(0);
    List<XMLStructure> keyInfoContent = new ArrayList<XMLStructure>();
    if (signatureConfig.isIncludeKeyValue()) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }
    if (signatureConfig.isIncludeIssuerSerial()) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }
    if (signatureConfig.isIncludeEntireCertificateChain()) {
        x509DataObjects.addAll(signatureConfig.getSigningCertificateChain());
    } else {
        x509DataObjects.add(signingCertificate);
    }
    if (!x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;
    Key key = new Key() {

        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };
    Element n = document.getDocumentElement();
    DOMSignContext domSignContext = (nextSibling == null) ? new DOMSignContext(key, n) : new DOMSignContext(key, n, nextSibling);
    for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
        domSignContext.putNamespacePrefix(me.getKey(), me.getValue());
    }
    DOMStructure domStructure = new DOMStructure(n);
    domKeyInfo.marshal(domStructure, domSignContext);
    // move keyinfo into the right place
    if (nextSibling != null) {
        NodeList kiNl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "KeyInfo");
        if (kiNl.getLength() != 1) {
            throw new RuntimeException("KeyInfo wasn't set");
        }
        nextSibling.getParentNode().insertBefore(kiNl.item(0), nextSibling);
    }
}
Also used : KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) X509Certificate(java.security.cert.X509Certificate) KeyException(java.security.KeyException) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMKeyInfo(org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMKeyInfo(org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo) DOMStructure(javax.xml.crypto.dom.DOMStructure) Map(java.util.Map) Key(java.security.Key)

Example 4 with KeyInfoFactory

use of javax.xml.crypto.dsig.keyinfo.KeyInfoFactory 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 5 with KeyInfoFactory

use of javax.xml.crypto.dsig.keyinfo.KeyInfoFactory in project cxf by apache.

the class MetadataWriter method signMetaInfo.

private static Document signMetaInfo(X509Certificate signingCert, Key signingKey, Document doc, String referenceID) throws Exception {
    String signatureMethod = null;
    if ("SHA1withDSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.DSA_SHA1;
    } else if ("SHA1withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else if ("SHA256withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else {
        LOG.error("Unsupported signature method: " + signingCert.getSigAlgName());
        throw new RuntimeException("Unsupported signature method: " + signingCert.getSigAlgName());
    }
    List<Transform> transformList = new ArrayList<>();
    transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null));
    // Create a Reference to the enveloped document (in this case,
    // you are signing the whole document, so a URI of "" signifies
    // that, and also specify the SHA1 digest algorithm and
    // the ENVELOPED Transform.
    Reference ref = XML_SIGNATURE_FACTORY.newReference("#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
    // Create the SignedInfo.
    SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), XML_SIGNATURE_FACTORY.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));
    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<>();
    x509Content.add(signingCert.getSubjectX500Principal().getName());
    x509Content.add(signingCert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    // DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
    dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
    dsc.setNextSibling(doc.getDocumentElement().getFirstChild());
    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);
    // Marshal, generate, and sign the enveloped signature.
    signature.sign(dsc);
    // Output the resulting document.
    return doc;
}
Also used : Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) 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) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) Transform(javax.xml.crypto.dsig.Transform) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Aggregations

KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)12 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)9 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)9 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)9 ArrayList (java.util.ArrayList)8 SignedInfo (javax.xml.crypto.dsig.SignedInfo)8 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)7 Reference (javax.xml.crypto.dsig.Reference)7 Transform (javax.xml.crypto.dsig.Transform)7 XMLSignature (javax.xml.crypto.dsig.XMLSignature)7 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)7 Element (org.w3c.dom.Element)7 Document (org.w3c.dom.Document)6 Node (org.w3c.dom.Node)5 URIReference (javax.xml.crypto.URIReference)4 DOMStructure (javax.xml.crypto.dom.DOMStructure)4 NodeList (org.w3c.dom.NodeList)4 X509Certificate (java.security.cert.X509Certificate)3 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)3 KeyValue (javax.xml.crypto.dsig.keyinfo.KeyValue)3