Search in sources :

Example 1 with UnsyncBufferedOutputStream

use of com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream in project jdk8u_jdk by JetBrains.

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.booleanValue()) {
        this.derefData = copyDerefData(dereferencedData);
        dos = new DigesterOutputStream(md, true);
    } else {
        dos = new DigesterOutputStream(md);
    }
    OutputStream os = null;
    Data data = dereferencedData;
    try {
        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("com.sun.org.apache.xml.internal.security.useC14N11");
                    c14n11 = (prop != null && prop.booleanValue());
                    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");
            }
            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);
                }
                t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context);
                allTransforms.add(t);
                xi.updateOutputStream(os, true);
            } else {
                xi.updateOutputStream(os);
            }
        }
        os.flush();
        if (cache != null && cache.booleanValue()) {
            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 (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) {
        throw new XMLSignatureException(e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                throw new XMLSignatureException(e);
            }
        }
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                throw new XMLSignatureException(e);
            }
        }
    }
}
Also used : DigesterOutputStream(org.jcp.xml.dsig.internal.DigesterOutputStream) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) Element(org.w3c.dom.Element) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) XMLSignatureInput(com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput) DigesterOutputStream(org.jcp.xml.dsig.internal.DigesterOutputStream)

Example 2 with UnsyncBufferedOutputStream

use of com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream in project jdk8u_jdk by JetBrains.

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();
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI());
            log.log(java.util.logging.Level.FINE, "jceSigAlgorithm    = " + sa.getJCEAlgorithmString());
            log.log(java.util.logging.Level.FINE, "jceSigProvider     = " + sa.getJCEProviderName());
            log.log(java.util.logging.Level.FINE, "PublicKey = " + pk);
        }
        byte[] sigBytes = null;
        try {
            sa.initVerify(pk);
            // Get the canonicalized (normalized) SignedInfo
            SignerOutputStream so = new SignerOutputStream(sa);
            OutputStream bos = new UnsyncBufferedOutputStream(so);
            si.signInOctetStream(bos);
            bos.close();
            // retrieve the byte[] from the stored signature
            sigBytes = this.getSignatureValue();
        } catch (IOException ex) {
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
            }
        // Impossible...
        } catch (XMLSecurityException ex) {
            throw ex;
        }
        // the bytes that were stored in the signature.
        if (!sa.verify(sigBytes)) {
            log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
            return false;
        }
        return si.verify(this.followManifestsDuringValidation);
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
Also used : SignerOutputStream(com.sun.org.apache.xml.internal.security.utils.SignerOutputStream) SignerOutputStream(com.sun.org.apache.xml.internal.security.utils.SignerOutputStream) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) OutputStream(java.io.OutputStream) SignatureAlgorithm(com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException)

Example 3 with UnsyncBufferedOutputStream

use of com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream in project jdk8u_jdk by JetBrains.

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 {
    OutputStream os = null;
    try {
        MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
        mda.reset();
        DigesterOutputStream diOs = new DigesterOutputStream(mda);
        os = new UnsyncBufferedOutputStream(diOs);
        XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
        // C14N11 transform if needed
        if (Reference.useC14N11 && !validating && !output.isOutputStreamSet() && !output.isOctetStream()) {
            if (transforms == null) {
                transforms = new Transforms(this.doc);
                transforms.setSecureValidation(secureValidation);
                this.constructionElement.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("empty", ex);
    } catch (IOException ex) {
        throw new ReferenceNotInitializedException("empty", ex);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException ex) {
                throw new ReferenceNotInitializedException("empty", ex);
            }
        }
    }
}
Also used : UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) OutputStream(java.io.OutputStream) DigesterOutputStream(com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream) Transforms(com.sun.org.apache.xml.internal.security.transforms.Transforms) MessageDigestAlgorithm(com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm) DigesterOutputStream(com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream) IOException(java.io.IOException) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException)

Example 4 with UnsyncBufferedOutputStream

use of com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream in project jdk8u_jdk by JetBrains.

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"));
    }
    try {
        //Create a SignatureAlgorithm object
        SignedInfo si = this.getSignedInfo();
        SignatureAlgorithm sa = si.getSignatureAlgorithm();
        OutputStream so = null;
        try {
            // initialize SignatureAlgorithm for signing
            sa.initSign(signingKey);
            // generate digest values for all References in this SignedInfo
            si.generateDigestValues();
            so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa));
            // get the canonicalized bytes from SignedInfo
            si.signInOctetStream(so);
        } catch (XMLSecurityException ex) {
            throw ex;
        } finally {
            if (so != null) {
                try {
                    so.close();
                } catch (IOException ex) {
                    if (log.isLoggable(java.util.logging.Level.FINE)) {
                        log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
                    }
                }
            }
        }
        // set them on the SignatureValue element
        this.setSignatureValueElement(sa.sign());
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException("empty", ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException("empty", ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
Also used : SignerOutputStream(com.sun.org.apache.xml.internal.security.utils.SignerOutputStream) PublicKey(java.security.PublicKey) CanonicalizationException(com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException) InvalidCanonicalizerException(com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException) SignerOutputStream(com.sun.org.apache.xml.internal.security.utils.SignerOutputStream) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) OutputStream(java.io.OutputStream) SignatureAlgorithm(com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException)

Example 5 with UnsyncBufferedOutputStream

use of com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream in project jdk8u_jdk by JetBrains.

the class DOMSignedInfo method canonicalize.

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

Aggregations

UnsyncBufferedOutputStream (com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream)5 IOException (java.io.IOException)4 OutputStream (java.io.OutputStream)4 XMLSecurityException (com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException)3 SignatureAlgorithm (com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm)2 SignerOutputStream (com.sun.org.apache.xml.internal.security.utils.SignerOutputStream)2 MessageDigestAlgorithm (com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm)1 CanonicalizationException (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException)1 InvalidCanonicalizerException (com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException)1 XMLSignatureInput (com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput)1 Transforms (com.sun.org.apache.xml.internal.security.transforms.Transforms)1 DigesterOutputStream (com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 PublicKey (java.security.PublicKey)1 DigesterOutputStream (org.jcp.xml.dsig.internal.DigesterOutputStream)1 Element (org.w3c.dom.Element)1