Java 类javax.xml.crypto.dsig.dom.DOMSignContext 实例源码

项目:jdk8u-jdk    文件:GenerationTests.java   
static void test_create_signature_with_empty_id() throws Exception {
    System.out.println("* Generating signature-with-empty-id.xml");

    // create references
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", sha1));

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);

    // create object with empty id
    Document doc = db.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    sig.sign(dsc);
}
项目:openjdk-jdk10    文件:GenerationTests.java   
static void test_create_signature_with_empty_id() throws Exception {
    System.out.println("* Generating signature-with-empty-id.xml");

    // create references
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", sha1));

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);

    // create object with empty id
    Document doc = db.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    sig.sign(dsc);
}
项目:openjdk9    文件:GenerationTests.java   
static void test_create_signature_with_empty_id() throws Exception {
    System.out.println("* Generating signature-with-empty-id.xml");

    // create references
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", sha1));

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);

    // create object with empty id
    Document doc = db.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    sig.sign(dsc);
}
项目:xmlsec-gost    文件:XMLSignatureTest.java   
@org.junit.Test
    public void testSignWithEmptyNSPrefix() throws Exception {
        SignedInfo si = createSignedInfo(SIG_METHODS[1]);
        KeyInfo ki = kifac.newKeyInfo(Collections.singletonList
                    (kifac.newKeyValue((PublicKey) VALIDATE_KEYS[1])));
        XMLSignature sig = fac.newXMLSignature(si, ki, objs, id, sigValueId);
        Document doc = TestUtils.newDocument();
        XMLSignContext signContext = new DOMSignContext(SIGN_KEYS[1], doc);
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "");
        signContext.setURIDereferencer(ud);
        sig.sign(signContext);
        TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
/*
        StringWriter sw = new StringWriter();
        dumpDocument(doc, sw);
        System.out.println(sw);
*/
    }
