Example usage for java.security Key Key

List of usage examples for java.security Key Key

Introduction

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

Prototype

Key

Source Link

Usage

From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureNamespacePrefix = signatureElement.getPrefix();

    /*//  www. j av  a  2s  .co  m
     * Make sure we insert right after the ds:SignatureValue element, just
     * before the first ds:Object element.
     */
    Node nextSibling;
    NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
            "Object");
    if (0 == objectNodeList.getLength()) {
        nextSibling = null;
    } else {
        nextSibling = objectNodeList.item(0);
    }

    /*
     * Construct the ds:KeyInfo element using JSR 105.
     */
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());
    List<Object> x509DataObjects = new LinkedList<Object>();
    X509Certificate signingCertificate = signingCertificateChain.get(0);

    List<Object> keyInfoContent = new LinkedList<Object>();

    if (this.includeKeyValue) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }

    if (this.includeIssuerSerial) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(
                signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }

    if (this.includeEntireCertificateChain) {
        for (X509Certificate certificate : signingCertificateChain) {
            x509DataObjects.add(certificate);
        }
    } else {
        x509DataObjects.add(signingCertificate);
    }

    if (false == x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };

    XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement);
    DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext;
    try {
        domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext);
    } catch (MarshalException e) {
        throw new RuntimeException("marshall error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

@SuppressWarnings("unchecked")
private byte[] getXmlSignatureDigestValue(DigestAlgo digestAlgo, List<DigestInfo> digestInfos,
        List<X509Certificate> signingCertificateChain)
        throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerFactoryConfigurationError,
        TransformerException, IOException, SAXException {
    /*/* w w  w . jav  a 2  s.  co  m*/
     * DOM Document construction.
     */
    Document document = getEnvelopingDocument();
    if (null == document) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
    }

    /*
     * Signature context construction.
     */
    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };
    XMLSignContext xmlSignContext = new DOMSignContext(key, document);
    URIDereferencer uriDereferencer = getURIDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }

    if (null != this.signatureNamespacePrefix) {
        /*
         * OOo doesn't like ds namespaces so per default prefixing is off.
         */
        xmlSignContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS,
                this.signatureNamespacePrefix);
    }

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM",
            new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());

    /*
     * Add ds:References that come from signing client local files.
     */
    List<Reference> references = new LinkedList<Reference>();
    addDigestInfosAsReferences(digestInfos, signatureFactory, references);

    /*
     * Invoke the signature facets.
     */
    String localSignatureId;
    if (null == this.signatureId) {
        localSignatureId = "xmldsig-" + UUID.randomUUID().toString();
    } else {
        localSignatureId = this.signatureId;
    }
    List<XMLObject> objects = new LinkedList<XMLObject>();
    for (SignatureFacet signatureFacet : this.signatureFacets) {
        LOG.debug("invoking signature facet: " + signatureFacet.getClass().getSimpleName());
        signatureFacet.preSign(signatureFactory, document, localSignatureId, signingCertificateChain,
                references, objects);
    }

    /*
     * ds:SignedInfo
     */
    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    /*
     * JSR105 ds:Signature creation
     */
    String signatureValueId = localSignatureId + "-signature-value";
    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null,
            objects, localSignatureId, signatureValueId);

    /*
     * ds:Signature Marshalling.
     */
    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    Node documentNode = document.getDocumentElement();
    if (null == documentNode) {
        /*
         * In case of an empty DOM document.
         */
        documentNode = document;
    }
    domXmlSignature.marshal(documentNode, this.signatureNamespacePrefix, (DOMCryptoContext) xmlSignContext);

    /*
     * Completion of undigested ds:References in the ds:Manifests.
     */
    for (XMLObject object : objects) {
        LOG.debug("object java type: " + object.getClass().getName());
        List<XMLStructure> objectContentList = object.getContent();
        for (XMLStructure objectContent : objectContentList) {
            LOG.debug("object content java type: " + objectContent.getClass().getName());
            if (false == objectContent instanceof Manifest) {
                continue;
            }
            Manifest manifest = (Manifest) objectContent;
            List<Reference> manifestReferences = manifest.getReferences();
            for (Reference manifestReference : manifestReferences) {
                if (null != manifestReference.getDigestValue()) {
                    continue;
                }
                DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }

    /*
     * Completion of undigested ds:References.
     */
    List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (Reference signedInfoReference : signedInfoReferences) {
        DOMReference domReference = (DOMReference) signedInfoReference;
        if (null != domReference.getDigestValue()) {
            // ds:Reference with external digest value
            continue;
        }
        domReference.digest(xmlSignContext);
    }

    /*
     * Store the intermediate XML signature document.
     */
    TemporaryDataStorage temporaryDataStorage = getTemporaryDataStorage();
    OutputStream tempDocumentOutputStream = temporaryDataStorage.getTempOutputStream();
    writeDocument(document, tempDocumentOutputStream);
    temporaryDataStorage.setAttribute(SIGNATURE_ID_ATTRIBUTE, localSignatureId);

    /*
     * Calculation of XML signature digest value.
     */
    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    byte[] octets = dataStream.toByteArray();

    /*
     * TODO: we could be using DigestOutputStream here to optimize memory
     * usage.
     */

    MessageDigest jcaMessageDigest = MessageDigest.getInstance(digestAlgo.getAlgoId());
    byte[] digestValue = jcaMessageDigest.digest(octets);
    return digestValue;
}

From source file:test.be.fedict.eid.applet.model.XmlSignatureServiceBean.java

private byte[] getXmlSignatureDigestValue(String digestAlgo, List<DigestInfo> digestInfos,
        HttpSession httpSession) throws ParserConfigurationException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException,
        TransformerFactoryConfigurationError, TransformerException, MalformedURLException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }/*from w  ww . java 2s  . co  m*/

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };
    XMLSignContext signContext = new DOMSignContext(key, document);
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");

    List<Reference> references = new LinkedList<Reference>();
    for (DigestInfo digestInfo : digestInfos) {
        byte[] documentDigestValue = digestInfo.digestValue;

        DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo),
                null);

        String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile());

        Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null,
                documentDigestValue);
        references.add(reference);
    }

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod,
            signatureMethod, references);

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null);
    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    domXmlSignature.marshal(document, "ds", (DOMCryptoContext) signContext);

    Source source = new DOMSource(document);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xformer.transform(source, result);
    String documentStr = stringWriter.getBuffer().toString();
    httpSession.setAttribute("xmlDocument", documentStr);

    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(signContext, dataStream);
    byte[] octets = dataStream.toByteArray();

    MessageDigest jcaMessageDigest = MessageDigest.getInstance(digestAlgo);
    byte[] digestValue = jcaMessageDigest.digest(octets);
    return digestValue;
}