Example usage for java.security PublicKey getAlgorithm

List of usage examples for java.security PublicKey getAlgorithm

Introduction

In this page you can find the example usage for java.security PublicKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * @param  key  Key to write and read./*from   ww  w  .  j a  v a 2 s . c o m*/
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "functest", "util" }, dataProvider = "pubkeydata")
public void testReadWriteDerPublicKey(final PublicKey key) throws Exception {
    logger.info("Testing " + key.getAlgorithm() + " public key.");

    final File keyFile = new File(getKeyPath(key, "DER", null));
    keyFile.getParentFile().mkdir();
    CryptWriter.writeEncodedKey(key, keyFile);
    AssertJUnit.assertEquals(key, CryptReader.readPublicKey(keyFile));
}

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * @param  key  Key to write and read.//from  ww  w .j  ava 2  s .c o  m
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "functest", "util" }, dataProvider = "pubkeydata")
public void testReadWritePemPublicKey(final PublicKey key) throws Exception {
    logger.info("Testing " + key.getAlgorithm() + " public key.");

    final File keyFile = new File(getKeyPath(key, "PEM", null));
    keyFile.getParentFile().mkdir();
    CryptWriter.writePemKey(key, keyFile);
    AssertJUnit.assertEquals(key, CryptReader.readPublicKey(keyFile));
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the duplicated certificate mapped to the passed in cert, or
 * creates and returns one if no mapping has yet been performed.  If a naked public
 * key has already been mapped that matches the key in the cert, the already mapped
 * keypair will be reused for the mapped cert.
 * @param cert/*ww  w. j av  a2s  .  c o m*/
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)
        throws CertificateEncodingException, InvalidKeyException, CertificateException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        KeyStoreException, UnrecoverableKeyException {

    String thumbprint = ThumbprintUtil.getThumbprint(cert);

    String mappedCertThumbprint = _certMap.get(thumbprint);

    if (mappedCertThumbprint == null) {

        // Check if we've already mapped this public key from a KeyValue
        PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());
        PrivateKey privKey;

        if (mappedPk == null) {
            PublicKey pk = cert.getPublicKey();

            String algo = pk.getAlgorithm();

            KeyPair kp;

            if (algo.equals("RSA")) {
                kp = getRSAKeyPair();
            } else if (algo.equals("DSA")) {
                kp = getDSAKeyPair();
            } else {
                throw new InvalidKeyException("Key algorithm " + algo + " not supported.");
            }
            mappedPk = kp.getPublic();
            privKey = kp.getPrivate();

            mapPublicKeys(cert.getPublicKey(), mappedPk);
        } else {
            privKey = getPrivateKey(mappedPk);
        }

        X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk,
                getSigningCert(), getSigningPrivateKey());

        addCertAndPrivateKey(null, replacementCert, privKey);

        mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);

        _certMap.put(thumbprint, mappedCertThumbprint);
        _certMap.put(mappedCertThumbprint, thumbprint);
        _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);

        if (persistImmediately) {
            persist();
        }
        return replacementCert;
    }
    return getCertificateByAlias(mappedCertThumbprint);

}

From source file:com.springcryptoutils.core.key.PublicKeyRegistryByAliasImplTest.java

@Test
public void testPublicKeyRegistryIsProperlyLoaded() {
    assertNotNull(registryByAlias);//  ww w .java  2  s. c  o  m
    PublicKey publicKey1 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreOne";
        }
    }, new PublicKeyChooserByAlias() {
        public String getAlias() {
            return "test";
        }
    });
    PublicKey publicKey2 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreTwo";
        }
    }, new PublicKeyChooserByAlias() {
        public String getAlias() {
            return "test";
        }
    });
    assertNotNull(publicKey1);
    assertNotNull(publicKey2);
    assertEquals("algorithm", "RSA", publicKey1.getAlgorithm());
    assertEquals("algorithm", "RSA", publicKey2.getAlgorithm());
    assertSame(publicKey1, publicKey2);
}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureSAML.java

