下面列出了怎么用javax.xml.crypto.dsig.XMLSignatureFactory的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException {
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));
// create a key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
// sign the document
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
OutputStream os = System.out;
new XmlGenerator().generate(doc.getDocumentElement(), os);
}
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));
// create a key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
// sign the document
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
OutputStream os = System.out;
new XmlGenerator().generate(doc.getDocumentElement(), os);
}
private KeyInfo getKeyInfo(XMLSignatureFactory fac, PrivateKeyEntry keyEntry) throws Exception {
String keyInfoChoice = (String) includeKeyInfo.getSelectedItem();
if( Boolean.parseBoolean(keyInfoChoice) ) {
KeyInfo keyInfo;
X509Certificate cert = (X509Certificate)keyEntry.getCertificate();
KeyInfoFactory keyInfoFac = fac.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
if( this.subject.isSelected() ) {
x509Content.add(cert.getSubjectX500Principal().getName());
}
if( this.serialIssuer.isSelected() ) {
x509Content.add(keyInfoFac.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),cert.getSerialNumber()));
}
if( this.issuer.isSelected() ) {
x509Content.add(cert.getIssuerX500Principal().getName());
}
if( this.certificate.isSelected() ) {
x509Content.add(cert);
}
X509Data xd = keyInfoFac.newX509Data(x509Content);
keyInfo = keyInfoFac.newKeyInfo(Collections.singletonList(xd));
return keyInfo;
}
return (KeyInfo)null;
}
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
Reference ref = initReference(fac);
String cm = null;
cm = map.getProperty(CANONICALIZATIONMETHOD);
String sigmethod = null;
sigmethod = map.getProperty(SIGNATURE_METHOD);
if (sigmethod == null) {
sigmethod = SignatureMethod.RSA_SHA1;
}
if (cm == null) {
cm = CanonicalizationMethod.EXCLUSIVE;
}
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
cm,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(sigmethod,
null), Collections.singletonList(ref));
return si;
}
/**
* Check the xmldsig signature of the XML document.
* @param document the document to test
* @param publicKey the public key corresponding to the key pair the document was signed with
* @return true if a correct signature is present, false otherwise
*/
public static boolean validSignature(Document document, Key publicKey) {
Node signatureNode = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0);
KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);
try {
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureNode);
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
return signature.validate(valContext);
} catch (Exception e) {
Logger.warn("Error validating an XML signature.", e);
return false;
}
}
protected byte[] perform(byte[] input) throws Exception {
String signMethod = (String)signatureMethod.getSelectedItem();
PrivateKeyEntry keyEntry = this.selectedEntry;
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
ArrayList<Reference> references = getReferences(fac);
SignedInfo signatureInfo = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), fac.newSignatureMethod(signatureMethods.get(signMethod), null), references);
KeyInfo keyInfo = this.getKeyInfo(fac, keyEntry);
XMLSignature signature = fac.newXMLSignature(signatureInfo, keyInfo);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input));
try {
validateIdAttributes(doc);
} catch( Exception e ) {
throw new IllegalArgumentException("Provided Id identifier seems to be invalid.");
}
DOMSignContext dsc = new DOMSignContext (keyEntry.getPrivateKey(), doc.getDocumentElement());
signature.sign(dsc);
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
return bos.toByteArray();
}
public XmlSignature() {
super();
this.digestMethods.put("sha1", DigestMethod.SHA1);
this.digestMethods.put("sha256", DigestMethod.SHA256);
this.digestMethods.put("sha512", DigestMethod.SHA512);
this.signatureMethods.put("rsa-sha1", SignatureMethod.RSA_SHA1);
this.signatureFac = XMLSignatureFactory.getInstance("DOM");
this.createMyUI();
}
public static void main(String[] args) throws Exception {
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));
// // create a key pair
// KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// kpg.initialize(512);
// KeyPair kp = kpg.generateKeyPair();
PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\public_key.der");
PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\private_key.der");
// sign the document
DOMSignContext dsc = new DOMSignContext(priv, doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(pub);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");
new XmlGenerator().generate(doc.getDocumentElement(), os);
}
public static void main(String[] args) throws Exception {
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));
// // create a key pair
// KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// kpg.initialize(512);
// KeyPair kp = kpg.generateKeyPair();
PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\public_key.der");
PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\private_key.der");
// sign the document
DOMSignContext dsc = new DOMSignContext(priv, doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(pub);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");
new XmlGenerator().generate(doc.getDocumentElement(), os);
}
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));
// create a key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
// sign the document
DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
OutputStream os = System.out;
new XmlGenerator().generate(doc.getDocumentElement(), os);
}
XMLSignature getValidXMLSignature(InputStream fileStream)
throws ParserConfigurationException,
IOException,
SAXException,
MarshalException,
XMLSignatureException,
DOMException
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xml = dBuilder.parse(fileStream);
xml.getDocumentElement().normalize();
// Find Signature element
NodeList nl = xml.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0)
{
throw new DOMException(DOMException.INDEX_SIZE_ERR, "Missing elements");
}
// Create a DOM XMLSignatureFactory that will be used to unmarshal the
// document containing the XMLSignature
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
// Create a DOMValidateContext and specify a KeyValue KeySelector
// and document context
DOMValidateContext valContext = new DOMValidateContext(new SigningCertSelector(), nl.item(0));
// unmarshal the XMLSignature
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
boolean validSig = signature.validate(valContext);
if(!validSig)
{
throw new XMLSignatureException("Invalid XML signature");
}
return signature;
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new RuntimeException("Couldn't find 'Signature' element");
}
Element element = (Element) nl.item(0);
byte[] keyBytes = Base64.getDecoder().decode(validationKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey key = kf.generatePublic(spec);
KeySelector ks = KeySelector.singletonKeySelector(key);
DOMValidateContext vc = new DOMValidateContext(ks, element);
// disable secure validation mode
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
// set a dummy dereferencer to be able to get content by references
vc.setURIDereferencer(dereferencer);
XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
XMLSignature signature = factory.unmarshalXMLSignature(vc);
// run validation
signature.validate(vc);
}
public RequestSigner ( final Configuration configuration ) throws Exception
{
this.fac = XMLSignatureFactory.getInstance ( "DOM" );
this.md = this.fac.newDigestMethod ( configuration.getDigestMethod (), null );
this.kif = this.fac.getKeyInfoFactory ();
this.t = this.fac.newTransform ( Transform.ENVELOPED, (TransformParameterSpec)null );
this.ref = this.fac.newReference ( "", this.md, Collections.singletonList ( this.t ), null, null );
this.cm = this.fac.newCanonicalizationMethod ( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null );
}
public static boolean verifySignature(Document doc , X509Certificate cert) {
try{
if (doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").getLength() == 0)
throw new Exception("Cannot find Signature element");
DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0));
XMLSignature signature = XMLSignatureFactory.getInstance("DOM").unmarshalXMLSignature(valContext);
return signature.validate(valContext);
}catch(Exception e){e.printStackTrace();}
return false;
}
private static List<Class<?>> getDeprivilegedClasses() {
List<Class<?>> classes = new ArrayList<Class<?>>();
// Test from java.xml.crypto/javax/xml/crypto/dsig package
classes.add(XMLSignatureFactory.class);
// Test from java.xml.crypto/javax/xml/crypto package
classes.add(KeySelectorException.class);
// Test From java.security.jgss/javax/security/auth/kerberos package
classes.add(KeyTab.class);
// Test from jdk.security.jgss/com/sun/security/jgss package
classes.add(AuthorizationDataEntry.class);
// Test from jdk.security.auth/com/sun/security/auth/callback package
classes.add(TextCallbackHandler.class);
return classes;
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new RuntimeException("Couldn't find 'Signature' element");
}
Element element = (Element) nl.item(0);
byte[] keyBytes = Base64.getDecoder().decode(validationKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey key = kf.generatePublic(spec);
KeySelector ks = KeySelector.singletonKeySelector(key);
DOMValidateContext vc = new DOMValidateContext(ks, element);
// disable secure validation mode
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
// set a dummy dereferencer to be able to get content by references
vc.setURIDereferencer(dereferencer);
XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
XMLSignature signature = factory.unmarshalXMLSignature(vc);
// run validation
signature.validate(vc);
}
public static void main(String[] args) {
try {
XMLSignatureFactory sf = XMLSignatureFactory.getInstance(
"DOM", "SomeProviderThatDoesNotExist");
}
catch(NoSuchProviderException e) {
// this is expected
}
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new RuntimeException("Couldn't find 'Signature' element");
}
Element element = (Element) nl.item(0);
byte[] keyBytes = Base64.getDecoder().decode(validationKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey key = kf.generatePublic(spec);
KeySelector ks = KeySelector.singletonKeySelector(key);
DOMValidateContext vc = new DOMValidateContext(ks, element);
// disable secure validation mode
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
// set a dummy dereferencer to be able to get content by references
vc.setURIDereferencer(dereferencer);
XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
XMLSignature signature = factory.unmarshalXMLSignature(vc);
// run validation
signature.validate(vc);
}
/**
* Verifies that signed mark data contains a valid signature.
*
* <p>This method DOES NOT check if the SMD ID is revoked. It's only concerned with the
* cryptographic stuff.
*
* @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH,
* incorrect keys, and for invalid, old, not-yet-valid or revoked certificates.
*/
public void verify(byte[] smdXml)
throws GeneralSecurityException, IOException, MarshalException, ParserConfigurationException,
SAXException, XMLSignatureException {
checkArgument(smdXml.length > 0);
Document doc = parseSmdDocument(new ByteArrayInputStream(smdXml));
NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (signatureNodes.getLength() != 1) {
throw new XMLSignatureException("Expected exactly one <ds:Signature> element.");
}
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
KeyValueKeySelector selector = new KeyValueKeySelector(tmchCertificateAuthority);
DOMValidateContext context = new DOMValidateContext(selector, signatureNodes.item(0));
XMLSignature signature = factory.unmarshalXMLSignature(context);
boolean isValid;
try {
isValid = signature.validate(context);
} catch (XMLSignatureException e) {
throwIfInstanceOf(getRootCause(e), GeneralSecurityException.class);
throw e;
}
if (!isValid) {
throw new XMLSignatureException(explainValidationProblem(context, signature));
}
}
public Document sign(FileInputStream fileStream, KeyPair keyPair)
throws ParserConfigurationException, SAXException, IOException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException,
KeyException, MarshalException, XMLSignatureException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fileStream);
DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
document.getDocumentElement());
XMLSignatureFactory signFactory = XMLSignatureFactory
.getInstance("DOM");
Reference ref = signFactory.newReference("", signFactory
.newDigestMethod(digestMethod, null), Collections
.singletonList(signFactory.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null);
SignedInfo si = signFactory.newSignedInfo(signFactory
.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
(C14NMethodParameterSpec) null), signFactory
.newSignatureMethod(signatureMethod, null), Collections
.singletonList(ref));
KeyInfoFactory kif = signFactory.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(keyPair.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = signFactory.newXMLSignature(si, ki);
signature.sign(signContext);
return document;
}
private boolean validate(final DOMValidateContext validationContext)
throws DigitalSignatureValidationException {
try {
// if (getLogger().isDebugLoggingEnabled()) {
// enableReferenceCaching(validationContext);
// }
XMLSignatureFactory factory = XMLSignatureFactory
.getInstance(XML_MECHANISM_TYPE);
XMLSignature signature = factory
.unmarshalXMLSignature(validationContext);
boolean validationResult = signature.validate(validationContext);
validationResult = workaroundOpenamBug(signature,
validationContext, validationResult);
// if (getLogger().isDebugLoggingEnabled()) {
// debugLogReferences(signature, validationContext);
// }
return validationResult;
} catch (XMLSignatureException | MarshalException exception) {
throw new DigitalSignatureValidationException(
"Error occurred during digital signature validation process",
DigitalSignatureValidationException.ReasonEnum.EXCEPTION_OCCURRED,
exception);
}
}
/**
* Validates if the first XML Signature of the given document is valid
* Only used for test purposes
*
* @param document
* Document with signature to validate
* @return true if valid, else false
*/
public boolean validateSignature(Document document) throws Exception {
setIDAttribute(document);
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
// Find Signature element.
NodeList nl = document.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("Cannot find Signature element");
}
// Create a DOMValidateContext and specify a KeySelector
// and document context.
DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));
// Unmarshal the XMLSignature
javax.xml.crypto.dsig.XMLSignature signature = fac.unmarshalXMLSignature(valContext);
// Validate the XMLSignature.
boolean coreValidity = signature.validate(valContext);
// Check core validation status.
if (coreValidity == false) {
boolean sv = signature.getSignatureValue().validate(valContext);
if (sv == false) {
if(Flags.DEBUG){
// Check the validation status of each Reference.
@SuppressWarnings("rawtypes")
Iterator i = signature.getSignedInfo().getReferences().iterator();
for (int j = 0; i.hasNext(); j++) {
boolean refValid = ((Reference) i.next()).validate(valContext);
System.out.println("ref[" + j + "] validity status: " + refValid);
}
}
}
}
return coreValidity;
}
private Reference initReference(XMLSignatureFactory fac) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
List transformers = new ArrayList();
transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD);
if (dm == null) {
dm = DigestMethod.SHA1;
}
Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null);
return ref;
}
public static void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
XMLSignatureFactory fac = initXMLSigFactory();
X509Certificate cert = (X509Certificate) origCert;
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
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(privateKey, node);
dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ns2");
// Create the XMLSignature, but don't sign it yet.
try {
SignedInfo si = initSignedInfo(fac);
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Reference initReference(XMLSignatureFactory fac) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
List transformers = new ArrayList();
transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
// String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD);
//if (dm == null) {
String dm = DigestMethod.SHA1;
//}
Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null);
return ref;
}
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
Reference ref = initReference(fac);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1,
null),
Collections.singletonList(ref));
return si;
}
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
XMLSignatureFactory fac = initXMLSigFactory();
X509Certificate cert = (X509Certificate) origCert;
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
//x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
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(privateKey, node);
dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2");
// Create the XMLSignature, but don't sign it yet.
try {
SignedInfo si = initSignedInfo(fac);
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Sign the XML document using xmldsig.
* @param document the document to sign; it will be modified by the method.
* @param publicKey the public key from the key pair to sign the document.
* @param privateKey the private key from the key pair to sign the document.
* @return the signed document for chaining.
*/
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();
try {
Reference ref =fac.newReference(
"",
fac.newDigestMethod(DigestMethod.SHA1, null),
Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
null,
null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement());
KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
} catch (Exception e) {
Logger.warn("Error while signing an XML document.", e);
}
return document;
}
private static XMLSignatureFactory getXMLSignatureFactory() {
XMLSignatureFactory xsf = null;
try {
xsf = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
} catch (NoSuchProviderException ex) {
try {
xsf = XMLSignatureFactory.getInstance("DOM");
} catch (Exception err) {
throw new RuntimeException(logger.couldNotCreateInstance("DOM", err));
}
}
return xsf;
}
/**
* Signs the SAML assertion using the specified public and private keys.
*
* @param document
* SAML assertion be signed.
* @param privateKey
* Private key used to sign SAML assertion.
* @param publicKey
* Public key used to sign SAML asserion.
* @return w3c element representation of specified document.
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws KeyException
* @throws MarshalException
* @throws XMLSignatureException
*/
private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
XMLSignatureException {
XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform(
Transform.ENVELOPED, (TransformParameterSpec) null));
Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
envelopedTransform, null, null);
SignatureMethod signatureMethod = null;
if (certificate.getPublicKey() instanceof DSAPublicKey) {
signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
} else if (certificate.getPublicKey() instanceof RSAPublicKey) {
signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
}
CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
Collections.singletonList(ref));
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate));
KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data));
Element w3cElement = document.getDocumentElement();
Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement);
DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint);
XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(dsc);
return w3cElement;
}