Example usage for javax.xml.crypto.dsig DigestMethod SHA1

List of usage examples for javax.xml.crypto.dsig DigestMethod SHA1

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig DigestMethod SHA1.

Prototype

String SHA1

To view the source code for javax.xml.crypto.dsig DigestMethod SHA1.

Click Source Link

Document

The <a href="http://www.w3.org/2000/09/xmldsig#sha1"> SHA1</a> digest method algorithm URI.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair dsaKeyPair = kpg.generateKeyPair();

    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
    Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
            sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair dsaKeyPair = kpg.generateKeyPair();

    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
    Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
            sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo);
}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(//  w  ww .j  ava  2s. c  o m
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:Main.java

public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException,
        XMLSignatureException {//ww  w . j  a v  a2 s  .  c o  m

    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);

}

From source file:Main.java

private static Reference createReference(final String uri) throws SignatureException {
    try {//w  w w .  j a va 2 s  .c om
        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);
    }
}

From source file:edu.isi.misd.tagfiler.util.LocalFileChecksum.java

/**
 * Computes a checksum on a file, given the proper message digest
 * implementation// ww w .  j a  v a 2  s .c o  m
 * 
 * @param file
 *            file to read
 * @param messageDigest
 *            MessageDigest to use
 * @return the checksum bytes of the file
 * @thows FatalException if the checksum cannot be constructed.
 */
public static String computeFileChecksum(File file) throws FatalException {
    if (file == null)
        throw new IllegalArgumentException("file");

    String checksum = null;

    FileInputStream stream = null;
    try {
        stream = new FileInputStream(file);
        if (DigestMethod.SHA512.equals(digestType)) {
            checksum = DigestUtils.sha512Hex(stream);
        } else if (DigestMethod.SHA256.equals(digestType)) {
            checksum = DigestUtils.sha256Hex(stream);
        } else if (DigestMethod.SHA1.equals(digestType)) {
            checksum = DigestUtils.shaHex(stream);
        } else {
            checksum = DigestUtils.md5Hex(stream);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new FatalException(e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }
    return checksum;
}

From source file:gov.nih.nci.cacis.nav.DefaultDocumentReferenceValidator.java

/**
 * Default Constructor/*from  w w  w  . jav  a 2s .  com*/
 */
public DefaultDocumentReferenceValidator() {
    supportedAlgorithms.put(DigestMethod.SHA1, "SHA-1");
    supportedAlgorithms.put(DigestMethod.SHA256, "SHA-256");
    supportedAlgorithms.put(DigestMethod.SHA512, "SHA-512");
}

From source file:Main.java

/**
 * Firma digitalmente usando la forma "enveloped signature" seg&uacute;n el
 * est&aacute;ndar de la W3C (<a//from  w w  w.  j  a va2  s  .  c o  m
 * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>).
 * <p>
 * 
 * Este m&eacute;todo adem&aacute;s incorpora la informaci&oacute;n del
 * certificado a la secci&oacute;n &lt;KeyInfo&gt; opcional del
 * est&aacute;ndar, seg&uacute;n lo exige SII.
 * <p>
 * 
 * @param doc
 *            El documento a firmar
 * @param uri
 *            La referencia dentro del documento que debe ser firmada
 * @param pKey
 *            La llave privada para firmar
 * @param cert
 *            El certificado digital correspondiente a la llave privada
 * @throws NoSuchAlgorithmException
 *             Si el algoritmo de firma de la llave no est&aacute; soportado
 *             (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1).
 * @throws InvalidAlgorithmParameterException
 *             Si los algoritmos de canonizaci&oacute;n (parte del
 *             est&aacute;ndar XML Signature) no son soportados (actaulmente
 *             se usa el por defecto)
 * @throws KeyException
 *             Si hay problemas al incluir la llave p&uacute;blica en el
 *             &lt;KeyValue&gt;.
 * @throws MarshalException
 * @throws XMLSignatureException
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 */
public static void signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException {

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.

    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 by SII

    if ("DSA".equals(cert.getPublicKey().getAlgorithm()))
        method = SignatureMethod.DSA_SHA1;
    else if ("HMAC".equals(cert.getPublicKey().getAlgorithm()))
        method = SignatureMethod.HMAC_SHA1;

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

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

    // Create a KeyInfo and add the KeyValue to it
    List<XMLStructure> kidata = new ArrayList<XMLStructure>();
    kidata.add(kv);
    kidata.add(kif.newX509Data(Collections.singletonList(cert)));
    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(pKey, 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);

}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * .//from   www  .ja  v a 2s .c om
 * @param id ???
 * @param issuedAt (epoch??)
 * @param lifespan ?
 * @param issuer  Cell URL
 * @param subject URL
 * @param target URL
 * @param roleList 
 * @param schema ???
 */
public TransCellAccessToken(final String id, final long issuedAt, final long lifespan, final String issuer,
        final String subject, final String target, final List<Role> roleList, final String schema) {
    this.issuedAt = issuedAt;
    this.lifespan = lifespan;
    this.id = id;
    this.issuer = issuer;
    this.subject = subject;
    this.target = target;
    this.roleList = roleList;
    this.schema = schema;

    try {
        /*
         * creates the Reference object, which identifies the data that will be digested and signed. The Reference
         * object is assembled by creating and passing as parameters each of its components: the URI, the
         * DigestMethod, and a list of Transforms
         */
        DigestMethod digestMethod = xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null);
        Transform transform = xmlSignatureFactory.newTransform(Transform.ENVELOPED,
                (TransformParameterSpec) null);
        Reference reference = xmlSignatureFactory.newReference("", digestMethod,
                Collections.singletonList(transform), null, null);

        /*
         * creates the SignedInfo object that the signature is calculated over. Like the Reference object, the
         * SignedInfo object is assembled by creating and passing as parameters each of its components: the
         * CanonicalizationMethod, the SignatureMethod, and a list of References
         */
        CanonicalizationMethod c14nMethod = xmlSignatureFactory
                .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
        SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1,
                null);
        signedInfo = xmlSignatureFactory.newSignedInfo(c14nMethod, signatureMethod,
                Collections.singletonList(reference));
    } catch (NoSuchAlgorithmException e) {
        // ????????????
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        // ????????????
        throw new RuntimeException(e);
    }

}

From source file:be.e_contract.mycarenet.xkms.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);/*from   ww  w.j av a 2 s  .  c  o m*/

    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);
}