Search in sources :

Example 1 with SignatureAlgorithm

use of org.apache.xml.security.algorithms.SignatureAlgorithm in project santuario-java by apache.

the class CreateSignatureTest method testSHA256Digest.

@org.junit.Test
public void testSHA256Digest() throws Exception {
    PrivateKey privateKey = kp.getPrivate();
    Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));
    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
    sig.addKeyInfo(kp.getPublic());
    sig.sign(privateKey);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLUtils.outputDOMc14nWithComments(doc, bos);
    String signedContent = new String(bos.toByteArray());
    doVerify(signedContent);
}
Also used : PrivateKey(java.security.PrivateKey) XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document)

Example 2 with SignatureAlgorithm

use of org.apache.xml.security.algorithms.SignatureAlgorithm in project santuario-java by apache.

the class CreateSignatureTest method testCanonicalizedOctetStream.

@org.junit.Test
public void testCanonicalizedOctetStream() throws Exception {
    String signedXML = doSign();
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(signedXML.getBytes())) {
        doc = db.parse(is);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignature signature = new XMLSignature(sigElement, "");
    KeyInfo ki = signature.getKeyInfo();
    if (ki == null) {
        throw new RuntimeException("No keyinfo");
    }
    PublicKey pk = signature.getKeyInfo().getPublicKey();
    if (pk == null) {
        throw new RuntimeException("No public key");
    }
    SignedInfo si = signature.getSignedInfo();
    SignatureAlgorithm sa = si.getSignatureAlgorithm();
    sa.initVerify(pk);
    byte[] sigBytes = signature.getSignatureValue();
    byte[] canonicalizedBytes = si.getCanonicalizedOctetStream();
    sa.update(canonicalizedBytes, 0, canonicalizedBytes.length);
    assertTrue(sa.verify(sigBytes));
    assertTrue(si.verify(false));
}
Also used : XPath(javax.xml.xpath.XPath) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) Document(org.w3c.dom.Document) SignedInfo(org.apache.xml.security.signature.SignedInfo) XPathFactory(javax.xml.xpath.XPathFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyInfo(org.apache.xml.security.keys.KeyInfo) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 3 with SignatureAlgorithm

use of org.apache.xml.security.algorithms.SignatureAlgorithm in project santuario-java by apache.

the class XMLSignature method sign.

/**
 * Digests all References in the SignedInfo, calculates the signature value
 * and sets it in the SignatureValue Element.
 *
 * @param signingKey the {@link java.security.PrivateKey} or
 * {@link javax.crypto.SecretKey} that is used to sign.
 * @throws XMLSignatureException
 */
public void sign(Key signingKey) throws XMLSignatureException {
    if (signingKey instanceof PublicKey) {
        throw new IllegalArgumentException(I18n.translate("algorithms.operationOnlyVerification"));
    }
    // Create a SignatureAlgorithm object
    SignedInfo si = this.getSignedInfo();
    SignatureAlgorithm sa = si.getSignatureAlgorithm();
    try (SignerOutputStream output = new SignerOutputStream(sa);
        OutputStream so = new UnsyncBufferedOutputStream(output)) {
        // generate digest values for all References in this SignedInfo
        si.generateDigestValues();
        // initialize SignatureAlgorithm for signing
        sa.initSign(signingKey);
        // get the canonicalized bytes from SignedInfo
        si.signInOctetStream(so);
        // set them on the SignatureValue element
        this.setSignatureValueElement(sa.sign());
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException(ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    } catch (IOException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) PublicKey(java.security.PublicKey) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 4 with SignatureAlgorithm

use of org.apache.xml.security.algorithms.SignatureAlgorithm in project santuario-java by apache.

the class XMLSignature method checkSignatureValue.

/**
 * Verifies if the signature is valid by redigesting all References,
 * comparing those against the stored DigestValues and then checking to see
 * if the Signatures match on the SignedInfo.
 *
 * @param pk {@link java.security.PublicKey} part of the keypair or
 * {@link javax.crypto.SecretKey} that was used to sign
 * @return true if the signature is valid, false otherwise
 * @throws XMLSignatureException
 */
public boolean checkSignatureValue(Key pk) throws XMLSignatureException {
    // check to see if the key is not null
    if (pk == null) {
        Object[] exArgs = { "Didn't get a key" };
        throw new XMLSignatureException("empty", exArgs);
    }
    // References inside a Manifest.
    try {
        SignedInfo si = this.getSignedInfo();
        // create a SignatureAlgorithms from the SignatureMethod inside
        // SignedInfo. This is used to validate the signature.
        SignatureAlgorithm sa = si.getSignatureAlgorithm();
        LOG.debug("signatureMethodURI = {}", sa.getAlgorithmURI());
        LOG.debug("jceSigAlgorithm = {}", sa.getJCEAlgorithmString());
        LOG.debug("jceSigProvider = {}", sa.getJCEProviderName());
        LOG.debug("PublicKey = {}", pk);
        byte[] sigBytes = null;
        try (SignerOutputStream so = new SignerOutputStream(sa);
            OutputStream bos = new UnsyncBufferedOutputStream(so)) {
            sa.initVerify(pk);
            // Get the canonicalized (normalized) SignedInfo
            si.signInOctetStream(bos);
            // retrieve the byte[] from the stored signature
            sigBytes = this.getSignatureValue();
        } catch (IOException ex) {
            LOG.debug(ex.getMessage(), ex);
        // Impossible...
        } catch (XMLSecurityException ex) {
            throw ex;
        }
        // the bytes that were stored in the signature.
        if (!sa.verify(sigBytes)) {
            LOG.warn("Signature verification failed.");
            return false;
        }
        return si.verify(this.followManifestsDuringValidation);
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 5 with SignatureAlgorithm

use of org.apache.xml.security.algorithms.SignatureAlgorithm in project santuario-java by apache.

the class ECDSASignatureTest method doSign.

private byte[] doSign() throws Exception {
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("ECDSA", ECDSA_JKS_PASSWORD.toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));
    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    X509Certificate x509 = (X509Certificate) keyStore.getCertificate("ECDSA");
    sig.addKeyInfo(x509);
    sig.sign(privateKey);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return bos.toByteArray();
}
Also used : PrivateKey(java.security.PrivateKey) XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) ByteArrayOutputStream(java.io.ByteArrayOutputStream) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SignatureAlgorithm (org.apache.xml.security.algorithms.SignatureAlgorithm)8 PrivateKey (java.security.PrivateKey)5 XMLSignature (org.apache.xml.security.signature.XMLSignature)5 Document (org.w3c.dom.Document)5 Element (org.w3c.dom.Element)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Transforms (org.apache.xml.security.transforms.Transforms)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)3 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 OutputStream (java.io.OutputStream)2 PublicKey (java.security.PublicKey)2 X509Certificate (java.security.cert.X509Certificate)2 SignerOutputStream (org.apache.xml.security.utils.SignerOutputStream)2 UnsyncBufferedOutputStream (org.apache.xml.security.utils.UnsyncBufferedOutputStream)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 KeyStore (java.security.KeyStore)1 XPath (javax.xml.xpath.XPath)1 XPathFactory (javax.xml.xpath.XPathFactory)1