/**
 * Initialize a WSSec SAML Signature.//from w ww  .  ja va2  s  . c om
 * 
 * The method sets up and initializes a WSSec SAML Signature structure after
 * the relevant information was set. After setup of the references to
 * elements to sign may be added. After all references are added they can be
 * signed.
 * 
 * This method does not add the Signature element to the security header.
 * See <code>prependSignatureElementToHeader()</code> method.
 * 
 * @param doc
 *            The SOAP envelope as <code>Document</code>
 * @param uCrypto
 *            The user's Crypto instance
 * @param assertion
 *            the complete SAML assertion
 * @param iCrypto
 *            An instance of the Crypto API to handle keystore SAML token
 *            issuer and to generate certificates
 * @param iKeyName
 *            Private key to use in case of "sender-Vouches"
 * @param iKeyPW
 *            Password for issuer private key
 * @param secHeader
 *            The Security header
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto uCrypto, AssertionWrapper assertion, Crypto iCrypto, String iKeyName,
        String iKeyPW, WSSecHeader secHeader) throws WSSecurityException {

    if (doDebug) {
        log.debug("Beginning ST signing...");
    }

    userCrypto = uCrypto;
    issuerCrypto = iCrypto;
    document = doc;
    issuerKeyName = iKeyName;
    issuerKeyPW = iKeyPW;

    samlToken = assertion.toDOM(doc);

    //
    // Get some information about the SAML token content. This controls how
    // to deal with the whole stuff. First get the Authentication statement
    // (includes Subject), then get the _first_ confirmation method only
    // thats if "senderVouches" is true.
    //
    String confirmMethod = null;
    List<String> methods = assertion.getConfirmationMethods();
    if (methods != null && methods.size() > 0) {
        confirmMethod = methods.get(0);
    }
    if (OpenSAMLUtil.isMethodSenderVouches(confirmMethod)) {
        senderVouches = true;
    }
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    wsDocInfo = new WSDocInfo(doc);

    X509Certificate[] certs = null;
    PublicKey publicKey = null;

    if (senderVouches) {
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        cryptoType.setAlias(issuerKeyName);
        certs = issuerCrypto.getX509Certificates(cryptoType);
        wsDocInfo.setCrypto(issuerCrypto);
    }
    //
    // in case of key holder: - get the user's certificate that _must_ be
    // included in the SAML token. To ensure the cert integrity the SAML
    // token must be signed (by the issuer).
    //
    else {
        if (userCrypto == null || !assertion.isSigned()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                    new Object[] { "for SAML Signature (Key Holder)" });
        }
        if (secretKey == null) {
            RequestData data = new RequestData();
            data.setSigCrypto(userCrypto);
            data.setWssConfig(getWsConfig());
            SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo,
                    getWsConfig().isWsiBSPCompliant());
            publicKey = samlKeyInfo.getPublicKey();
            certs = samlKeyInfo.getCerts();
            wsDocInfo.setCrypto(userCrypto);
        }
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null && secretKey == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                new Object[] { "SAML signature" });
    }

    if (sigAlgo == null) {
        PublicKey key = null;
        if (certs != null && certs[0] != null) {
            key = certs[0].getPublicKey();
        } else if (publicKey != null) {
            key = publicKey;
        }

        String pubKeyAlgo = key.getAlgorithm();
        log.debug("automatic sig algo detection: " + pubKeyAlgo);
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = WSConstants.DSA;
        } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) {
            sigAlgo = WSConstants.RSA;
        } else {
            throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm",
                    new Object[] { pubKeyAlgo });
        }
    }
    sig = null;

    try {
        C14NMethodParameterSpec c14nSpec = null;
        if (getWsConfig().isWsiBSPCompliant() && canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
            List<String> prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            c14nSpec = new ExcC14NParameterSpec(prefixes);
        }

        c14nMethod = signatureFactory.newCanonicalizationMethod(canonAlgo, c14nSpec);
    } catch (Exception ex) {
        log.error("", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    keyInfoUri = getWsConfig().getIdAllocator().createSecureId("KeyId-", keyInfo);
    secRef = new SecurityTokenReference(doc);
    strUri = getWsConfig().getIdAllocator().createSecureId("STRId-", secRef);
    secRef.setID(strUri);

    if (certs != null && certs.length != 0) {

        // __MOD__ 2012-01-15

        if (certUri == null)
            certUri = getWsConfig().getIdAllocator().createSecureId("CertId-", certs[0]);
    }

    //
    // If the sender vouches, then we must sign the SAML token _and_ at
    // least one part of the message (usually the SOAP body). To do so we
    // need to - put in a reference to the SAML token. Thus we create a STR
    // and insert it into the wsse:Security header - set a reference of the
    // created STR to the signature and use STR Transform during the
    // signature
    //
    try {
        if (senderVouches) {
            secRefSaml = new SecurityTokenReference(doc);
            secRefID = getWsConfig().getIdAllocator().createSecureId("STRSAMLId-", secRefSaml);
            secRefSaml.setID(secRefID);

            if (useDirectReferenceToAssertion) {
                Reference ref = new Reference(doc);
                ref.setURI("#" + assertion.getId());
                if (assertion.getSaml1() != null) {
                    ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                secRefSaml.setReference(ref);
            } else {
                Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
                String valueType = null;
                if (assertion.getSaml1() != null) {
                    valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                keyId.setAttributeNS(null, "ValueType", valueType);
                keyId.appendChild(doc.createTextNode(assertion.getId()));
                Element elem = secRefSaml.getElement();
                elem.appendChild(keyId);
            }
            wsDocInfo.addTokenElement(secRefSaml.getElement(), false);
        }
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    if (senderVouches) {
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(doc);
            ref.setURI("#" + certUri);
            bstToken = new X509Security(doc);
            ((X509Security) bstToken).setX509Certificate(certs[0]);
            bstToken.setID(certUri);
            wsDocInfo.addTokenElement(bstToken.getElement(), false);
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            break;

        case WSConstants.X509_KEY_IDENTIFIER:
            secRef.setKeyIdentifier(certs[0]);
            break;

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], iCrypto != null ? iCrypto : uCrypto);
            break;

        case WSConstants.THUMBPRINT_IDENTIFIER:
            secRef.setKeyIdentifierThumb(certs[0]);
            break;

        case WSConstants.ISSUER_SERIAL:
            final String issuer = certs[0].getIssuerDN().getName();
            final java.math.BigInteger serialNumber = certs[0].getSerialNumber();
            final DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(document, issuer, serialNumber);
            final DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
            secRef.setX509Data(domX509Data);
            break;

        default:
            throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId", new Object[] {});
        }
    } else if (useDirectReferenceToAssertion) {
        Reference ref = new Reference(doc);
        ref.setURI("#" + assertion.getId());
        if (assertion.getSaml1() != null) {
            ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        secRef.setReference(ref);
    } else {
        Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
        String valueType = null;
        if (assertion.getSaml1() != null) {
            valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        keyId.setAttributeNS(null, "ValueType", valueType);
        keyId.appendChild(doc.createTextNode(assertion.getId()));
        Element elem = secRef.getElement();
        elem.appendChild(keyId);
    }
    XMLStructure structure = new DOMStructure(secRef.getElement());
    wsDocInfo.addTokenElement(secRef.getElement(), false);

    keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri);

    wsDocInfo.addTokenElement(samlToken, false);
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static PrivateKey unwrap(CryptoToken token, PublicKey pubKey, boolean temporary,
        SymmetricKey wrappingKey, byte[] wrappedData, KeyWrapAlgorithm wrapAlgorithm, IVParameterSpec wrapIV)
        throws Exception {
    KeyWrapper wrapper = token.getKeyWrapper(wrapAlgorithm);
    wrapper.initUnwrap(wrappingKey, wrapIV);

    // Get the key type for unwrapping the private key.
    PrivateKey.Type keyType = null;
    if (pubKey.getAlgorithm().equalsIgnoreCase("RSA")) {
        keyType = PrivateKey.RSA;
    } else if (pubKey.getAlgorithm().equalsIgnoreCase("DSA")) {
        keyType = PrivateKey.DSA;
    } else if (pubKey.getAlgorithm().equalsIgnoreCase("EC")) {
        keyType = PrivateKey.EC;/*from ww  w  . j a  va 2 s  .c  o  m*/
    }

    PrivateKey pk = null;
    if (temporary) {
        pk = wrapper.unwrapTemporaryPrivate(wrappedData, keyType, pubKey);
    } else {
        pk = wrapper.unwrapPrivate(wrappedData, keyType, pubKey);
    }
    return pk;
}

