Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dsig.*;

import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;

import java.security.SignatureException;

import java.util.ArrayList;
import java.util.Collections;

import java.util.List;

public class Main {
    private static SignedInfo createSignedInfo(final String algorithm,
            final SignatureMethodParameterSpec methodParamSpec, final String signatureId, final String referenceUri)
            throws SignatureException {
        try {
            final CanonicalizationMethod canonicalizationMethod = getXMLSignatureFactory()
                    .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (XMLStructure) null);
            final SignatureMethod signatureMethod = getXMLSignatureFactory().newSignatureMethod(algorithm,
                    methodParamSpec);
            return getXMLSignatureFactory().newSignedInfo(canonicalizationMethod, signatureMethod,
                    Collections.singletonList(createReference(referenceUri)), signatureId);
        } catch (final Exception e) {
            throw new SignatureException("Error creating signed info", e);
        }
    }

    private static synchronized XMLSignatureFactory getXMLSignatureFactory() {
        return XMLSignatureFactory.getInstance("DOM");
    }

    private static Reference createReference(final String uri) throws SignatureException {
        try {
            final List<Transform> transforms = new ArrayList<>();
            transforms
                    .add(getXMLSignatureFactory().newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
            transforms.add(getXMLSignatureFactory().newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (XMLStructure) null));
            final DigestMethod digestMethod = getXMLSignatureFactory().newDigestMethod(DigestMethod.SHA1, null);
            String referenceUri = "";
            if (uri != null) {
                referenceUri = uri;
            }
            return getXMLSignatureFactory().newReference(referenceUri, digestMethod, transforms, null, null);
        } catch (final Exception e) {
            throw new SignatureException("Error creating reference", e);
        }
    }
}