Java 类javax.xml.crypto.MarshalException 实例源码

项目:eSaskaita    文件:AbstractSignatureHelper.java   
@Test
public void signRequest() throws JAXBException, ParserConfigurationException, CertificateException, KeyException, MarshalException, NoSuchAlgorithmException, SOAPException, XPathExpressionException, XMLSignatureException, InvalidAlgorithmParameterException, java.security.cert.CertificateException, NoSuchProviderException, KeyStoreException, IOException, UnrecoverableKeyException {
    Serializable payload = createRequest();

    SOAPMessage signedRequest = sign(
            marshall(
                    payload,
                    getMarshaller(payload.getClass())
            ),
            getClient()
    );

    System.out.println("============ SIGNED SOAP MESSAGE ================");
    signedRequest.writeTo(System.out);
    System.out.println("\n=================================================");
}
项目:OpenJSharp    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:Java_CTe    文件:Assinatura.java   
/**
 * Assinatura do XML de Envio de Lote da CT-e utilizando Certificado
 * Digital.
 *
 * @param Conteudo do Xml
 * @param Nome     do Certificado Digital
 * @return String do XMl Assinado
 * @throws Exception
 */
private static String assinaDoc(String xml, String tipo) throws CteException {


    try {
        Document document = documentFactory(xml);
        XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
        ArrayList<Transform> transformList = signatureFactory(signatureFactory);
        loadCertificates(signatureFactory);

        if (tipo.equals(EVENTO)) {
            assinar(tipo, signatureFactory, transformList, privateKey, keyInfo, document, 0);

        } else {
            for (int i = 0; i < document.getDocumentElement().getElementsByTagName(tipo).getLength(); i++) {
                assinar(tipo, signatureFactory, transformList, privateKey, keyInfo, document, i);
            }
        }

        return outputXML(document);
    } catch (SAXException | IOException | ParserConfigurationException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException | UnrecoverableEntryException | NoSuchProviderException | CertificateException | MarshalException | XMLSignatureException | CertificadoException e) {
        throw new CteException("Erro ao Assinar Cte" + e.getMessage());
    }


}
项目:jdk8u-jdk    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:openjdk-jdk10    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:openjdk9    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:xmlsec-gost    文件:Marshaller.java   
/**
 * Marshals a {@link PGPData}
 *
 * @param xwriter
 * @param pgpData
 * @param dsPrefix
 * @param context
 * @throws MarshalException
 */
