Example usage for javax.xml.crypto.dsig SignatureMethod HMAC_SHA1

List of usage examples for javax.xml.crypto.dsig SignatureMethod HMAC_SHA1

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig SignatureMethod HMAC_SHA1.

Prototype

String HMAC_SHA1

To view the source code for javax.xml.crypto.dsig SignatureMethod HMAC_SHA1.

Click Source Link

Document

The <a href="http://www.w3.org/2000/09/xmldsig#hmac-sha1">HMAC-SHA1</a> MAC signature method algorithm URI

Usage

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 av  a  2 s  .c om*/
 * 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:be.agiv.security.handler.WSSecurityHandler.java

private void addProofOfPossessionSignature(SOAPMessageContext context, SOAPMessage soapMessage,
        SOAPPart soapPart, WSSecHeader wsSecHeader, WSSecTimestamp wsSecTimeStamp)
        throws SOAPException, IOException, WSSecurityException {
    if (null == this.key) {
        return;/*from  w  ww. j  a  v  a  2 s.  c  o m*/
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    LOG.debug("SOAP message before signing: " + new String(outputStream.toByteArray()));
    Vector<WSEncryptionPart> signParts = new Vector<WSEncryptionPart>();
    signParts.add(new WSEncryptionPart(wsSecTimeStamp.getId()));

    LOG.debug("token identifier: " + this.tokenIdentifier);

    WSSConfig wssConfig = new WSSConfig();
    WSSecSignature sign = new WSSecSignature(wssConfig);
    if (this.samlReference) {
        sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        sign.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
    } else {
        sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    }
    sign.setSecretKey(this.key);
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
    sign.setCustomTokenId(this.tokenIdentifier);
    sign.prepare(soapPart, null, wsSecHeader);
    sign.setParts(signParts);
    List<Reference> referenceList = sign.addReferencesToSign(signParts, wsSecHeader);
    sign.computeSignature(referenceList, false, null);
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java

static SignatureMethod unmarshal(Element smElem) throws MarshalException {
    String alg = DOMUtils.getAttributeValue(smElem, "Algorithm");
    if (alg.equals(SignatureMethod.RSA_SHA1)) {
        return new SHA1withRSA(smElem);
    } else if (alg.equals(RSA_SHA256)) {
        return new SHA256withRSA(smElem);
    } else if (alg.equals(RSA_SHA384)) {
        return new SHA384withRSA(smElem);
    } else if (alg.equals(RSA_SHA512)) {
        return new SHA512withRSA(smElem);
    } else if (alg.equals(SignatureMethod.DSA_SHA1)) {
        return new SHA1withDSA(smElem);
    } else if (alg.equals(ECDSA_SHA1)) {
        return new SHA1withECDSA(smElem);
    } else if (alg.equals(ECDSA_SHA256)) {
        return new SHA256withECDSA(smElem);
    } else if (alg.equals(ECDSA_SHA384)) {
        return new SHA384withECDSA(smElem);
    } else if (alg.equals(ECDSA_SHA512)) {
        return new SHA512withECDSA(smElem);
    } else if (alg.equals(SignatureMethod.HMAC_SHA1)) {
        return new DOMHMACSignatureMethod.SHA1(smElem);
    } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
        return new DOMHMACSignatureMethod.SHA256(smElem);
    } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
        return new DOMHMACSignatureMethod.SHA384(smElem);
    } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
        return new DOMHMACSignatureMethod.SHA512(smElem);
    } else if (alg.equals(GOSTR34102001_GOSTR3411)) {
        return new GOST3411withGOST3410(smElem);
    } else if (alg.equals(GOSTR34102001_GOSTR3411URN)) {
        return new GOST3411withGOST3410URN(smElem);
    } else {/*  w  w  w.  java2s  .c  o  m*/
        throw new MarshalException("unsupported SignatureMethod algorithm: " + alg);
    }
}

From source file:org.apache.ws.security.message.SecurityContextTokenTest.java

/**
 * Test signature and verification using a SecurityContextToken directly,
 * rather than using a DerivedKeyToken to point to a SecurityContextToken.
 * See WSS-216 - https://issues.apache.org/jira/browse/WSS-216
 *///ww w .j a  v  a2  s . c o  m
