List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory getInstance
public static XMLSignatureFactory getInstance(String mechanismType)
XMLSignatureFactory
that supports the specified XML processing mechanism and representation type (ex: "DOM"). From source file:Main.java
/** * @throws NoSuchMechanismException//w w w . ja v a 2s. co m */ static XMLSignatureFactory getDOMInstance() { try { return XMLSignatureFactory.getInstance("DOM"); } catch (NoSuchMechanismException nsme) { Provider provider; try { Class<?> clazz = Class.forName("org.jcp.xml.dsig.internal.dom.XMLDSigRI"); provider = (Provider) clazz.newInstance(); } catch (Exception e) { throw new NoSuchMechanismException(e); } return XMLSignatureFactory.getInstance("DOM", provider); } }
From source file:Main.java
public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException, XMLSignatureException {//from w w w .ja va 2 s . co m XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo String method = SignatureMethod.RSA_SHA1; // default if ("DSA".equals(privKey.getAlgorithm())) method = SignatureMethod.DSA_SHA1; SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it List<XMLStructure> kidata = new ArrayList<XMLStructure>(); kidata.add(kv); KeyInfo ki = kif.newKeyInfo(kidata); // Create a DOMSignContext and specify the PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privKey, doc); // Create the XMLSignature (but don't sign it yet) XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate (and sign) the enveloped signature signature.sign(dsc); }
From source file:Main.java
private static synchronized XMLSignatureFactory getXMLSignatureFactory() { return XMLSignatureFactory.getInstance("DOM"); }
From source file:Main.java
/** * Firma digitalmente usando la forma "enveloped signature" según el * estándar de la W3C (<a/*from ww w. j av a2s . co m*/ * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>). * <p> * * Este método además incorpora la información del * certificado a la sección <KeyInfo> opcional del * estándar, según lo exige SII. * <p> * * @param doc * El documento a firmar * @param uri * La referencia dentro del documento que debe ser firmada * @param pKey * La llave privada para firmar * @param cert * El certificado digital correspondiente a la llave privada * @throws NoSuchAlgorithmException * Si el algoritmo de firma de la llave no está soportado * (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1). * @throws InvalidAlgorithmParameterException * Si los algoritmos de canonización (parte del * estándar XML Signature) no son soportados (actaulmente * se usa el por defecto) * @throws KeyException * Si hay problemas al incluir la llave pública en el * <KeyValue>. * @throws MarshalException * @throws XMLSignatureException * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) */ public static void signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo String method = SignatureMethod.RSA_SHA1; // default by SII if ("DSA".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.DSA_SHA1; else if ("HMAC".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.HMAC_SHA1; SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical and // default by SII (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(cert.getPublicKey()); // Create a KeyInfo and add the KeyValue to it List<XMLStructure> kidata = new ArrayList<XMLStructure>(); kidata.add(kv); kidata.add(kif.newX509Data(Collections.singletonList(cert))); KeyInfo ki = kif.newKeyInfo(kidata); // Create a DOMSignContext and specify the PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(pKey, doc); // Create the XMLSignature (but don't sign it yet) XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate (and sign) the enveloped signature signature.sign(dsc); }
From source file:no.digipost.api.SdpMeldingSigner.java
public Document sign(final StandardBusinessDocument sbd) { try {/*from w w w . jav a 2 s. com*/ PrivateKey privateKey = keystoreInfo.getPrivateKey(); X509Certificate certificate = keystoreInfo.getCertificate(); DOMResult result = new DOMResult(); Marshalling.marshal(marshaller, sbd, result); Document doc = (Document) result.getNode(); Marshalling.trimNamespaces(doc); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(Constants.RSA_SHA256, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data xd = kif.newX509Data(Collections.singletonList(certificate)); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = fac.newXMLSignature(si, ki); Node digitalPostNode = doc.getDocumentElement().getFirstChild().getNextSibling(); Node avsenderNode = digitalPostNode.getFirstChild(); DOMSignContext dsc = new DOMSignContext(privateKey, digitalPostNode, avsenderNode); signature.sign(dsc); doc.normalizeDocument(); return doc; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (MarshalException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create an enveloped digital signature for an element of a TAXII document. * * @param element the element to be signed * @param keyEntry the PrivateKeyEntry/*from w ww. java 2s . c o m*/ * @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element * @return the status of the operation * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String keyName = config.getProperty("publisherKeyName"); * String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * PrivateKeyEntry keyEntry = FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW); * List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1); */ private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) { element.normalize(); boolean status = false; //Create XML Signature Factory XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM"); PublicKey publicKey = ClientUtil.getPublicKey(keyEntry); PrivateKey privateKey = keyEntry.getPrivateKey(); DOMSignContext dsc = new DOMSignContext(privateKey, element); dsc.setDefaultNamespacePrefix("ds"); dsc.setURIDereferencer(new MyURIDereferencer(element)); SignedInfo si = null; DigestMethod dm = null; SignatureMethod sm = null; KeyInfo ki = null; X509Data xd; List<Serializable> x509Content = new ArrayList<>(); try { String algorithm = publicKey.getAlgorithm(); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); String algorithmName = cert.getSigAlgName(); if (algorithm.toUpperCase().contains("RSA")) { if (algorithmName.toUpperCase().contains("SHA1")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null); sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } else if (algorithmName.toUpperCase().contains("SHA2")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null); sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } CanonicalizationMethod cm; if (cbIndex != -1) { cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex + "]/*[local-name()='Content'][1]/*)"; List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } else { List<Transform> transforms = new ArrayList<>(2); transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); String refUri = "#xpointer(/*)"; List<Reference> references = Collections .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory(); xd = kif.newX509Data(x509Content); ki = kif.newKeyInfo(Collections.singletonList(xd)); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } } catch (NoSuchAlgorithmException ex) { logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document."); } catch (InvalidAlgorithmParameterException ex) { logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document."); } // Create a new XML Signature XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki); try { // Sign the document signature.sign(dsc); status = true; } catch (MarshalException ex) { logger.error("MarshalException when attempting to digitally sign a document."); } catch (XMLSignatureException ex) { logger.error("XMLSignature Exception when attempting to digitally sign a document."); } catch (Exception e) { logger.error("General exception when attempting to digitally sign a document."); } return status; }
From source file:be.e_contract.dssp.client.SignResponseVerifier.java
/** * Checks the signature on the SignResponse browser POST message. * /*from w ww .j a v a 2s . c o m*/ * @param signResponseMessage * the SignResponse message. * @param session * the session object. * @return the verification result object. * @throws JAXBException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws MarshalException * @throws XMLSignatureException * @throws Base64DecodingException * @throws UserCancelException * @throws ClientRuntimeException * @throws SubjectNotAuthorizedException */ public static SignResponseVerificationResult checkSignResponse(String signResponseMessage, DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException { if (null == session) { throw new IllegalArgumentException("missing session"); } byte[] decodedSignResponseMessage; try { decodedSignResponseMessage = Base64.decode(signResponseMessage); } catch (Base64DecodingException e) { throw new SecurityException("no Base64"); } // JAXB parsing JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class, be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); SignResponse signResponse; try { signResponse = (SignResponse) unmarshaller .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage)); } catch (UnmarshalException e) { throw new SecurityException("no valid SignResponse XML"); } // DOM parsing DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage); Document signResponseDocument = documentBuilder.parse(signResponseInputStream); // signature verification NodeList signatureNodeList = signResponseDocument .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (signatureNodeList.getLength() != 1) { throw new SecurityException("requires 1 ds:Signature element"); } Element signatureElement = (Element) signatureNodeList.item(0); SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey()); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validSignature = xmlSignature.validate(domValidateContext); if (false == validSignature) { throw new SecurityException("invalid ds:Signature"); } // verify content String responseId = null; RelatesToType relatesTo = null; AttributedURIType to = null; TimestampType timestamp = null; String signerIdentity = null; AnyType optionalOutputs = signResponse.getOptionalOutputs(); List<Object> optionalOutputsList = optionalOutputs.getAny(); for (Object optionalOutputObject : optionalOutputsList) { LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName()); if (optionalOutputObject instanceof JAXBElement) { JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject; LOG.debug("optional output name: " + optionalOutputElement.getName()); LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName()); if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) { responseId = (String) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof RelatesToType) { relatesTo = (RelatesToType) optionalOutputElement.getValue(); } else if (TO_QNAME.equals(optionalOutputElement.getName())) { to = (AttributedURIType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof TimestampType) { timestamp = (TimestampType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) { NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue(); signerIdentity = nameIdentifier.getValue(); } } } Result result = signResponse.getResult(); LOG.debug("result major: " + result.getResultMajor()); LOG.debug("result minor: " + result.getResultMinor()); if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) { if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) { throw new UserCancelException(); } if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) { throw new ClientRuntimeException(); } if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR .equals(result.getResultMinor())) { throw new SubjectNotAuthorizedException(signerIdentity); } } if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) { throw new SecurityException("invalid dss:ResultMajor"); } if (null == responseId) { throw new SecurityException("missing async:ResponseID"); } if (false == responseId.equals(session.getResponseId())) { throw new SecurityException("invalid async:ResponseID"); } if (null == relatesTo) { throw new SecurityException("missing wsa:RelatesTo"); } if (false == session.getInResponseTo().equals(relatesTo.getValue())) { throw new SecurityException("invalid wsa:RelatesTo"); } if (null == to) { throw new SecurityException("missing wsa:To"); } if (false == session.getDestination().equals(to.getValue())) { throw new SecurityException("invalid wsa:To"); } if (null == timestamp) { throw new SecurityException("missing wsu:Timestamp"); } AttributedDateTime expires = timestamp.getExpires(); if (null == expires) { throw new SecurityException("missing wsu:Timestamp/wsu:Expires"); } DateTime expiresDateTime = new DateTime(expires.getValue()); DateTime now = new DateTime(); if (now.isAfter(expiresDateTime)) { throw new SecurityException("wsu:Timestamp expired"); } session.setSignResponseVerified(true); SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult( signerIdentity); return signResponseVerificationResult; }
From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java
private void addSignature(Element parentElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { DOMSignContext domSignContext = new DOMSignContext(this.sessionKey.getPrivate(), parentElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); Reference reference = xmlSignatureFactory.newReference("#" + this.prototypeKeyBindingId, xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null);//w w w. j a va 2 s . c o m SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, null); xmlSignature.sign(domSignContext); }
From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java
@Override public void validateDigitalSignature(Node sig, final XDSDocumentResolver resolver) throws NotificationValidationException { boolean valid = false; try {/*from ww w . j a v a 2 s. c o m*/ final DOMValidateContext valContext = new DOMValidateContext(getKeySelector(), sig); final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = fac.unmarshalXMLSignature(valContext); // We cannot validate the References to documents in the XDS without // first retrieving them. So, for now, we can't do "core" validation. // We can only validate the Signature itself. valid = signature.getSignatureValue().validate(valContext); // CHECKSTYLE:OFF } catch (Exception ex) { // CHECKSTYLE:ON throw new NotificationValidationException("Error validating digital signature: " + ex.getMessage(), ex); } if (!valid) { throw new NotificationValidationException(ERR_SIG_VALIDATION_FAILED_MSG); } validateDocReferences(sig, resolver); }
From source file:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java
private void addSignature(Element parentElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { DOMSignContext domSignContext = new DOMSignContext(this.authnPrivateKey, parentElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); Reference reference = xmlSignatureFactory.newReference(this.referenceUri, xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null);/*from ww w . j a v a 2s .co m*/ SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections .singletonList(keyInfoFactory.newX509Data(Collections.singletonList(this.authnCertificate)))); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(domSignContext); }