public static void marshalPGPData(XmlWriter xwriter, PGPData pgpData, String dsPrefix, XMLCryptoContext context)
throws MarshalException {
    xwriter.writeStartElement(dsPrefix, "PGPData", XMLSignature.XMLNS);

    // create and append PGPKeyID element
    byte[] keyId = pgpData.getKeyId();
    if (keyId != null) {
        xwriter.writeTextElement(dsPrefix, "PGPKeyID", XMLSignature.XMLNS, Base64.encode(keyId));
    }

    // create and append PGPKeyPacket element
    byte[] keyPacket = pgpData.getKeyPacket();
    if (keyPacket != null) {
        xwriter.writeTextElement(dsPrefix, "XMLSignature.XMLNS", XMLSignature.XMLNS, Base64.encode(keyPacket));
    }

    // create and append any elements
    @SuppressWarnings("unchecked")
    List<XMLStructure> externalElements = pgpData.getExternalElements();
    for (XMLStructure externalItem : externalElements) {
        xwriter.marshalStructure(externalItem, dsPrefix, context);
    }

    xwriter.writeEndElement(); // "PGPData"
}
项目:xmlsec-gost    文件:DOMRetrievalMethod.java   
@Override
public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
    throws MarshalException
{
    xwriter.writeStartElement(dsPrefix, "RetrievalMethod", XMLSignature.XMLNS);

    // TODO - see whether it is important to capture the "here" attribute as part of the
    // marshalling - do any of the tests fail?
    // add URI and Type attributes
    here = xwriter.writeAttribute("", "", "URI", uri);
    xwriter.writeAttribute("", "", "Type", type);

    // add Transforms elements
    if (!transforms.isEmpty()) {
        xwriter.writeStartElement(dsPrefix, "Transforms", XMLSignature.XMLNS);
        for (Transform transform : transforms) {
            ((DOMTransform)transform).marshal(xwriter, dsPrefix, context);
        }
        xwriter.writeEndElement(); // "Transforms"
    }
    xwriter.writeEndElement(); // "RetrievalMethod"
}
项目:xmlsec-gost    文件:DOMKeyInfo.java   
private static void marshalInternal(XmlWriter xwriter, KeyInfo ki,
    String dsPrefix, XMLCryptoContext context, boolean declareNamespace) throws MarshalException {

    xwriter.writeStartElement(dsPrefix, "KeyInfo", XMLSignature.XMLNS);
    if (declareNamespace) {
        xwriter.writeNamespace(dsPrefix, XMLSignature.XMLNS);
    }

    xwriter.writeIdAttribute("", "", "Id", ki.getId());
    // create and append KeyInfoType elements
    List<XMLStructure> keyInfoTypes = getContent(ki);
    for (XMLStructure kiType : keyInfoTypes) {
        xwriter.marshalStructure(kiType, dsPrefix, context);
    }

    xwriter.writeEndElement(); // "KeyInfo"
}
项目:xmlsec-gost    文件:JSRForbiddenRefCountTest.java   
@org.junit.Test
public void testReferenceCount() throws Exception {
    Element signedInfoElement =
        getSignedInfoElement("src/test/resources/interop/c14n/Y4", "signature-manifest.xml");

    InternalDOMCryptoContext context = new InternalDOMCryptoContext();
    new DOMSignedInfo(signedInfoElement, context, null);

    context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    try {
        new DOMSignedInfo(signedInfoElement, context, null);
    } catch (MarshalException ex) {
        String error =
            "A maxiumum of 30 references per Manifest are allowed with secure validation";
        assertTrue(ex.getMessage().contains(error));
    }
}
项目:Java_NFe    文件:Assinar.java   
/**
 * Assinatura do XML de Envio de Lote da NF-e utilizando Certificado
 * Digital.
 * 
 * @param Conteudo do Xml
 * @param Nome do Certificado Digital
 * @return String do XMl Assinado
 * @throws Exception
 */
private static String assinaDocNFe(String xml, String tipo) throws NfeException{

    Document document = null;

    try {
        document = documentFactory(xml);
        XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
        ArrayList<Transform> transformList = signatureFactory(signatureFactory);
        loadCertificates(signatureFactory);

        for (int i = 0; i < document.getDocumentElement().getElementsByTagName(tipo).getLength(); i++) {
            assinarNFe(tipo, signatureFactory, transformList, privateKey, keyInfo, document, i);
        }

    } catch (SAXException | IOException | ParserConfigurationException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException | UnrecoverableEntryException | NoSuchProviderException | CertificateException | CertificadoException | MarshalException | XMLSignatureException e) {
        throw new NfeException("Erro ao Assinar Nfe"+e.getMessage());
    }

    return outputXML(document);

}
项目:jdk8u_jdk    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:lookaside_java-1.8.0-openjdk    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:eid-applet    文件:RelationshipTransformService.java   
@Override
public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException {
    LOG.debug("marshallParams(parent,context)");
    DOMStructure domParent = (DOMStructure) parent;
    Node parentNode = domParent.getNode();
    Element parentElement = (Element) parentNode;
    parentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi",
            "http://schemas.openxmlformats.org/package/2006/digital-signature");
    Document document = parentNode.getOwnerDocument();
    for (String sourceId : this.sourceIds) {
        Element relationshipReferenceElement = document.createElementNS(
                "http://schemas.openxmlformats.org/package/2006/digital-signature", "mdssi:RelationshipReference");
        relationshipReferenceElement.setAttribute("SourceId", sourceId);
        parentElement.appendChild(relationshipReferenceElement);
    }
    for (String sourceType : this.sourceTypes) {
        Element relationshipsGroupReferenceElement = document.createElementNS(
                "http://schemas.openxmlformats.org/package/2006/digital-signature",
                "mdssi:RelationshipsGroupReference");
        relationshipsGroupReferenceElement.setAttribute("SourceType", sourceType);
        parentElement.appendChild(relationshipsGroupReferenceElement);
    }
}
项目:eid-applet    文件:AbstractODFSignatureServiceTest.java   
/**
 * Verification via the default JSR105 implementation triggers some
 * canonicalization errors.
 * 
 * @param odfUrl
 * @param signatureNode
 * @throws MarshalException
 * @throws XMLSignatureException
 */
