Search in sources :

Example 1 with UnsyncBufferedOutputStream

use of org.apache.xml.security.utils.UnsyncBufferedOutputStream in project santuario-java by apache.

the class XMLSignature method sign.

/**
 * Digests all References in the SignedInfo, calculates the signature value
 * and sets it in the SignatureValue Element.
 *
 * @param signingKey the {@link java.security.PrivateKey} or
 * {@link javax.crypto.SecretKey} that is used to sign.
 * @throws XMLSignatureException
 */
public void sign(Key signingKey) throws XMLSignatureException {
    if (signingKey instanceof PublicKey) {
        throw new IllegalArgumentException(I18n.translate("algorithms.operationOnlyVerification"));
    }
    // Create a SignatureAlgorithm object
    SignedInfo si = this.getSignedInfo();
    SignatureAlgorithm sa = si.getSignatureAlgorithm();
    try (SignerOutputStream output = new SignerOutputStream(sa);
        OutputStream so = new UnsyncBufferedOutputStream(output)) {
        // generate digest values for all References in this SignedInfo
        si.generateDigestValues();
        // initialize SignatureAlgorithm for signing
        sa.initSign(signingKey);
        // get the canonicalized bytes from SignedInfo
        si.signInOctetStream(so);
        // set them on the SignatureValue element
        this.setSignatureValueElement(sa.sign());
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException(ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    } catch (IOException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) PublicKey(java.security.PublicKey) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 2 with UnsyncBufferedOutputStream

use of org.apache.xml.security.utils.UnsyncBufferedOutputStream in project santuario-java by apache.

the class Reference method calculateDigest.

/**
 * Method calculateDigest
 *
 * @param validating true if validating the reference
 * @return reference Calculate the digest of this reference.
 * @throws ReferenceNotInitializedException
 * @throws XMLSignatureException
 */
private byte[] calculateDigest(boolean validating) throws ReferenceNotInitializedException, XMLSignatureException {
    XMLSignatureInput input = this.getContentsBeforeTransformation();
    if (input.isPreCalculatedDigest()) {
        return getPreCalculatedDigest(input);
    }
    cacheDereferencedElement(input);
    MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
    mda.reset();
    try (DigesterOutputStream diOs = new DigesterOutputStream(mda);
        OutputStream os = new UnsyncBufferedOutputStream(diOs)) {
        XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
        this.transformsOutput = output;
        // C14N11 transform if needed
        if (Reference.useC14N11 && !validating && !output.isOutputStreamSet() && !output.isOctetStream()) {
            if (transforms == null) {
                transforms = new Transforms(getDocument());
                transforms.setSecureValidation(secureValidation);
                getElement().insertBefore(transforms.getElement(), digestMethodElem);
            }
            transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
            output.updateOutputStream(os, true);
        } else {
            output.updateOutputStream(os);
        }
        os.flush();
        if (output.getOctetStreamReal() != null) {
            output.getOctetStreamReal().close();
        }
        return diOs.getDigestValue();
    } catch (XMLSecurityException ex) {
        throw new ReferenceNotInitializedException(ex);
    } catch (IOException ex) {
        throw new ReferenceNotInitializedException(ex);
    }
}
Also used : DigesterOutputStream(org.apache.xml.security.utils.DigesterOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) Transforms(org.apache.xml.security.transforms.Transforms) MessageDigestAlgorithm(org.apache.xml.security.algorithms.MessageDigestAlgorithm) DigesterOutputStream(org.apache.xml.security.utils.DigesterOutputStream) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 3 with UnsyncBufferedOutputStream

use of org.apache.xml.security.utils.UnsyncBufferedOutputStream in project santuario-java by apache.

the class XMLSignature method checkSignatureValue.

/**
 * Verifies if the signature is valid by redigesting all References,
 * comparing those against the stored DigestValues and then checking to see
 * if the Signatures match on the SignedInfo.
 *
 * @param pk {@link java.security.PublicKey} part of the keypair or
 * {@link javax.crypto.SecretKey} that was used to sign
 * @return true if the signature is valid, false otherwise
 * @throws XMLSignatureException
 */
public boolean checkSignatureValue(Key pk) throws XMLSignatureException {
    // check to see if the key is not null
    if (pk == null) {
        Object[] exArgs = { "Didn't get a key" };
        throw new XMLSignatureException("empty", exArgs);
    }
    // References inside a Manifest.
    try {
        SignedInfo si = this.getSignedInfo();
        // create a SignatureAlgorithms from the SignatureMethod inside
        // SignedInfo. This is used to validate the signature.
        SignatureAlgorithm sa = si.getSignatureAlgorithm();
        LOG.debug("signatureMethodURI = {}", sa.getAlgorithmURI());
        LOG.debug("jceSigAlgorithm = {}", sa.getJCEAlgorithmString());
        LOG.debug("jceSigProvider = {}", sa.getJCEProviderName());
        LOG.debug("PublicKey = {}", pk);
        byte[] sigBytes = null;
        try (SignerOutputStream so = new SignerOutputStream(sa);
            OutputStream bos = new UnsyncBufferedOutputStream(so)) {
            sa.initVerify(pk);
            // Get the canonicalized (normalized) SignedInfo
            si.signInOctetStream(bos);
            // retrieve the byte[] from the stored signature
            sigBytes = this.getSignatureValue();
        } catch (IOException ex) {
            LOG.debug(ex.getMessage(), ex);
        // Impossible...
        } catch (XMLSecurityException ex) {
            throw ex;
        }
        // the bytes that were stored in the signature.
        if (!sa.verify(sigBytes)) {
            LOG.warn("Signature verification failed.");
            return false;
        }
        return si.verify(this.followManifestsDuringValidation);
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 4 with UnsyncBufferedOutputStream

use of org.apache.xml.security.utils.UnsyncBufferedOutputStream in project santuario-java by apache.

the class DOMReference method transform.

private byte[] transform(Data dereferencedData, XMLCryptoContext context) throws XMLSignatureException {
    if (md == null) {
        try {
            md = MessageDigest.getInstance(((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    md.reset();
    DigesterOutputStream dos;
    Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference");
    if (cache != null && cache) {
        this.derefData = copyDerefData(dereferencedData);
        dos = new DigesterOutputStream(md, true);
    } else {
        dos = new DigesterOutputStream(md);
    }
    Data data = dereferencedData;
    try (OutputStream os = new UnsyncBufferedOutputStream(dos)) {
        for (int i = 0, size = transforms.size(); i < size; i++) {
            DOMTransform transform = (DOMTransform) transforms.get(i);
            if (i < size - 1) {
                data = transform.transform(data, context);
            } else {
                data = transform.transform(data, context, os);
            }
        }
        if (data != null) {
            XMLSignatureInput xi;
            // explicitly use C14N 1.1 when generating signature
            // first check system property, then context property
            boolean c14n11 = useC14N11;
            String c14nalg = CanonicalizationMethod.INCLUSIVE;
            if (context instanceof XMLSignContext) {
                if (!c14n11) {
                    Boolean prop = (Boolean) context.getProperty("org.apache.xml.security.useC14N11");
                    c14n11 = prop != null && prop;
                    if (c14n11) {
                        c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
                    }
                } else {
                    c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
                }
            }
            if (data instanceof ApacheData) {
                xi = ((ApacheData) data).getXMLSignatureInput();
            } else if (data instanceof OctetStreamData) {
                xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
            } else if (data instanceof NodeSetData) {
                TransformService spi = null;
                if (provider == null) {
                    spi = TransformService.getInstance(c14nalg, "DOM");
                } else {
                    try {
                        spi = TransformService.getInstance(c14nalg, "DOM", provider);
                    } catch (NoSuchAlgorithmException nsae) {
                        spi = TransformService.getInstance(c14nalg, "DOM");
                    }
                }
                data = spi.transform(data, context);
                xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
            } else {
                throw new XMLSignatureException("unrecognized Data type");
            }
            boolean secVal = Utils.secureValidation(context);
            xi.setSecureValidation(secVal);
            if (context instanceof XMLSignContext && c14n11 && !xi.isOctetStream() && !xi.isOutputStreamSet()) {
                TransformService spi = null;
                if (provider == null) {
                    spi = TransformService.getInstance(c14nalg, "DOM");
                } else {
                    try {
                        spi = TransformService.getInstance(c14nalg, "DOM", provider);
                    } catch (NoSuchAlgorithmException nsae) {
                        spi = TransformService.getInstance(c14nalg, "DOM");
                    }
                }
                DOMTransform t = new DOMTransform(spi);
                Element transformsElem = null;
                String dsPrefix = DOMUtils.getSignaturePrefix(context);
                if (allTransforms.isEmpty()) {
                    transformsElem = DOMUtils.createElement(refElem.getOwnerDocument(), "Transforms", XMLSignature.XMLNS, dsPrefix);
                    refElem.insertBefore(transformsElem, DOMUtils.getFirstChildElement(refElem));
                } else {
                    transformsElem = DOMUtils.getFirstChildElement(refElem);
                }
                XmlWriter xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), transformsElem);
                t.marshal(xwriter, dsPrefix, context);
                allTransforms.add(t);
                xi.updateOutputStream(os, true);
            } else {
                xi.updateOutputStream(os);
            }
        }
        os.flush();
        if (cache != null && cache) {
            this.dis = dos.getInputStream();
        }
        return dos.getDigestValue();
    } catch (NoSuchAlgorithmException e) {
        throw new XMLSignatureException(e);
    } catch (TransformException e) {
        throw new XMLSignatureException(e);
    } catch (MarshalException e) {
        throw new XMLSignatureException(e);
    } catch (IOException e) {
        throw new XMLSignatureException(e);
    } catch (org.apache.xml.security.c14n.CanonicalizationException e) {
        throw new XMLSignatureException(e);
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                throw new XMLSignatureException(e);
            }
        }
    }
}
Also used : DigesterOutputStream(org.apache.jcp.xml.dsig.internal.DigesterOutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) Element(org.w3c.dom.Element) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) DigesterOutputStream(org.apache.jcp.xml.dsig.internal.DigesterOutputStream)

Example 5 with UnsyncBufferedOutputStream

use of org.apache.xml.security.utils.UnsyncBufferedOutputStream in project santuario-java by apache.

the class DOMSignedInfo method canonicalize.

public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos) throws XMLSignatureException {
    if (context == null) {
        throw new NullPointerException("context cannot be null");
    }
    DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true);
    try (OutputStream os = new UnsyncBufferedOutputStream(bos)) {
        ((DOMCanonicalizationMethod) canonicalizationMethod).canonicalize(subTree, context, os);
        os.flush();
        byte[] signedInfoBytes = bos.toByteArray();
        // this whole block should only be done if LOGging is enabled
        if (LOG.isDebugEnabled()) {
            LOG.debug("Canonicalized SignedInfo:");
            StringBuilder sb = new StringBuilder(signedInfoBytes.length);
            for (int i = 0; i < signedInfoBytes.length; i++) {
                sb.append((char) signedInfoBytes[i]);
            }
            LOG.debug(sb.toString());
            LOG.debug("Data to be signed/verified:" + Base64.getMimeEncoder().encodeToString(signedInfoBytes));
        }
        this.canonData = new ByteArrayInputStream(signedInfoBytes);
    } catch (TransformException te) {
        throw new XMLSignatureException(te);
    } catch (IOException e) {
        LOG.debug(e.getMessage(), e);
    // Impossible
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream)

Aggregations

UnsyncBufferedOutputStream (org.apache.xml.security.utils.UnsyncBufferedOutputStream)6 IOException (java.io.IOException)4 OutputStream (java.io.OutputStream)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)4 SignatureAlgorithm (org.apache.xml.security.algorithms.SignatureAlgorithm)2 SignerOutputStream (org.apache.xml.security.utils.SignerOutputStream)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 PublicKey (java.security.PublicKey)1 DigesterOutputStream (org.apache.jcp.xml.dsig.internal.DigesterOutputStream)1 MessageDigestAlgorithm (org.apache.xml.security.algorithms.MessageDigestAlgorithm)1 CanonicalizationException (org.apache.xml.security.c14n.CanonicalizationException)1 InvalidCanonicalizerException (org.apache.xml.security.c14n.InvalidCanonicalizerException)1 XMLSignatureInput (org.apache.xml.security.signature.XMLSignatureInput)1 Canonicalizer20010315_OmitCommentsTransformer (org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_OmitCommentsTransformer)1 DigestOutputStream (org.apache.xml.security.stax.impl.util.DigestOutputStream)1 Transforms (org.apache.xml.security.transforms.Transforms)1 DigesterOutputStream (org.apache.xml.security.utils.DigesterOutputStream)1 Element (org.w3c.dom.Element)1