use of javax.xml.crypto.dsig.XMLSignature in project openolat by klemens.
the class XMLDigitalSignatureUtil method signEmbedded.
/**
* Produce a signed a XML file. The signature is added in the XML file.
*
* @param xmlFile The original XML file
* @param xmlSignedFile The signed XML file
* @param x509Cert
* @param privateKey
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws NoSuchAlgorithmException
* @throws GeneralSecurityException
* @throws MarshalException
* @throws XMLSignatureException
* @throws TransformerException
*/
public static void signEmbedded(File xmlFile, File xmlSignedFile, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
Document doc = getDocument(xmlFile);
// Create the signature factory for creating the signature.
XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
List<Transform> transforms = new ArrayList<Transform>();
Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
transforms.add(envelopped);
// Create the canonicalization transform to be applied after the XSLT.
CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
transforms.add(c14n);
// Create the Reference to the XML to be signed specifying the hash algorithm to be used
// and the list of transforms to apply. Also specify the XML to be signed as the current
// document (specified by the first parameter being an empty string).
Reference reference = sigFactory.newReference("", sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
// Create the Signed Info node of the signature by specifying the canonicalization method
// to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
// Create the KeyInfo node containing the public key information to include in the signature.
KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Get the node to attach the signature.
Node signatureInfoNode = doc.getDocumentElement();
// Create a signing context using the private key.
DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
// Create the signature from the signing context and key info
XMLSignature signature = sigFactory.newXMLSignature(si, ki);
signature.sign(dsc);
write(doc, xmlSignedFile);
}
use of javax.xml.crypto.dsig.XMLSignature in project openolat by klemens.
the class XMLDigitalSignatureUtil method validate.
/**
* Validate a XML file with a XML Digital Signature saved in an extenral file.
*
* @param xmlFile
* @param xmlSignatureFile
* @param publicKey
* @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws MarshalException
* @throws XMLSignatureException
*/
public static boolean validate(String uri, File xmlFile, File xmlSignatureFile, PublicKey publicKey) throws ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException {
Document doc = getDocument(xmlSignatureFile);
NodeList nl = doc.getElementsByTagName("Signature");
if (nl.getLength() == 0) {
return false;
}
DOMValidateContext validContext = new DOMValidateContext(publicKey, nl.item(0));
validContext.setBaseURI(uri);
validContext.setURIDereferencer(new FileURIDereferencer(uri, xmlFile));
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
XMLSignature signature = fac.unmarshalXMLSignature(validContext);
boolean validFlag = signature.validate(validContext);
if (!validFlag) {
// log and throw if not valid
boolean sv = signature.getSignatureValue().validate(validContext);
String msg = "signature validation status: " + sv;
int numOfReferences = signature.getSignedInfo().getReferences().size();
for (int j = 0; j < numOfReferences; j++) {
Reference ref = (Reference) signature.getSignedInfo().getReferences().get(j);
boolean refValid = ref.validate(validContext);
msg += " ref[" + j + "] validity status: " + refValid;
}
log.warn(msg);
}
return validFlag;
}
use of javax.xml.crypto.dsig.XMLSignature in project oxCore by GluuFederation.
the class Response method isValid.
public boolean isValid() throws Exception {
NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodes == null || nodes.getLength() == 0) {
throw new Exception("Can't find signature in document.");
}
if (setIdAttributeExists()) {
tagIdAttributes(xmlDoc);
}
X509Certificate cert = samlSettings.getCertificate();
DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0));
XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);
return xmlSignature.validate(ctx);
}
use of javax.xml.crypto.dsig.XMLSignature in project cxf by apache.
the class MetadataWriter method signMetaInfo.
private static Document signMetaInfo(X509Certificate signingCert, Key signingKey, Document doc, String referenceID) throws Exception {
final String signatureMethod;
if ("SHA1withDSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.DSA_SHA1;
} else if ("SHA1withRSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else if ("SHA256withRSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else {
LOG.error("Unsupported signature method: " + signingCert.getSigAlgName());
throw new RuntimeException("Unsupported signature method: " + signingCert.getSigAlgName());
}
List<Transform> transformList = Arrays.asList(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null), XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null));
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
Reference ref = XML_SIGNATURE_FACTORY.newReference("#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
// Create the SignedInfo.
SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), XML_SIGNATURE_FACTORY.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
List<Object> x509Content = Arrays.asList(signingCert.getSubjectX500Principal().getName(), signingCert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
// DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
dsc.setNextSibling(doc.getDocumentElement().getFirstChild());
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
// Output the resulting document.
return doc;
}
use of javax.xml.crypto.dsig.XMLSignature in project camel by apache.
the class XmlVerifierProcessor method verify.
@SuppressWarnings("unchecked")
protected void verify(InputStream input, final Message out) throws Exception {
//NOPMD
LOG.debug("Verification of XML signature document started");
final Document doc = parseInput(input, out);
XMLSignatureFactory fac;
// not work
try {
fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
} catch (NoSuchProviderException ex) {
fac = XMLSignatureFactory.getInstance("DOM");
}
KeySelector selector = getConfiguration().getKeySelector();
if (selector == null) {
throw new IllegalStateException("Wrong configuration. Key selector is missing.");
}
DOMValidateContext valContext = new DOMValidateContext(selector, doc);
valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
}
setUriDereferencerAndBaseUri(valContext);
setCryptoContextProperties(valContext);
NodeList signatureNodes = getSignatureNodes(doc);
List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
List<Reference> collectedReferences = new ArrayList<Reference>(3);
int totalCount = signatureNodes.getLength();
for (int i = 0; i < totalCount; i++) {
Element signatureNode = (Element) signatureNodes.item(i);
valContext.setNode(signatureNode);
final XMLSignature signature = fac.unmarshalXMLSignature(valContext);
if (getConfiguration().getXmlSignatureChecker() != null) {
XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc).keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode).objects(signature.getObjects()).signatureValue(signature.getSignatureValue()).signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount).xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build();
getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput);
}
boolean coreValidity;
try {
coreValidity = signature.validate(valContext);
} catch (XMLSignatureException se) {
throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se);
}
// Check core validation status
boolean goon = coreValidity;
if (!coreValidity) {
goon = handleSignatureValidationFailed(valContext, signature);
}
if (goon) {
LOG.debug("XML signature {} verified", i + 1);
} else {
throw new XmlSignatureInvalidException("XML signature validation failed");
}
collectedObjects.addAll(signature.getObjects());
collectedReferences.addAll(signature.getSignedInfo().getReferences());
}
map2Message(collectedReferences, collectedObjects, out, doc);
}
Aggregations