项目:xmlsec-gost    文件:XMLSignatureTest.java   
@org.junit.Test
public void testCreateDSA2048Signature() throws Exception {

    // check if SHA256withDSA is supported
    boolean gotSHA256withDSA = false;
    try {
        Signature.getInstance("SHA256withDSA");
        gotSHA256withDSA = true;
    } catch (NoSuchAlgorithmException e) {}
    org.junit.Assume.assumeTrue(gotSHA256withDSA);

    SignatureMethod sm = fac.newSignatureMethod(DSA_SHA256, null);
    SignedInfo si = createSignedInfo(sm);
    KeyInfo ki = kifac.newKeyInfo(Collections.singletonList
        (kifac.newKeyValue((PublicKey)TestUtils.getPublicKey("DSA", 2048))));
    XMLSignature sig = fac.newXMLSignature(si, ki, objs, id, sigValueId);
    Document doc = TestUtils.newDocument();
    XMLSignContext signContext =
        new DOMSignContext(TestUtils.getPrivateKey("DSA", 2048), doc);
    signContext.setURIDereferencer(ud);
    sig.sign(signContext);
    XMLValidateContext validateContext = new DOMValidateContext
        (TestUtils.getPublicKey("DSA", 2048), doc.getDocumentElement());
    validateContext.setURIDereferencer(ud);
    assertTrue(sig.validate(validateContext));
}
项目:jdk8u_jdk    文件:GenerationTests.java   
static void test_create_signature_with_empty_id() throws Exception {
    System.out.println("* Generating signature-with-empty-id.xml");

    // create references
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", sha1));

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);

    // create object with empty id
    Document doc = db.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    sig.sign(dsc);
}
项目:lookaside_java-1.8.0-openjdk    文件:GenerationTests.java   
static void test_create_signature_with_empty_id() throws Exception {
    System.out.println("* Generating signature-with-empty-id.xml");

    // create references
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", sha1));

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);

    // create object with empty id
    Document doc = db.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    sig.sign(dsc);
}
项目: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);
}
项目:cas-5.1.0    文件:AbstractSamlObjectBuilder.java   
/**
 * 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 XMLSignatureFactory sigFactory = XMLSignatureFactory
                .getInstance("DOM", (Provider) Class.forName(providerName).newInstance());

        final List<Transform> envelopedTransform = Collections.singletonList(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 RuntimeException("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, Collections.singletonList(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(Collections.singletonList(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 RuntimeException("Error signing SAML element: " + e.getMessage(), e);
    }
}
项目:neoscada    文件:RequestSigner.java   
synchronized void sign ( final Key privateKey, final PublicKey publicKey, final Certificate cert, final Document doc ) throws Exception
{
    final DOMSignContext dsc = new DOMSignContext ( privateKey, doc.getDocumentElement () );

    final SignatureMethod sm = this.fac.newSignatureMethod ( fromAlg ( privateKey.getAlgorithm () ), null );

    final SignedInfo si = this.fac.newSignedInfo ( this.cm, sm, Collections.singletonList ( this.ref ) );

    final List<Object> data = new LinkedList<Object> ();

    if ( cert != null )
    {
        data.add ( this.kif.newKeyValue ( cert.getPublicKey () ) );
        data.add ( this.kif.newX509Data ( Collections.singletonList ( cert ) ) );
    }
    else
    {
        data.add ( this.kif.newKeyValue ( publicKey ) );
    }

    final KeyInfo ki = this.kif.newKeyInfo ( data );

    final XMLSignature signature = this.fac.newXMLSignature ( si, ki );

    // finally sign
    signature.sign ( dsc );
}
项目: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;
}
项目: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);
}
项目:xmlsec-gost    文件:XMLSignatureTest.java   
@org.junit.Test
public void testSignTemplateWithObjectNSDefs() throws Exception {
    String base = System.getProperty("basedir") == null ? "./"
                  : System.getProperty("basedir");

    File f = new File(base + "/src/test/resources/javax/xml/crypto/dsig/" +
        "signature-enveloping-rsa-template.xml");

    Document doc = XMLUtils.createDocumentBuilder(false).parse(new FileInputStream(f));

    // Find Signature element
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Cannot find Signature element");
    }
    DOMStructure domSignature = new DOMStructure(nl.item(0));
    // unmarshal the XMLSignature
    XMLSignature signature = fac.unmarshalXMLSignature(domSignature);

    // create copy of Signature
    XMLSignature newSignature = fac.newXMLSignature
        (signature.getSignedInfo(), null, signature.getObjects(),
         signature.getId(), signature.getSignatureValue().getId());

    // Sign the template
    Node parent = domSignature.getNode().getParentNode();
    DOMSignContext signContext = new DOMSignContext(SIGN_KEYS[0], parent);
    // remove the signature node (since it will get recreated)
    parent.removeChild(domSignature.getNode());
    newSignature.sign(signContext);
    TestUtils.validateSecurityOrEncryptionElement(parent.getLastChild());

    // check that Object element retained namespace definitions
    Element objElem = (Element)parent.getFirstChild().getLastChild();
    Attr a = objElem.getAttributeNode("xmlns:test");
    if (!a.getValue().equals("http://www.example.org/ns")) {
        throw new Exception("Object namespace definition not retained");
    }
}
项目:xmlsec-gost    文件:XMLSignatureTest.java   
@org.junit.Test
public void testCreateSignatureWithEmptyId() throws Exception {
    // create references
    DigestMethod dm = fac.newDigestMethod(DigestMethod.SHA1, null);
    List<Reference> refs = Collections.singletonList
        (fac.newReference("#", dm));

    // create SignedInfo
    CanonicalizationMethod cm = fac.newCanonicalizationMethod
        (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo si = fac.newSignedInfo(cm, SIG_METHODS[1], refs);

    // create object with empty id
    Document doc = TestUtils.newDocument();
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("I am the text."))),
        "", "text/plain", null);

    KeyInfo ki = kifac.newKeyInfo(Collections.singletonList
                (kifac.newKeyValue((PublicKey) VALIDATE_KEYS[1])));

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki,
                                           Collections.singletonList(obj),
                                           "signature", null);
    DOMSignContext dsc = new DOMSignContext(SIGN_KEYS[1], doc);
    sig.sign(dsc);
}
项目:xmlsec-gost    文件:HMACSignatureAlgorithmTest.java   
private void test_create_signature_enveloping(
    SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks
) throws Exception {

    // create reference
    Reference ref = fac.newReference("#DSig.Object_1", dm, null,
                                     XMLObject.TYPE, null);

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm,
                                      Collections.singletonList(ref));

    Document doc = db.newDocument();
    // create Objects
    Element webElem = doc.createElementNS(null, "Web");
    Text text = doc.createTextNode("up up and away");
    webElem.appendChild(text);
    XMLObject obj = fac.newXMLObject(Collections.singletonList
                                     (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature
    (si, ki, Collections.singletonList(obj), null, null);

    DOMSignContext dsc = new DOMSignContext(signingKey, doc);
    dsc.setDefaultNamespacePrefix("dsig");

    sig.sign(dsc);
    TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());

    // XMLUtils.outputDOM(doc.getDocumentElement(), System.out);

    DOMValidateContext dvc = new DOMValidateContext
    (ks, doc.getDocumentElement());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

    assertTrue(sig.equals(sig2));
    assertTrue(sig2.validate(dvc));
}
项目:xmlsec-gost    文件:PKSignatureAlgorithmTest.java   
private void test_create_signature_enveloping(
    SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks
) throws Exception {

    // create reference
    Reference ref = fac.newReference("#DSig.Object_1", dm, null,
                                     XMLObject.TYPE, null);

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm,
                                      Collections.singletonList(ref));

    Document doc = db.newDocument();
    // create Objects
    Element webElem = doc.createElementNS(null, "Web");
    Text text = doc.createTextNode("up up and away");
    webElem.appendChild(text);
    XMLObject obj = fac.newXMLObject(Collections.singletonList
                                     (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature
    (si, ki, Collections.singletonList(obj), null, null);

    DOMSignContext dsc = new DOMSignContext(signingKey, doc);
    dsc.setDefaultNamespacePrefix("dsig");

    sig.sign(dsc);
    TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());

    // XMLUtils.outputDOM(doc.getDocumentElement(), System.out);

    DOMValidateContext dvc = new DOMValidateContext
    (ks, doc.getDocumentElement());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

    assertTrue(sig.equals(sig2));
    assertTrue(sig2.validate(dvc));
}
项目:xmlsec-gost    文件:SignatureDigestMethodTest.java   
private void test_create_signature_enveloping(
    SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks
) throws Exception {

    // create reference
    Reference ref = fac.newReference("#DSig.Object_1", dm, null,
                                     XMLObject.TYPE, null);

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm,
                                      Collections.singletonList(ref));

    Document doc = db.newDocument();
    // create Objects
    Element webElem = doc.createElementNS(null, "Web");
    Text text = doc.createTextNode("up up and away");
    webElem.appendChild(text);
    XMLObject obj = fac.newXMLObject(Collections.singletonList
                                     (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature
    (si, ki, Collections.singletonList(obj), null, null);

    DOMSignContext dsc = new DOMSignContext(signingKey, doc);
    dsc.setDefaultNamespacePrefix("dsig");

    sig.sign(dsc);
    TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());

    // XMLUtils.outputDOM(doc.getDocumentElement(), System.out);

    DOMValidateContext dvc = new DOMValidateContext
    (ks, doc.getDocumentElement());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

    assertTrue(sig.equals(sig2));
    assertTrue(sig2.validate(dvc));
}
项目:xmlsec-gost    文件:CreateBaltimore23Test.java   
@org.junit.Test
public void test_create_signature_enveloped_dsa() throws Exception {
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo
        (withoutComments, dsaSha1, Collections.singletonList
            (fac.newReference
                ("", sha1, Collections.singletonList
                    (fac.newTransform(Transform.ENVELOPED,
                     (TransformParameterSpec) null)),
             null, null)));

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, dsa);

    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS
        (Constants.NamespaceSpecNS, "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    DOMSignContext dsc = new DOMSignContext(signingKey, envelope);

    sig.sign(dsc);
    TestUtils.validateSecurityOrEncryptionElement(envelope.getFirstChild());

    DOMValidateContext dvc = new DOMValidateContext
        (kvks, envelope.getFirstChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

    assertTrue(sig.equals(sig2));

    assertTrue(sig2.validate(dvc));
}
项目:xmlsec-gost    文件:CreateBaltimore23Test.java   
private void test_create_signature_enveloping
    (SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks,
    boolean b64) throws Exception {

    // create reference
    Reference ref;
    if (b64) {
        ref = fac.newReference("#object", sha1, Collections.singletonList
            (fac.newTransform(Transform.BASE64,
             (TransformParameterSpec) null)), null, null);
    } else {
        ref = fac.newReference("#object", sha1);
    }

    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm,
        Collections.singletonList(ref));

    Document doc = db.newDocument();
    // create Objects
    XMLObject obj = fac.newXMLObject(Collections.singletonList
        (new DOMStructure(doc.createTextNode("some text"))),
        "object", null, null);

    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature
        (si, ki, Collections.singletonList(obj), null, null);

    DOMSignContext dsc = new DOMSignContext(signingKey, doc);

    sig.sign(dsc);
    TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());

    DOMValidateContext dvc = new DOMValidateContext
        (ks, doc.getDocumentElement());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

    assertTrue(sig.equals(sig2));
    assertTrue(sig2.validate(dvc));
}
项目:xmlsec-gost    文件:XMLSignContextTest.java   
public XMLSignContextTest() throws Exception {
    // set up the signingKeys
    KEYS = new Key[3];
    KEYS[0] = TestUtils.getPrivateKey("DSA");
    KEYS[1] = TestUtils.getPrivateKey("RSA");
    KEYS[2] = new SecretKeySpec(new byte[16], "HmacSHA1");
    // set up the default XMLSignContext
    SecretKey sk = new SecretKeySpec(new byte[8], "DES");
    doc = TestUtils.newDocument();
    defContext = new DOMSignContext(sk, doc);
}
项目:nfce    文件:AssinaturaDigital.java   
public String assinarDocumento(final String conteudoXml) throws Exception {
    final KeyStore keyStore = KeyStore.getInstance("PKCS12");
    try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) {
        keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray());
    }

    final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()));
    final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    final List<Transform> transforms = new ArrayList<>(2);
    transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));

    final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
    final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    try (StringReader stringReader = new StringReader(conteudoXml)) {
        final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader));
        for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) {
            final NodeList elements = document.getElementsByTagName(elementoAssinavel);
            for (int i = 0; i < elements.getLength(); i++) {
                final Element element = (Element) elements.item(i);
                final String id = element.getAttribute("Id");
                element.setIdAttribute("Id", true);

                final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
                final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));

                final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
                signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
            }
        }
        return this.converteDocumentParaXml(document);
    }
}
项目:Camel    文件:XmlSignerProcessor.java   
private DOMSignContext createAndConfigureSignContext(Node parent, KeySelector keySelector) {
    DOMSignContext dsc = new DOMSignContext(keySelector, parent);
    // set namespace prefix for "http://www.w3.org/2000/09/xmldsig#" according to best practice described in http://www.w3.org/TR/xmldsig-bestpractices/#signing-xml-without-namespaces
    if (getConfiguration().getPrefixForXmlSignatureNamespace() != null
            && !getConfiguration().getPrefixForXmlSignatureNamespace().isEmpty()) {
        dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", getConfiguration().getPrefixForXmlSignatureNamespace());
    }
    dsc.putNamespacePrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
    setCryptoContextProperties(dsc);
    setUriDereferencerAndBaseUri(dsc);
    return dsc;
}
项目:eid-applet    文件:XmlSignatureServiceBeanTest.java   
@Test
public void testJsr105ReferenceUri() throws Exception {
    String uri = FilenameUtils.getName(new File("foo bar.txt").toURI().toURL().getFile());

    KeyPair keyPair = generateKeyPair();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document);

    byte[] externalDocument = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(externalDocument);
    byte[] documentDigestValue = messageDigest.digest();

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
    Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue);

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod,
            signatureMethod, Collections.singletonList(reference));

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);

    xmlSignature.sign(signContext);
}
项目:development    文件: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;
}
项目:oiosaml.java    文件:OIOSoapEnvelope.java   
private Element signSignature(String id, Element env, KeyInfoFactory keyInfoFactory, X509Credential credential) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    if (endorsingToken == null) return env;

    NodeList nl = env.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        if (e.hasAttributeNS(null, "Id")) {
            e.setAttributeNS(WSSecurityConstants.WSU_NS, "Id", e.getAttribute("Id"));
            e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true);
        }
    }
    env = SAMLUtil.loadElementFromString(XMLHelper.nodeToString(env));


    DigestMethod digestMethod = xsf.newDigestMethod(DigestMethod.SHA1, null);
    List<Transform> transforms = new ArrayList<Transform>(2);
    transforms.add(xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",new ExcC14NParameterSpec(Collections.singletonList("xsd"))));


    List<Reference> refs = new ArrayList<Reference>();
    Reference r = xsf.newReference("#"+id, digestMethod, transforms, null, null);
    refs.add(r);

    CanonicalizationMethod canonicalizationMethod = xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignatureMethod signatureMethod = xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    SignedInfo signedInfo = xsf.newSignedInfo(canonicalizationMethod, signatureMethod, refs);

    KeyInfo ki = generateKeyInfo(credential, keyInfoFactory, false);
    XMLSignature signature = xsf.newXMLSignature(signedInfo, ki);

       Node security = env.getElementsByTagNameNS(WSSecurityConstants.WSSE_NS, "Security").item(0);

       DOMSignContext signContext = new DOMSignContext(credential.getPrivateKey(), security); 
       signContext.putNamespacePrefix(SAMLConstants.XMLSIG_NS, SAMLConstants.XMLSIG_PREFIX);
       signContext.putNamespacePrefix(SAMLConstants.XMLENC_NS, SAMLConstants.XMLENC_PREFIX);

       signature.sign(signContext);

       return env;
}
项目:opes    文件:CertificadoDigital.java   
public <T extends Node> T sign(T node) {
    checkNotNull(node);
    checkArgument(node instanceof Document || node instanceof Element);
    try {
        Element element = node instanceof Document ? ((Document) node).getDocumentElement() : (Element) node;
        DOMSignContext dsc = new DOMSignContext(privateKey, element);
        XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

        List<Transform> transformList = new LinkedList<>();
        transformList.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        transformList.add(signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));

        Node child = findFirstElementChild(element);
        ((Element) child).setIdAttribute("Id", true);

        String id = child.getAttributes().getNamedItem("Id").getNodeValue();
        String uri = String.format("#%s", id);
        Reference reference = signatureFactory.newReference(uri,
                signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);

        SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(
                CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory
                .newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));

        KeyInfoFactory kif = signatureFactory.getKeyInfoFactory();
        X509Data x509Data = kif.newX509Data(Collections.singletonList(certificateChain[0]));
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(x509Data));

        XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo);

        xmlSignature.sign(dsc);

        return node;
    }
    catch (Exception ex) {
        throw new IllegalArgumentException("Erro ao assinar XML.", ex);
    }
}
项目:goja    文件:XML.java   
/**
 * Sign the XML document using xmldsig.
 *
 * @param document   the document to sign; it will be modified by the method.
 * @param publicKey  the public key from the key pair to sign the document.
 * @param privateKey the private key from the key pair to sign the document.
 * @return the signed document for chaining.
 */
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();

    try {
        Reference ref = fac.newReference(
                "",
                fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(
                        fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null,
                null);
        SignedInfo si =
                fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
                        (C14NMethodParameterSpec) null),
                        fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                        Collections.singletonList(ref));
        DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement());
        KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
        KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue));
        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);
    } catch (Exception e) {
        logger.warn("Error while signing an XML document.", e);
    }

    return document;
}
项目:muleebmsadapter    文件:XMLDSignatureOutInterceptor.java   
private void sign(KeyStore keyStore, KeyPair keyPair, String alias, Document document, List<EbMSDataSource> dataSources) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, KeyException, MarshalException, XMLSignatureException, KeyStoreException
{
    //XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance();
    DigestMethod sha1DigestMethod = signFactory.newDigestMethod(DigestMethod.SHA1,null);

    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(signFactory.newTransform(Transform.ENVELOPED,(TransformParameterSpec)null));
    Map<String,String> m = new HashMap<String,String>();
    m.put("soap","http://schemas.xmlsoap.org/soap/envelope/");
    transforms.add(signFactory.newTransform(Transform.XPATH,new XPathFilterParameterSpec("not(ancestor-or-self::node()[@soap:actor=\"urn:oasis:names:tc:ebxml-msg:service:nextMSH\"]|ancestor-or-self::node()[@soap:actor=\"http://schemas.xmlsoap.org/soap/actor/next\"])",m)));
    transforms.add(signFactory.newTransform(CanonicalizationMethod.INCLUSIVE,(TransformParameterSpec)null));

    List<Reference> references = new ArrayList<Reference>();
    references.add(signFactory.newReference("",sha1DigestMethod,transforms,null,null));

    for (EbMSDataSource dataSource : dataSources)
        references.add(signFactory.newReference("cid:" + dataSource.getContentId(),sha1DigestMethod,Collections.emptyList(),null,null,DigestUtils.sha(IOUtils.toByteArray(dataSource.getInputStream()))));

    SignedInfo signedInfo = signFactory.newSignedInfo(signFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,(C14NMethodParameterSpec)null),signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1,null),references);

    List<XMLStructure> keyInfoElements = new ArrayList<XMLStructure>();
    KeyInfoFactory keyInfoFactory = signFactory.getKeyInfoFactory();
    keyInfoElements.add(keyInfoFactory.newKeyValue(keyPair.getPublic()));

    Certificate[] certificates = keyStore.getCertificateChain(alias);
    //keyInfoElements.add(keyInfoFactory.newX509Data(Arrays.asList(certificates)));
    keyInfoElements.add(keyInfoFactory.newX509Data(Collections.singletonList(certificates[0])));

    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoElements);

    XMLSignature signature = signFactory.newXMLSignature(signedInfo,keyInfo);

    Element soapHeader = getFirstChildElement(document.getDocumentElement());
    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),soapHeader);
    signContext.putNamespacePrefix(XMLSignature.XMLNS,"ds");
    signature.sign(signContext);
}
项目:mycarenet    文件:RequestFactory.java   
private void signRequest(Element requestElement, PrivateKey privateKey,
        X509Certificate certificate) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(privateKey,
            requestElement, requestElement.getFirstChild());
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory
            .getInstance("DOM");

    String requestId = requestElement.getAttribute("RequestID");
    requestElement.setIdAttribute("RequestID", true);

    List<Transform> transforms = new LinkedList<>();
    transforms.add(xmlSignatureFactory.newTransform(Transform.ENVELOPED,
            (TransformParameterSpec) null));
    transforms.add(xmlSignatureFactory.newTransform(
            CanonicalizationMethod.EXCLUSIVE,
            (C14NMethodParameterSpec) null));
    Reference reference = xmlSignatureFactory.newReference("#" + requestId,
            xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            transforms, null, null);

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null), xmlSignatureFactory
                    .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
            .singletonList(keyInfoFactory.newX509Data(Collections
                    .singletonList(certificate))));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(
            signedInfo, keyInfo);
    xmlSignature.sign(domSignContext);
}
项目:mycarenet    文件:ProofOfPossessionSignatureSOAPHandler.java   
private void addSignature(Element parentElement)
        throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(
            this.sessionKey.getPrivate(), parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory
            .getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference("#"
            + this.prototypeKeyBindingId, xmlSignatureFactory
            .newDigestMethod(DigestMethod.SHA1, null), Collections
            .singletonList(xmlSignatureFactory.newTransform(
                    CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null)), null, null);

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null), xmlSignatureFactory
                    .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(
            signedInfo, null);
    xmlSignature.sign(domSignContext);
}
项目:mycarenet    文件:ProofOfPossessionSignatureSOAPHandler.java   
private void addSignature(Element parentElement)
        throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(
            this.sessionKey.getPrivate(), parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory
            .getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference("#"
            + this.prototypeKeyBindingId, xmlSignatureFactory
            .newDigestMethod(DigestMethod.SHA1, null), Collections
            .singletonList(xmlSignatureFactory.newTransform(
                    CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null)), null, null);

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null), xmlSignatureFactory
                    .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(
            signedInfo, null);
    xmlSignature.sign(domSignContext);
}
项目:mycarenet    文件:KeyBindingAuthenticationSignatureSOAPHandler.java   
private void addSignature(Element parentElement)
        throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(
            this.authnPrivateKey, parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory
            .getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference(
            this.referenceUri, xmlSignatureFactory.newDigestMethod(
                    DigestMethod.SHA1, null), Collections
                    .singletonList(xmlSignatureFactory.newTransform(
                            CanonicalizationMethod.EXCLUSIVE,
                            (TransformParameterSpec) null)), null, null);

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null), xmlSignatureFactory
                    .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
            .singletonList(keyInfoFactory.newX509Data(Collections
                    .singletonList(this.authnCertificate))));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(
            signedInfo, keyInfo);
    xmlSignature.sign(domSignContext);
}
项目:hapi-fhir    文件:DigitalSignatures.java   
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 

  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 

  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 

  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));

  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);

  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
