Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Node;

import javax.xml.crypto.*;

import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;

import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;

import java.security.*;

import java.util.*;

public class Main {
    public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey)
            throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException,
            XMLSignatureException {

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

        Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null, null);

        // Create the SignedInfo
        String method = SignatureMethod.RSA_SHA1; // default

        if ("DSA".equals(privKey.getAlgorithm()))
            method = SignatureMethod.DSA_SHA1;

        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical
                (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null),
                Collections.singletonList(ref));

        KeyInfoFactory kif = fac.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(pubKey);

        // Create a KeyInfo and add the KeyValue to it
        List<XMLStructure> kidata = new ArrayList<XMLStructure>();
        kidata.add(kv);
        KeyInfo ki = kif.newKeyInfo(kidata);

        // Create a DOMSignContext and specify the PrivateKey and
        // location of the resulting XMLSignature's parent element
        DOMSignContext dsc = new DOMSignContext(privKey, doc);

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

        // Marshal, generate (and sign) the enveloped signature
        signature.sign(dsc);

    }
}