@org.junit.Test
public void testSCTSign() {
    try {
        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
        sctBuilder.prepare(doc, crypto);

        byte[] tempSecret = WSSecurityUtil.generateNonce(16);

        // Store the secret
        callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);

        String tokenId = sctBuilder.getSctId();

        WSSecSignature builder = new WSSecSignature();
        builder.setSecretKey(tempSecret);
        builder.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        builder.setCustomTokenValueType(WSConstants.WSC_SCT);
        builder.setCustomTokenId(tokenId);
        builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
        builder.build(doc, crypto, secHeader);

        sctBuilder.prependSCTElementToHeader(doc, secHeader);

        if (LOG.isDebugEnabled()) {
            LOG.debug("SCT sign");
            String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
            LOG.debug(outputString);
        }

        verify(doc);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.apache.ws.security.message.SignatureAlgorithmSuiteTest.java

@org.junit.Test
public void testSymmetricKey() throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);/*from w  w  w .j  ava 2  s .  c  om*/
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    WSSecSignature builder = new WSSecSignature();
    builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    builder.setSecretKey(keyData);
    builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document signedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
    String identifier = Base64.encode(encodedBytes);
    SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
    secretKeyCallbackHandler.addSecretKey(identifier, keyData);

    Element securityHeader = WSSecurityUtil.getSecurityHeader(signedDoc, null);
    AlgorithmSuite algorithmSuite = createAlgorithmSuite();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    RequestData data = new RequestData();
    data.setSigCrypto(crypto);
    data.setCallbackHandler(secretKeyCallbackHandler);
    data.setAlgorithmSuite(algorithmSuite);

    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as HMAC-SHA1 is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.addSignatureMethod(WSConstants.HMAC_SHA1);
    secEngine.processSecurityHeader(securityHeader, data);

    algorithmSuite.setMinimumSymmetricKeyLength(256);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.setMinimumSymmetricKeyLength(64);
    algorithmSuite.setMaximumSymmetricKeyLength(120);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }
}

From source file:org.apache.ws.security.message.SignatureEncryptionTest.java

/**
 * Test signature created using an encrypted key
 * SOAP Body is signed and encrypted. In the encryption, The ReferenceList element is 
 * put into the Encrypted Key, as a child of the EncryptedKey. Signature is created 
 * using the encrypted key. //from  ww  w  .  ja va2s.co m
 */
@org.junit.Test
public void testEncryptedKeySignature() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    LOG.info("Before Sign/Encryption....");

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
    encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    encrKey.setUserInfo("wss40", "security");
    encrKey.setSymmetricEncAlgorithm(WSConstants.AES_192);
    encrKey.prepare(doc, crypto);

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setEncKeyId(encrKey.getId());
    encrypt.setEphemeralKey(encrKey.getEphemeralKey());
    encrypt.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    encrypt.setEncryptSymmKey(false);
    encrypt.setEncryptedKeyElement(encrKey.getEncryptedKeyElement());

    WSSecSignature sign = new WSSecSignature();
    sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    sign.setCustomTokenId(encrKey.getId());
    sign.setSecretKey(encrKey.getEphemeralKey());
    sign.setCustomTokenValueType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document signedDoc = sign.build(doc, crypto, secHeader);
    Document encryptedSignedDoc = encrypt.build(signedDoc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Signed and encrypted message with IssuerSerial key identifier (both), 3DES:");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedSignedDoc);
        LOG.debug(outputString);
    }

    LOG.info("After Sign/Encryption....");
    verify(encryptedSignedDoc);
}

From source file:org.apache.ws.security.message.SymmetricSignatureTest.java

/**
 * Test signing a message body using a symmetric key with EncryptedKeySHA1
 *//*from   ww  w  .  ja  v a  2s . c o  m*/
@org.junit.Test
public void testSymmetricSignatureSHA1() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecSignature sign = new WSSecSignature();
    sign.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    sign.setSecretKey(keyData);
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document signedDoc = sign.build(doc, crypto, secHeader);

    byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
    String identifier = Base64.encode(encodedBytes);
    secretKeyCallbackHandler.addSecretKey(identifier, keyData);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Signed symmetric message SHA1:");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    secEngine.processSecurityHeader(doc, null, secretKeyCallbackHandler, null, crypto);
}