private boolean verifySignature(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException {

    // work-around for Java 7
    Element signedPropertiesElement = (Element) ((Element) signatureNode)
            .getElementsByTagNameNS(XAdESXLSignatureFacet.XADES_NAMESPACE, "SignedProperties").item(0);
    if (null != signedPropertiesElement) {
        signedPropertiesElement.setIdAttribute("Id", true);
    }

    DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode);
    ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl);
    domValidateContext.setURIDereferencer(dereferencer);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    LOG.debug("java version: " + System.getProperty("java.version"));
    /*
     * Requires Java 6u10 because of a bug. See also:
     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582
     */
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = xmlSignature.validate(domValidateContext);
    return validity;
}
项目:oiosaml.java    文件:TokenClientTest.java   
public Envelope buildFault(String request) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    Envelope r = buildResponse(request, false);
    r.getBody().getUnknownXMLObjects().clear();

    Fault fault = SAMLUtil.buildXMLObject(Fault.class);
    Detail detail = SAMLUtil.buildXMLObject(Detail.class);

    FaultString msg = SAMLUtil.buildXMLObject(FaultString.class);
    msg.setValue("test");
    fault.setMessage(msg);

    fault.setDetail(detail);

    XSAny d = new XSAnyBuilder().buildObject("urn:test", "fault", "fa");
    detail.getUnknownXMLObjects().add(d);

    r.getBody().getUnknownXMLObjects().add(fault);

    return r;
}
项目:infobip-open-jdk-8    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:jdk8u-dev-jdk    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:OLD-OpenJDK8    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
项目:jetfuel    文件:XmlSignatureHandler.java   
public synchronized void sign()
        throws MarshalException,
        XMLSignatureException,
        KeyException {

    if (this.document == null)
        throw new RuntimeException("Can't sign a NULL document");

    Reference reference = this.signatureFactory.newReference(
            referenceUri,
            this.digestMethod,
            this.transformList,
            null,
            null);

    SignedInfo signedInfo = this.signatureFactory.newSignedInfo(
            this.canonicalizationMethod,
            this.signatureMethod,
            Collections.singletonList(reference));

    // Create the KeyInfo containing the X509Data.
    X509Data xd = this.keyInfoFactory.newX509Data(
            Collections.singletonList(this.certificateWithKey.certificate));

    KeyInfo keyInfo = this.keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    XMLSignature signature = this.signatureFactory.newXMLSignature(
            signedInfo,
            keyInfo);

    DOMSignContext signingContext = new DOMSignContext(
            this.certificateWithKey.privateKey,
            document.getDocumentElement());

    signature.sign(signingContext);
}
项目:jetfuel    文件:XmlSignatureHandler.java   
public synchronized boolean validate()
        throws MarshalException,
        XMLSignatureException {

    // Find Signature element.
    NodeList list = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (list.getLength() == 0) {
        throw new RuntimeException("Cannot find Signature element");
    }

    // Create a DOMValidateContext and specify a KeySelector
    // and document context.
    DOMValidateContext validateContext = new DOMValidateContext(new X509CertificateKeySelector(), list.item(0));

    // Unmarshal the XMLSignature.
    XMLSignature signature = this.signatureFactory.unmarshalXMLSignature(validateContext);

    // Validate the XMLSignature.
    if (signature.validate(validateContext)) {
        return true;
    } else {
        Iterator<?> i = signature.getSignedInfo().getReferences().iterator();
        for (int j = 0; i.hasNext(); j++) {
            System.out.print("ref[" + j + "] -> ");
            Reference ref = (Reference) i.next();
            System.out.print(ref.getURI());
            System.out.print(", ");
            System.out.print(ref.getDigestMethod().toString());
            System.out.print(", ");
            System.out.print(ref.getId());
            boolean refValid = ref.validate(validateContext);
            System.out.print(", validity status: " + refValid + "\r\n");
        }
        return false;
    }
}
项目:oscm    文件:XMLSignatureBuilder.java   
public Document sign(FileInputStream fileStream, KeyPair keyPair)
        throws ParserConfigurationException, SAXException, IOException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        KeyException, MarshalException, XMLSignatureException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(fileStream);

    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
            document.getDocumentElement());
    XMLSignatureFactory signFactory = XMLSignatureFactory
            .getInstance("DOM");
    Reference ref = signFactory.newReference("", signFactory
            .newDigestMethod(digestMethod, null), Collections
            .singletonList(signFactory.newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null)), null, null);
    SignedInfo si = signFactory.newSignedInfo(signFactory
            .newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null), signFactory
            .newSignatureMethod(signatureMethod, null), Collections
            .singletonList(ref));

    KeyInfoFactory kif = signFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(keyPair.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature signature = signFactory.newXMLSignature(si, ki);
    signature.sign(signContext);

    return document;
}
项目:oscm    文件:DigitalSignatureValidator.java   
private boolean validate(final DOMValidateContext validationContext)
        throws DigitalSignatureValidationException {

    try {
        // if (getLogger().isDebugLoggingEnabled()) {
        // enableReferenceCaching(validationContext);
        // }

        XMLSignatureFactory factory = XMLSignatureFactory
                .getInstance(XML_MECHANISM_TYPE);
        XMLSignature signature = factory
                .unmarshalXMLSignature(validationContext);
        boolean validationResult = signature.validate(validationContext);

        validationResult = workaroundOpenamBug(signature,
                validationContext, validationResult);

        // if (getLogger().isDebugLoggingEnabled()) {
        // debugLogReferences(signature, validationContext);
        // }
        return validationResult;
    } catch (XMLSignatureException | MarshalException exception) {
        throw new DigitalSignatureValidationException(
                "Error occurred during digital signature validation process",
                DigitalSignatureValidationException.ReasonEnum.EXCEPTION_OCCURRED,
                exception);
    }
}
项目:hadoopoffice    文件:MSExcelOOXMLSignUtil.java   
/** 
 * Signs the Excel OOXML file and writes it to the final outputstream
 * 
 * @param privateKey private Key for signing
 * @param x509 Certificate for private Key for signing
 * @param password optional password for encryption, if used
 * @param hashAlgorithm hash algorithm to be used
 * 
 * @throws MarshalException 
 * @throws XMLSignatureException 
 * @throws IOException 
 * @throws FormatNotUnderstoodException 
 */