From source file:netscape.security.pkcs.PKCS12Util.java

public PrivateKey.Type getPrivateKeyType(PublicKey publicKey) {
    if (publicKey.getAlgorithm().equals("EC")) {
        return PrivateKey.Type.EC;
    }/*from  w w w .  ja va2s  .co  m*/
    return PrivateKey.Type.RSA;
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateKeys(PublicKey pubKey, PrivateKey privKey) {

    if (pubKey.getAlgorithm() != privKey.getAlgorithm())
        throw new IllegalArgumentException("Public and private key have different algorithms");

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA")
        return;/*from  w w w  .ja  v a  2  s.  c  o m*/

    try {

        String data = "ENCRYPT_DATA";
        SecureRandom random = new SecureRandom();
        Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
        byte[] encryptedData = cipher.doFinal(data.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
        String decreptedData = new String(cipher.doFinal(encryptedData));
        if (!decreptedData.equals(data))
            throw new IllegalArgumentException("Bad public-private key");

    } catch (BadPaddingException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("Invalid public-private key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid algorithm for public-private key", e);
    }
}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private void validateKeys(final PublicKey pubKey, final PrivateKey privKey) {
    Preconditions.checkNotNull(pubKey);//w w  w  .j  a v a  2  s .c o m
    Preconditions.checkNotNull(privKey);

    if (!pubKey.getAlgorithm().equals(privKey.getAlgorithm())) {
        throw new IllegalArgumentException("Public and private key have different algorithms");
    }

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA") {
        return;
    }

    try {
        final String data = "ENCRYPT_DATA";
        final SecureRandom random = new SecureRandom();
        final Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
        final byte[] encryptedData = cipher.doFinal(data.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
        final String decreptedData = new String(cipher.doFinal(encryptedData));
        if (!decreptedData.equals(data)) {
            throw new IllegalStateException("Bad public-private key");
        }

    } catch (final BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | NoSuchPaddingException e) {
        throw new IllegalStateException("Bad public-private key", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid algorithm for public-private key", e);
    }
}

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

/**
 * Initialize a WSSec Signature./*from w  w  w .  ja  v  a 2s . co m*/
 * 
 * The method sets up and initializes a WSSec Signature structure after the
 * relevant information was set. After setup of the references to elements
 * to sign may be added. After all references are added they can be signed.
 * 
 * This method does not add the Signature element to the security header.
 * See <code>prependSignatureElementToHeader()</code> method.
 * 
 * @param doc The SOAP envelope as <code>Document</code>
 * @param cr An instance of the Crypto API to handle keystore and certificates
 * @param secHeader The security header that will hold the Signature. This is used
 *                   to construct namespace prefixes for Signature. This method
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto cr, WSSecHeader secHeader) throws WSSecurityException {
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    crypto = cr;
    document = doc;
    wsDocInfo = new WSDocInfo(doc);
    wsDocInfo.setCrypto(cr);

    //
    // At first get the security token (certificate) according to the
    // parameters.
    //
    X509Certificate[] certs = null;
    if (keyIdentifierType != WSConstants.UT_SIGNING && keyIdentifierType != WSConstants.CUSTOM_SYMM_SIGNING
            && keyIdentifierType != WSConstants.CUSTOM_SYMM_SIGNING_DIRECT
            && keyIdentifierType != WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER
            && keyIdentifierType != WSConstants.CUSTOM_KEY_IDENTIFIER) {
        if (useThisCert == null) {
            certs = crypto.getCertificates(user);
        } else {
            certs = new X509Certificate[] { useThisCert };
        }
        if (certs == null || certs.length <= 0) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound",
                    new Object[] { user, "signature" });
        }
        certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]);
        //
        // If no signature algorithm was set try to detect it according to the
        // data stored in the certificate.
        //
        if (sigAlgo == null) {
            String pubKeyAlgo = certs[0].getPublicKey().getAlgorithm();
            log.debug("automatic sig algo detection: " + pubKeyAlgo);
            if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
                sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
            } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) {
                sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
            } else {
                throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm",
                        new Object[] { pubKeyAlgo });
            }
        }
    }

    //
    // Get an initialized XMLSignature element.
    //
    if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
        Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
        canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo);

        if (wssConfig.isWsiBSPCompliant()) {
            Set prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes);
            canonElem.appendChild(inclusiveNamespaces.getElement());
        }

        try {
            SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo);
            sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
        } catch (XMLSecurityException e) {
            log.error("", e);
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e);
        }
    } else {
        try {
            sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
        } catch (XMLSecurityException e) {
            log.error("", e);
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e);
        }
    }

    EnvelopeIdResolver resolver = (EnvelopeIdResolver) EnvelopeIdResolver.getInstance();
    resolver.setWsDocInfo(wsDocInfo);
    sig.addResourceResolver(resolver);
    sig.setId(wssConfig.getIdAllocator().createId("Signature-", sig));

    keyInfo = sig.getKeyInfo();
    keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", keyInfo);
    keyInfo.setId(keyInfoUri);

    secRef = new SecurityTokenReference(doc);
    strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef);
    secRef.setID(strUri);

    //
    // Prepare and setup the token references for this Signature
    //
    switch (keyIdentifierType) {
    case WSConstants.BST_DIRECT_REFERENCE:
        Reference ref = new Reference(document);
        ref.setURI("#" + certUri);
        if (!useSingleCert) {
            bstToken = new PKIPathSecurity(document);
            ((PKIPathSecurity) bstToken).setX509Certificates(certs, false, crypto);
        } else {
            bstToken = new X509Security(document);
            ((X509Security) bstToken).setX509Certificate(certs[0]);
        }
        ref.setValueType(bstToken.getValueType());
        secRef.setReference(ref);
        bstToken.setID(certUri);
        wsDocInfo.setBst(bstToken.getElement());
        break;
    case WSConstants.EMBED_SECURITY_TOKEN_REF:
        XMLX509Certificate cert = null;
        XMLX509SubjectName subject = null;
        try {
            cert = new XMLX509Certificate(document, certs[0]);
        } catch (XMLSecurityException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "");
        }
        subject = new XMLX509SubjectName(doc, certs[0]);

        X509Data x509KeyVal = new X509Data(document);
        x509KeyVal.add(subject);
        x509KeyVal.add(cert);
        keyInfo.add(x509KeyVal);
        break;
    case WSConstants.ISSUER_SERIAL:
        XMLX509IssuerSerial data = new XMLX509IssuerSerial(document, certs[0]);
        X509Data x509Data = new X509Data(document);
        x509Data.add(data);
        secRef.setX509IssuerSerial(x509Data);
        break;
    case WSConstants.X509_KEY_IDENTIFIER:
        secRef.setKeyIdentifier(certs[0]);
        break;

    case WSConstants.SKI_KEY_IDENTIFIER:
        secRef.setKeyIdentifierSKI(certs[0], crypto);
        break;

    case WSConstants.UT_SIGNING:
        Reference refUt = new Reference(document);
        refUt.setValueType(WSConstants.USERNAMETOKEN_NS + "#UsernameToken");
        String utId = usernameToken.getId();
        refUt.setURI("#" + utId);
        secRef.setReference(refUt);
        secretKey = usernameToken.getSecretKey();
        break;

    case WSConstants.THUMBPRINT_IDENTIFIER:
        secRef.setKeyIdentifierThumb(certs[0]);
        break;

    case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
        if (encrKeySha1value != null) {
            secRef.setKeyIdentifierEncKeySHA1(encrKeySha1value);
        } else {
            secRef.setKeyIdentifierEncKeySHA1(getSHA1(secretKey));
        }
        break;

    case WSConstants.CUSTOM_SYMM_SIGNING:

        if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)
                || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
            secRef.setKeyIdentifier(customTokenValueType, customTokenId);
        } else {
            Reference refCust = new Reference(document);
            refCust.setValueType(customTokenValueType);
            refCust.setURI((new StringBuilder()).append("#").append(customTokenId).toString());
            secRef.setReference(refCust);
        }
        break;

    case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT:
        Reference refCustd = new Reference(document);
        refCustd.setValueType(this.customTokenValueType);
        refCustd.setURI(this.customTokenId);
        secRef.setReference(refCustd);
        break;
    case WSConstants.CUSTOM_KEY_IDENTIFIER:
        secRef.setKeyIdentifier(customTokenValueType, customTokenId);
        break;
    case WSConstants.KEY_VALUE:
        java.security.PublicKey publicKey = certs[0].getPublicKey();
        String pubKeyAlgo = publicKey.getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            DSAKeyValue dsaKeyValue = new DSAKeyValue(document, publicKey);
            keyInfo.add(dsaKeyValue);
        } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) {
            RSAKeyValue rsaKeyValue = new RSAKeyValue(document, publicKey);
            keyInfo.add(rsaKeyValue);
        } else {
            throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm",
                    new Object[] { pubKeyAlgo });
        }
        break;
    default:
        throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
    }

    if (keyIdentifierType != WSConstants.KEY_VALUE
            && keyIdentifierType != WSConstants.EMBED_SECURITY_TOKEN_REF) {
        keyInfo.addUnknownElement(secRef.getElement());
        wsDocInfo.setSecurityTokenReference(secRef.getElement());
    }
}