|
Java example source code file (XMLSignature.java)
The XMLSignature.java Java example source code/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.sun.org.apache.xml.internal.security.signature; import java.io.IOException; import java.io.OutputStream; import java.security.Key; import java.security.PublicKey; import java.security.cert.X509Certificate; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /** * Handles <code><ds:Signature> elements. * This is the main class that deals with creating and verifying signatures. * * <p>There are 2 types of constructors for this class. The ones that take a * document, baseURI and 1 or more Java Objects. This is mostly used for * signing purposes. * The other constructor is the one that takes a DOM Element and a baseURI. * This is used mostly with for verifying, when you have a SignatureElement. * * There are a few different types of methods: * <ul> th element exists.
*
* @param i
* @return the <code>ith element exists.
*/
public ObjectContainer getObjectItem(int i) {
Element objElem =
XMLUtils.selectDsNode(
this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i
);
try {
return new ObjectContainer(objElem, this.baseURI);
} catch (XMLSecurityException ex) {
return null;
}
}
/**
* Returns the number of all <code>ds:Object elements.
*
* @return the number of all <code>ds:Object elements.
*/
public int getObjectLength() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
}
/**
* 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")
);
}
try {
//Create a SignatureAlgorithm object
SignedInfo si = this.getSignedInfo();
SignatureAlgorithm sa = si.getSignatureAlgorithm();
OutputStream so = null;
try {
// initialize SignatureAlgorithm for signing
sa.initSign(signingKey);
// generate digest values for all References in this SignedInfo
si.generateDigestValues();
so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa));
// get the canonicalized bytes from SignedInfo
si.signInOctetStream(so);
} catch (XMLSecurityException ex) {
throw ex;
} finally {
if (so != null) {
try {
so.close();
} catch (IOException ex) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
}
}
}
}
// set them on the SignatureValue element
this.setSignatureValueElement(sa.sign());
} catch (XMLSignatureException ex) {
throw ex;
} catch (CanonicalizationException ex) {
throw new XMLSignatureException("empty", ex);
} catch (InvalidCanonicalizerException ex) {
throw new XMLSignatureException("empty", ex);
} catch (XMLSecurityException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Adds a {@link ResourceResolver} to enable the retrieval of resources.
*
* @param resolver
*/
public void addResourceResolver(ResourceResolver resolver) {
this.getSignedInfo().addResourceResolver(resolver);
}
/**
* Adds a {@link ResourceResolverSpi} to enable the retrieval of resources.
*
* @param resolver
*/
public void addResourceResolver(ResourceResolverSpi resolver) {
this.getSignedInfo().addResourceResolver(resolver);
}
/**
* Extracts the public key from the certificate and verifies if the signature
* is valid by re-digesting all References, comparing those against the
* stored DigestValues and then checking to see if the Signatures match on
* the SignedInfo.
*
* @param cert Certificate that contains the public key part of the keypair
* that was used to sign.
* @return true if the signature is valid, false otherwise
* @throws XMLSignatureException
*/
public boolean checkSignatureValue(X509Certificate cert)
throws XMLSignatureException {
// see if cert is null
if (cert != null) {
// check the values with the public key from the cert
return this.checkSignatureValue(cert.getPublicKey());
}
Object exArgs[] = { "Didn't get a certificate" };
throw new XMLSignatureException("empty", exArgs);
}
/**
* 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 {
//COMMENT: pk suggests it can only be a public key?
//check to see if the key is not null
if (pk == null) {
Object exArgs[] = { "Didn't get a key" };
throw new XMLSignatureException("empty", exArgs);
}
// all references inside the signedinfo need to be dereferenced and
// digested again to see if the outcome matches the stored value in the
// SignedInfo.
// If followManifestsDuringValidation is true it will do the same for
// 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();
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI());
log.log(java.util.logging.Level.FINE, "jceSigAlgorithm = " + sa.getJCEAlgorithmString());
log.log(java.util.logging.Level.FINE, "jceSigProvider = " + sa.getJCEProviderName());
log.log(java.util.logging.Level.FINE, "PublicKey = " + pk);
}
byte sigBytes[] = null;
try {
sa.initVerify(pk);
// Get the canonicalized (normalized) SignedInfo
SignerOutputStream so = new SignerOutputStream(sa);
OutputStream bos = new UnsyncBufferedOutputStream(so);
si.signInOctetStream(bos);
bos.close();
// retrieve the byte[] from the stored signature
sigBytes = this.getSignatureValue();
} catch (IOException ex) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
}
// Impossible...
} catch (XMLSecurityException ex) {
throw ex;
}
// have SignatureAlgorithm sign the input bytes and compare them to
// the bytes that were stored in the signature.
if (!sa.verify(sigBytes)) {
log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
return false;
}
return si.verify(this.followManifestsDuringValidation);
} catch (XMLSignatureException ex) {
throw ex;
} catch (XMLSecurityException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Add a Reference with full parameters to this Signature
*
* @param referenceURI URI of the resource to be signed. Can be null in
* which case the dereferencing is application specific. Can be "" in which
* it's the parent node (or parent document?). There can only be one "" in
* each signature.
* @param trans Optional list of transformations to be done before digesting
* @param digestURI Mandatory URI of the digesting algorithm to use.
* @param referenceId Optional id attribute for this Reference
* @param referenceType Optional mimetype for the URI
* @throws XMLSignatureException
*/
public void addDocument(
String referenceURI,
Transforms trans,
String digestURI,
String referenceId,
String referenceType
) throws XMLSignatureException {
this.signedInfo.addDocument(
this.baseURI, referenceURI, trans, digestURI, referenceId, referenceType
);
}
/**
* This method is a proxy method for the {@link Manifest#addDocument} method.
*
* @param referenceURI URI according to the XML Signature specification.
* @param trans List of transformations to be applied.
* @param digestURI URI of the digest algorithm to be used.
* @see Manifest#addDocument
* @throws XMLSignatureException
*/
public void addDocument(
String referenceURI,
Transforms trans,
String digestURI
) throws XMLSignatureException {
this.signedInfo.addDocument(this.baseURI, referenceURI, trans, digestURI, null, null);
}
/**
* Adds a Reference with just the URI and the transforms. This used the
* SHA1 algorithm as a default digest algorithm.
*
* @param referenceURI URI according to the XML Signature specification.
* @param trans List of transformations to be applied.
* @throws XMLSignatureException
*/
public void addDocument(String referenceURI, Transforms trans)
throws XMLSignatureException {
this.signedInfo.addDocument(
this.baseURI, referenceURI, trans, Constants.ALGO_ID_DIGEST_SHA1, null, null
);
}
/**
* Add a Reference with just this URI. It uses SHA1 by default as the digest
* algorithm
*
* @param referenceURI URI according to the XML Signature specification.
* @throws XMLSignatureException
*/
public void addDocument(String referenceURI) throws XMLSignatureException {
this.signedInfo.addDocument(
this.baseURI, referenceURI, null, Constants.ALGO_ID_DIGEST_SHA1, null, null
);
}
/**
* Add an X509 Certificate to the KeyInfo. This will include the whole cert
* inside X509Data/X509Certificate tags.
*
* @param cert Certificate to be included. This should be the certificate of
* the key that was used to sign.
* @throws XMLSecurityException
*/
public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
X509Data x509data = new X509Data(this.doc);
x509data.addCertificate(cert);
this.getKeyInfo().add(x509data);
}
/**
* Add this public key to the KeyInfo. This will include the complete key in
* the KeyInfo structure.
*
* @param pk
*/
public void addKeyInfo(PublicKey pk) {
this.getKeyInfo().add(pk);
}
/**
* Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want
* to create a MAC, this method helps you to obtain the
* {@link javax.crypto.SecretKey} from octets.
*
* @param secretKeyBytes
* @return the secret key created.
* @see SignedInfo#createSecretKey(byte[])
*/
public SecretKey createSecretKey(byte[] secretKeyBytes) {
return this.getSignedInfo().createSecretKey(secretKeyBytes);
}
/**
* Signal whether Manifest should be automatically validated.
* Checking the digests in References in a Signature are mandatory, but for
* References inside a Manifest it is application specific. This boolean is
* to indicate that the References inside Manifests should be validated.
*
* @param followManifests
* @see <a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">
* Core validation section in the XML Signature Rec.</a>
*/
public void setFollowNestedManifests(boolean followManifests) {
this.followManifestsDuringValidation = followManifests;
}
/**
* Get the local name of this element
*
* @return Constants._TAG_SIGNATURE
*/
public String getBaseLocalName() {
return Constants._TAG_SIGNATURE;
}
}
Other Java examples (source code examples)Here is a short list of links related to this Java XMLSignature.java source code file: |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.