public void sign(Key privateKey, X509Certificate x509, String password, HashAlgorithm hashAlgorithm) throws XMLSignatureException, MarshalException, IOException, FormatNotUnderstoodException {
    if (this.tempSignFileOS!=null) { // close it we sign only a closed temporary file
        this.tempSignFileOS.close();
    }
    SignatureConfig sc = new SignatureConfig();
       sc.addSignatureFacet(new OOXMLSignatureFacet());
       sc.addSignatureFacet(new KeyInfoSignatureFacet());
       sc.addSignatureFacet(new XAdESSignatureFacet());
       sc.addSignatureFacet(new Office2010SignatureFacet());
    sc.setKey((PrivateKey)privateKey);
    sc.setSigningCertificateChain(Collections.singletonList(x509));
    sc.setDigestAlgo(hashAlgorithm);
    FileInputStream tempSignFileIS = null;
    try {

        InputStream tmpFileInputStream = new FileInputStream(this.tempSignFile);
        if (password==null) {
            this.signUnencryptedOpcPackage(tmpFileInputStream, sc);
        } else {
            this.signEncryptedPackage(tmpFileInputStream, sc, password);
        }

    } catch (InvalidFormatException | IOException e) {
        LOG.error(e);
    } finally {
        if (this.finalOutputStream!=null) {
            this.finalOutputStream.close();
        }
        if (tempSignFileIS!=null) {
            tempSignFileIS.close();
        }
    }
}
项目:hadoopoffice    文件:MSExcelOOXMLSignUtil.java   
private void signUnencryptedOpcPackage(InputStream tmpFileInputStream, SignatureConfig sc) throws InvalidFormatException, IOException, XMLSignatureException, MarshalException {
    OPCPackage  pkg = OPCPackage.open(tmpFileInputStream);
    sc.setOpcPackage(pkg);
    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(sc);
    si.confirmSignature();
    pkg.save(this.finalOutputStream);
    pkg.close();
}
项目:hadoopoffice    文件:MSExcelOOXMLSignUtil.java   
private void signEncryptedPackage(InputStream tmpFileInputStream, SignatureConfig sc, String password) throws IOException, InvalidFormatException, FormatNotUnderstoodException, XMLSignatureException, MarshalException {

    NPOIFSFileSystem poifsTemp = new NPOIFSFileSystem(tmpFileInputStream);
    EncryptionInfo info = new EncryptionInfo(poifsTemp);
    Decryptor d = Decryptor.getInstance(info);
    try {
        if (!d.verifyPassword(password)) {
            throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing. Invalid password");
        }
        // signing
        OPCPackage pkg = OPCPackage.open(d.getDataStream(poifsTemp));
        sc.setOpcPackage(pkg);
        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(sc);
        si.confirmSignature();
        // encrypt again
        Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);
        NPOIFSFileSystem poifs = new NPOIFSFileSystem();
        OutputStream os = enc.getDataStream(poifs);
        pkg.save(os);
        pkg.close();
        if (os!=null) {
            os.close();
        }
        poifs.writeFilesystem(this.finalOutputStream);
        if (poifs!=null) {
            poifs.close();
        }
        if (poifsTemp!=null) {
            poifsTemp.close();
        }
    } catch (GeneralSecurityException e) {

        LOG.error(e);
        throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx)  for signing.");
    }
}
项目:xmlsec-gost    文件:AbstractDOMSignatureMethod.java   
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(XmlWriter xwriter, String dsPrefix)
    throws MarshalException
{
    xwriter.writeStartElement(dsPrefix, "SignatureMethod", XMLSignature.XMLNS);
    xwriter.writeAttribute("", "", "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(xwriter, dsPrefix);
    }
    xwriter.writeEndElement(); // "SignatureMethod"
}
项目:xmlsec-gost    文件:Marshaller.java   
@Override
public void marshalObject(XmlWriter xwriter, KeyValue toMarshal, String dsPrefix,
        XMLCryptoContext context) throws MarshalException {
    // Since DOMKeyValue allows for deserializing unrecognized keys, and that
    // capability isn't available via the KeyValue interface, this must continue
    // to cast to DOMKeyValue.
    DOMKeyValue<?> dkv = (DOMKeyValue<?>) toMarshal;
    dkv.marshal( xwriter, dsPrefix, context);
}
项目:xmlsec-gost    文件:DOMTransform.java   
/**
 * Creates a <code>DOMTransform</code> from an element. It unmarshals any
 * algorithm-specific input parameters.
 *
 * @param transElem a Transform element
 */