项目:dssp    文件:PendingRequestFactory.java   
private static void sign(Document document, DigitalSignatureServiceSession session) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    Key key = new SecretKeySpec(session.getKey(), "HMACSHA1");
    Node parentElement = document.getElementsByTagNameNS("urn:oasis:names:tc:dss:1.0:core:schema", "OptionalInputs")
            .item(0);
    DOMSignContext domSignContext = new DOMSignContext(key, parentElement);
    domSignContext.setDefaultNamespacePrefix("ds");
    // XMLDSigRI Websphere work-around
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    List<Transform> transforms = new LinkedList<Transform>();
    transforms.add(xmlSignatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(
            xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null));
    Reference reference = xmlSignatureFactory.newReference("",
            xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(SignatureMethod.HMAC_SHA1, null),
            Collections.singletonList(reference));

    Element securityTokenReferenceElement = getSecurityTokenReference(session);

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    DOMStructure securityTokenReferenceDOMStructure = new DOMStructure(securityTokenReferenceElement);
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(securityTokenReferenceDOMStructure));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
    xmlSignature.sign(domSignContext);
}
项目:juddi    文件:TckSigningUtil.java   
public static void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
    XMLSignatureFactory fac = initXMLSigFactory();
    X509Certificate cert = (X509Certificate) origCert;
    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    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(privateKey, node);
    dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ns2");

    // Create the XMLSignature, but don't sign it yet.
    try {
        SignedInfo si = initSignedInfo(fac);
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:juddi    文件:XmlSignatureApplet.java   
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
    XMLSignatureFactory fac = initXMLSigFactory();
    X509Certificate cert = (X509Certificate) origCert;
    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    //x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    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(privateKey, node);
    dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2");

    // Create the XMLSignature, but don't sign it yet.
    try {
        SignedInfo si = initSignedInfo(fac);
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:restcommander    文件:XML.java   
/**
 * Sign the XML document using xmldsig.
 * @param document the document to sign; it will be modified by the method.
 * @param publicKey the public key from the key pair to sign the document.
 * @param privateKey the private key from the key pair to sign the document.
 * @return the signed document for chaining.
 */
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();

    try {
        Reference ref =fac.newReference(
                "",
                fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null,
                null);
        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
                                                                        (C14NMethodParameterSpec) null),
                                          fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                                          Collections.singletonList(ref));
        DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement());
        KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
        KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue));
        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);
    } catch (Exception e) {
        Logger.warn("Error while signing an XML document.", e);
    }

    return document;
}
项目:secure-data-service    文件:XmlSignatureHelper.java   
/**
 * Signs the SAML assertion using the specified public and private keys.
 * 
 * @param document
 *            SAML assertion be signed.
 * @param privateKey
 *            Private key used to sign SAML assertion.
 * @param publicKey
 *            Public key used to sign SAML asserion.
 * @return w3c element representation of specified document.
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws KeyException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException {
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform(
            Transform.ENVELOPED, (TransformParameterSpec) null));
    Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            envelopedTransform, null, null);

    SignatureMethod signatureMethod = null;
    if (certificate.getPublicKey() instanceof DSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
    } else if (certificate.getPublicKey() instanceof RSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }

    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);

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

    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate));
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data));

    Element w3cElement = document.getDocumentElement();
    Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement);
    DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint);

    XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    signature.sign(dsc);
    return w3cElement;
}
项目:nfe    文件:AssinaturaDigital.java   
public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception {
    final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() : config.getCertificadoKeyStore().aliases().nextElement();
    final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray());
    final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection);
    final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    final List<Transform> transforms = new ArrayList<>(2);
    transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));

    final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
    final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    try (StringReader stringReader = new StringReader(conteudoXml)) {
        final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader));
        for (final String elementoAssinavel : elementosAssinaveis) {
            final NodeList elements = document.getElementsByTagName(elementoAssinavel);
            for (int i = 0; i < elements.getLength(); i++) {
                final Element element = (Element) elements.item(i);
                final String id = element.getAttribute("Id");
                element.setIdAttribute("Id", true);

                final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
                final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));

                final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
                signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
            }
        }
        return this.converteDocumentParaXml(document);
    }
}
项目:springboot-shiro-cas-mybatis    文件:AbstractSamlObjectBuilder.java   
/**
 * Sign SAML element.
 *
 * @param element the element
 * @param privKey the priv key
 * @param pubKey the pub key
 * @return the element
 */
private 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 XMLSignatureFactory sigFactory = XMLSignatureFactory
                .getInstance("DOM", (Provider) Class.forName(providerName)
                        .newInstance());

        final List<Transform> envelopedTransform = Collections
                .singletonList(sigFactory.newTransform(Transform.ENVELOPED,
                        (TransformParameterSpec) null));

        final Reference ref = sigFactory.newReference("", sigFactory
                        .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform,
                null, null);

        // Create the SignatureMethod based on the type of key
        final SignatureMethod signatureMethod;
        if (pubKey instanceof DSAPublicKey) {
            signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.DSA_SHA1, null);
        } else if (pubKey instanceof RSAPublicKey) {
            signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.RSA_SHA1, null);
        } else {
            throw new RuntimeException("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, Collections
                        .singletonList(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(Collections
                .singletonList(keyValuePair));
        // Convert the JDOM document to w3c (Java XML signature API requires
        // w3c representation)
        final org.w3c.dom.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 org.w3c.dom.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 RuntimeException("Error signing SAML element: "
                + e.getMessage(), e);
    }
}