From source file:org.apache.ws.security.message.SymmetricSignatureTest.java

/**
 * Test signing a message body using a symmetric key with Direct Reference to an
 * EncryptedKey//from  www.  j  ava2  s.  co  m
 */
@org.junit.Test
public void testSymmetricSignatureDR() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
    encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    encrKey.setUserInfo("wss40", "security");
    encrKey.setSymmetricEncAlgorithm(WSConstants.AES_192);
    encrKey.prepare(doc, crypto);

    WSSecSignature sign = new WSSecSignature();
    sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    sign.setCustomTokenId(encrKey.getId());
    sign.setSecretKey(encrKey.getEphemeralKey());
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
    sign.setCustomTokenValueType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);

    Document signedDoc = sign.build(doc, crypto, secHeader);
    encrKey.prependToHeader(secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Signed symmetric message DR:");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    verify(signedDoc);
}

From source file:org.apache.ws.security.message.SymmetricSignatureTest.java

/**
 * Test that first signs, then encrypts a WS-Security envelope.
 * <p/>//from  w  ww . jav  a  2  s.  co m
 * 
 * @throws Exception Thrown when there is any problem in signing, encryption,
 *                   decryption, or verification
 */
@org.junit.Test
public void testEncryptedKeySignature() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    LOG.info("Before Sign/Encryption....");

    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
    encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    encrKey.setUserInfo("wss40", "security");
    encrKey.setSymmetricEncAlgorithm(WSConstants.AES_192);
    encrKey.prepare(doc, crypto);

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setEncKeyId(encrKey.getId());
    encrypt.setEphemeralKey(encrKey.getEphemeralKey());
    encrypt.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    encrypt.setEncryptSymmKey(false);
    encrypt.setEncryptedKeyElement(encrKey.getEncryptedKeyElement());

    WSSecSignature sign = new WSSecSignature();
    sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    sign.setCustomTokenId(encrKey.getId());
    sign.setCustomTokenValueType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
    sign.setSecretKey(encrKey.getEphemeralKey());
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document signedDoc = sign.build(doc, crypto, secHeader);
    Document encryptedSignedDoc = encrypt.build(signedDoc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Signed and encrypted message with IssuerSerial key identifier (both), 3DES:");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedSignedDoc);
        LOG.debug(outputString);
    }

    LOG.info("After Sign/Encryption....");
    verify(encryptedSignedDoc);
}

From source file:org.apache.ws.security.message.SymmetricSignatureTest.java

/**
 * Test signing a message body using a symmetric key with EncryptedKeySHA1. 
 * The request is generated using WSHandler, instead of coding it.
 *///w  ww.  j a va  2  s. c  o  m
@org.junit.Test
public void testSymmetricSignatureSHA1Handler() throws Exception {
    final WSSConfig cfg = WSSConfig.getNewInstance();
    RequestData reqData = new RequestData();
    reqData.setWssConfig(cfg);
    java.util.Map<String, Object> messageContext = new java.util.TreeMap<String, Object>();
    messageContext.put(WSHandlerConstants.SIG_KEY_ID, "EncryptedKeySHA1");
    messageContext.put(WSHandlerConstants.SIG_ALGO, SignatureMethod.HMAC_SHA1);
    messageContext.put(WSHandlerConstants.PW_CALLBACK_REF, this);
    reqData.setMsgContext(messageContext);
    reqData.setUsername("");

    final java.util.List<Integer> actions = new java.util.ArrayList<Integer>();
    actions.add(Integer.valueOf(WSConstants.SIGN));
    final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    CustomHandler handler = new CustomHandler();
    handler.send(WSConstants.SIGN, doc, reqData, actions, true);

    String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
    if (LOG.isDebugEnabled()) {
        LOG.debug(outputString);
    }

    reqData = new RequestData();
    reqData.setWssConfig(WSSConfig.getNewInstance());
    messageContext = new java.util.TreeMap<String, Object>();
    messageContext.put(WSHandlerConstants.PW_CALLBACK_REF, this);
    reqData.setMsgContext(messageContext);
    reqData.setUsername("");

    handler.receive(WSConstants.SIGN, reqData);

    secEngine.processSecurityHeader(doc, null, this, null, crypto);
}