public DOMTransform(Element transElem, XMLCryptoContext context,
                    Provider provider)
    throws MarshalException
{
    String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm");
    if (provider == null) {
        try {
            spi = TransformService.getInstance(algorithm, "DOM");
        } catch (NoSuchAlgorithmException e1) {
            throw new MarshalException(e1);
        }
    } else {
        try {
            spi = TransformService.getInstance(algorithm, "DOM", provider);
        } catch (NoSuchAlgorithmException nsae) {
            try {
                spi = TransformService.getInstance(algorithm, "DOM");
            } catch (NoSuchAlgorithmException e2) {
                throw new MarshalException(e2);
            }
        }
    }
    try {
        spi.init(new javax.xml.crypto.dom.DOMStructure(transElem), context);
    } catch (InvalidAlgorithmParameterException iape) {
        throw new MarshalException(iape);
    }
}
项目:xmlsec-gost    文件:DOMTransform.java   
/**
 * This method marshals any algorithm-specific parameters.
 */
public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
    throws MarshalException
{
    String parentLocalName = xwriter.getCurrentLocalName();
    String localName = parentLocalName.equals("Transforms") ? "Transform" : "CanonicalizationMethod";
    xwriter.writeStartElement(dsPrefix, localName, XMLSignature.XMLNS);
    xwriter.writeAttribute("", "", "Algorithm", getAlgorithm());

    javax.xml.crypto.XMLStructure xmlStruct = xwriter.getCurrentNodeAsStructure();
    spi.marshalParams(xmlStruct, context);

    xwriter.writeEndElement(); // "Transforms" or "CanonicalizationMethod"
}
项目:xmlsec-gost    文件:XmlWriterToTree.java   
@Override
public void marshalStructure(XMLStructure toMarshal, String dsPrefix, XMLCryptoContext context) throws MarshalException {

    // look for the first isInstance match, and marshal to that.
    for (int idx = 0 ; idx < m_marshallers.size() ; idx++) {
        @SuppressWarnings("unchecked")
        XmlWriter.ToMarshal<XMLStructure> marshaller = (ToMarshal<XMLStructure>) m_marshallers.get(idx);
        if (marshaller.clazzToMatch.isInstance(toMarshal)) {
            marshaller.marshalObject(this, toMarshal, dsPrefix, context);
            return;
        }
    }
    throw new IllegalArgumentException("Unable to marshal unexpected object of class " + toMarshal.getClass().toString());
}
项目:xmlsec-gost    文件:DOMX509IssuerSerial.java   
/**
 * Creates a <code>DOMX509IssuerSerial</code> from an element.
 *
 * @param isElem an X509IssuerSerial element
 */
public DOMX509IssuerSerial(Element isElem) throws MarshalException {
    Element iNElem = DOMUtils.getFirstChildElement(isElem,
                                                   "X509IssuerName",
                                                   XMLSignature.XMLNS);
    Element sNElem = DOMUtils.getNextSiblingElement(iNElem,
                                                    "X509SerialNumber",
                                                    XMLSignature.XMLNS);
    issuerName = iNElem.getFirstChild().getNodeValue();
    serialNumber = new BigInteger(sNElem.getFirstChild().getNodeValue());
}
项目:xmlsec-gost    文件:DOMKeyInfo.java   
/**
 * Creates a <code>DOMKeyInfo</code> from XML.
 *
 * @param kiElem KeyInfo element
 */
public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
                  Provider provider)
    throws MarshalException
{
    id = DOMUtils.getIdAttributeValue(kiElem, "Id");

    // get all children nodes
    List<XMLStructure> content = new ArrayList<XMLStructure>();
    Node firstChild = kiElem.getFirstChild();
    if (firstChild == null) {
        throw new MarshalException("KeyInfo must contain at least one type");
    }
    while (firstChild != null) {
        if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
            Element childElem = (Element)firstChild;
            String localName = childElem.getLocalName();
            String namespace = childElem.getNamespaceURI();
            if (localName.equals("X509Data") && XMLSignature.XMLNS.equals(namespace)) {
                content.add(new DOMX509Data(childElem));
            } else if (localName.equals("KeyName") && XMLSignature.XMLNS.equals(namespace)) {
                content.add(new DOMKeyName(childElem));
            } else if (localName.equals("KeyValue") && XMLSignature.XMLNS.equals(namespace)) {
                content.add(DOMKeyValue.unmarshal(childElem));
            } else if (localName.equals("RetrievalMethod") && XMLSignature.XMLNS.equals(namespace)) {
                content.add(new DOMRetrievalMethod(childElem,
                                                   context, provider));
            } else if (localName.equals("PGPData") && XMLSignature.XMLNS.equals(namespace)) {
                content.add(new DOMPGPData(childElem));
            } else { //may be MgmtData, SPKIData or element from other namespace
                content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
            }
        }
        firstChild = firstChild.getNextSibling();
    }
    keyInfoTypes = Collections.unmodifiableList(content);
}
项目:xmlsec-gost    文件:DOMKeyInfo.java   
@Override
public void marshal(XMLStructure parent, XMLCryptoContext context)
    throws MarshalException
{
    if (parent == null) {
        throw new NullPointerException("parent is null");
    }
    if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
        throw new ClassCastException("parent must be of type DOMStructure");
    }

    internalMarshal( (javax.xml.crypto.dom.DOMStructure) parent, context);
}
项目:xmlsec-gost    文件:DOMKeyInfo.java   
private void internalMarshal(javax.xml.crypto.dom.DOMStructure parent, XMLCryptoContext context)
        throws MarshalException {
    Node pNode = parent.getNode();
    String dsPrefix = DOMUtils.getSignaturePrefix(context);

    Node nextSibling = null;
    if (context instanceof DOMSignContext) {
        nextSibling = ((DOMSignContext)context).getNextSibling();
    }

    XmlWriterToTree xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), pNode, nextSibling);
    marshalInternal(xwriter, this, dsPrefix, context, true);
}
项目:nomulus    文件:TmchXmlSignature.java   
/**
 * Verifies that signed mark data contains a valid signature.
 *
 * <p>This method DOES NOT check if the SMD ID is revoked. It's only concerned with the
 * cryptographic stuff.
 *
 * @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH,
 *     incorrect keys, and for invalid, old, not-yet-valid or revoked certificates.
 * @throws IOException
 * @throws MarshalException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public void verify(byte[] smdXml)
    throws GeneralSecurityException, IOException, MarshalException, ParserConfigurationException,
        SAXException, XMLSignatureException {
  checkArgument(smdXml.length > 0);
  Document doc = parseSmdDocument(new ByteArrayInputStream(smdXml));

  NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
  if (signatureNodes.getLength() != 1) {
    throw new XMLSignatureException("Expected exactly one <ds:Signature> element.");
  }
  XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
  KeyValueKeySelector selector = new KeyValueKeySelector(tmchCertificateAuthority);
  DOMValidateContext context = new DOMValidateContext(selector, signatureNodes.item(0));
  XMLSignature signature = factory.unmarshalXMLSignature(context);

  boolean isValid;
  try {
    isValid = signature.validate(context);
  } catch (XMLSignatureException e) {
    throwIfInstanceOf(getRootCause(e), GeneralSecurityException.class);
    throw e;
  }
  if (!isValid) {
    throw new XMLSignatureException(explainValidationProblem(context, signature));
  }
}
项目:eid-applet    文件:ODFSignatureVerifier.java   
/**
 * return list of signers for the document available via the given URL.
 *
 * @param odfUrl
 * @return list of X509 certificates
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
public static List<X509Certificate> getSigners(URL odfUrl)
        throws IOException, ParserConfigurationException, SAXException, MarshalException, XMLSignatureException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    if (null == odfUrl) {
        throw new IllegalArgumentException("odfUrl is null");
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(odfUrl.openStream());
    ZipEntry zipEntry;

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Node signatureNode = signatureNodeList.item(idx);
                X509Certificate signer = getVerifiedSignatureSigner(odfUrl, signatureNode);
                if (null == signer) {
                    LOG.debug("JSR105 says invalid signature");
                } else {
                    signers.add(signer);
                }
            }
            return signers;
        }
    }
    LOG.debug("no signature file present");
    return signers;
}
项目:eid-applet    文件:ODFSignatureVerifier.java   
private static X509Certificate getVerifiedSignatureSigner(URL odfUrl, Node signatureNode)
        throws MarshalException, XMLSignatureException {
    if (null == odfUrl) {
        throw new IllegalArgumentException("odfUrl is null");
    }
    KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);
    ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl);
    domValidateContext.setURIDereferencer(dereferencer);

    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    LOG.debug("java version: " + System.getProperty("java.version"));
    /*
     * Requires Java 6u10 because of a bug. See also:
     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582
     */
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = xmlSignature.validate(domValidateContext);
    if (false == validity) {
        LOG.debug("invalid signature");
        return null;
    }
    // TODO: check what has been signed.

    X509Certificate signer = keySelector.getCertificate();
    if (null == signer) {
        throw new IllegalStateException("signer X509 certificate is null");
    }
    LOG.debug("signer: " + signer.getSubjectX500Principal());
    return signer;
}
项目:eid-applet    文件:XPSSignatureVerifier.java   
public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException,
        TransformerException, MarshalException, XMLSignatureException, JAXBException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    List<String> signatureResourceNames = getSignatureResourceNames(url);
    for (String signatureResourceName : signatureResourceNames) {
        LOG.debug("signature resource name: " + signatureResourceName);
        Document signatureDocument = loadDocument(url, signatureResourceName);
        if (null == signatureDocument) {
            LOG.warn("signature resource not found: " + signatureResourceName);
            continue;
        }

        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (0 == signatureNodeList.getLength()) {
            LOG.debug("no signature elements present");
            continue;
        }
        Node signatureNode = signatureNodeList.item(0);

        OPCKeySelector keySelector = new OPCKeySelector(url, signatureResourceName);
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);
        domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
        OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean validity = xmlSignature.validate(domValidateContext);

        if (false == validity) {
            LOG.debug("not a valid signature");
            continue;
        }
        // TODO: check what has been signed.

        X509Certificate signer = keySelector.getCertificate();
        signers.add(signer);
    }
    return signers;
}
项目:eid-applet    文件:AbstractODFSignatureServiceTest.java   
private boolean hasOdfSignature(URL odfUrl, int signatureCount) throws IOException, ParserConfigurationException,
        SAXException, org.apache.xml.security.signature.XMLSignatureException, XMLSecurityException,
        MarshalException, XMLSignatureException {
    InputStream odfInputStream = odfUrl.openStream();
    if (null == odfInputStream) {
        return false;
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        LOG.debug(zipEntry.getName());
        if (true == "META-INF/documentsignatures.xml".equals(zipEntry.getName())) {
            Document documentSignatures = loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
            assertEquals(signatureCount, signatureNodeList.getLength());
            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Node signatureNode = signatureNodeList.item(idx);
                if (false == verifySignature(odfUrl, signatureNode)) {
                    LOG.debug("JSR105 says invalid signature");
                    return false;
                }
            }
            return true;
        }
    }
    LOG.debug("no documentsignatures.xml entry present");
    return false;
}