/** * @param caminhoCertificado * @param senhaCertificado * @paaram senhaCertificado * @param caminhoArquivo * @return * @throws Exception */ public static String assinarDocumento( String caminhoCertificado, String senhaCertificado, String caminhoArquivo) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream certificadoStream = new FileInputStream(new File(caminhoCertificado))) { keyStore.load(certificadoStream, senhaCertificado.toCharArray()); } final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry( keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(senhaCertificado.toCharArray())); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add( signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add( signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data( Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(new File(caminhoArquivo)); for (final String elementoAssinavel : ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference( "#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo( signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(document), new StreamResult(outputStream)); return outputStream.toString(); } }
private static KeyInfo createKeyInfo(PublicKey publicKey, X509Certificate x509Certificate) throws KeyException { KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory(); KeyInfo keyInfo = null; KeyValue keyValue = null; // Just with public key if (publicKey != null) { keyValue = keyInfoFactory.newKeyValue(publicKey); keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue)); } if (x509Certificate != null) { List x509list = new ArrayList(); x509list.add(x509Certificate); X509Data x509Data = keyInfoFactory.newX509Data(x509list); List items = new ArrayList(); items.add(x509Data); if (keyValue != null) { items.add(keyValue); } keyInfo = keyInfoFactory.newKeyInfo(items); } return keyInfo; }
/** * Signs a SoapMessage with the holder-of-key configuration provided on class creation. This * method changes the SoapMessage. * * @param message cannot be null * @return The signed SoapMessage * @throws ParserException * @throws SignatureException */ @Override public final SoapMessage sign(SoapMessage message) throws ParserException, SignatureException { assert message != null; Provider securityProvider = holderOfKeyConfig.getSecurityProvider(); XMLSignatureFactory xmlSigFactory = (securityProvider != null) ? XMLSignatureFactory.getInstance("DOM", securityProvider) : XMLSignatureFactory.getInstance(); try { String bodyUuid = createSoapBodyUuid(message); CanonicalizationMethod canonicalizationMethod = xmlSigFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = getSignatureMethod(xmlSigFactory); ArrayList<String> refList = new ArrayList<String>(); refList.add(bodyUuid); refList.add(createTimestampUuid(message)); List<Reference> references = createSignatureReferences(xmlSigFactory, refList); SignedInfo signedInfo = xmlSigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); KeyInfoFactory kif = KeyInfoFactory.getInstance(); KeyInfo ki = kif.newKeyInfo( Collections.singletonList(new DOMStructure(createKeyInfoContent(message)))); XMLSignature signature = xmlSigFactory.newXMLSignature(signedInfo, ki, null, addUseKeySignatureId(message), null); DOMSignContext dsc = new DOMSignContext( holderOfKeyConfig.getPrivateKey(), message.getHeader().getFirstChild()); dsc.putNamespacePrefix(XMLSignature.XMLNS, DIGITAL_SIGNATURE_NAMESPACE_PREFIX); signature.sign(dsc); log.debug("Message with SOAPBody id: " + bodyUuid + " is signed."); } catch (NoSuchAlgorithmException e) { log.debug(CREATING_SIGNATURE_ERR_MSG); throw new SignatureException(CREATING_SIGNATURE_ERR_MSG, e); } catch (InvalidAlgorithmParameterException e) { log.debug(CREATING_SIGNATURE_ERR_MSG); throw new SignatureException(CREATING_SIGNATURE_ERR_MSG, e); } catch (MarshalException e) { log.debug(CREATING_SIGNATURE_ERR_MSG); throw new SignatureException(CREATING_SIGNATURE_ERR_MSG, e); } catch (XMLSignatureException e) { log.debug(CREATING_SIGNATURE_ERR_MSG); throw new SignatureException(CREATING_SIGNATURE_ERR_MSG, e); } return message; }
/** * @param chnlId * @param xmlStr * @param chnlStr * @return */ public String processXMLForChnls(String chnlId, String xmlStr, final String chnlStr) { if ("106".equals(chnlId) || "102".equals(chnlId)) { try { xmlStr = URLEncoder.encode(xmlStr.trim(), "UTF-8"); } catch (UnsupportedEncodingException e) { } xmlStr = "xml=".concat(xmlStr); } else if ("103".equals(chnlId) && !"Route1_CONT".equals(chnlStr)) { xmlStr = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Header>" + "<SOAP-SEC:Signature xmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\">" + "</SOAP-SEC:Signature>" + "</soap:Header>".concat(xmlStr).concat("</soap:Envelope>"); try { // Create a DOM XMLSignatureFactory that will be used to // generate the enveloped signature. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference( "#Body", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList( fac.newTransform( "http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)), null, null); // Create the SignedInfo. SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); // Load the KeyStore and get the signing key and // certificate. KeyStore ks = KeyStore.getInstance("JKS"); String certFileNm = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_JSK"); String pwd = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_PASSWORD"); String aliasNm = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_ALIAS"); ks.load(new FileInputStream(certFileNm), pwd.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(aliasNm, new KeyStore.PasswordProtection(pwd.toCharArray())); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List x509Content = new ArrayList(); // x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert.getIssuerX500Principal().getName()); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // Instantiate the document to be signed. // Document doc = xmlUtil.getDocumentFromString(xmlStr); Document doc = null; // 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()); // 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); // Output the resulting document. xmlStr = xmlUtil.convertXMLDocToString(doc); } catch (Exception e) { } } return xmlStr; }
@Test public void testXmlSignature() throws Exception { String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory factory = XMLSignatureFactory.getInstance( "DOM", (Provider) Class.forName(providerName).newInstance()); DigestMethod digestMethod = factory.newDigestMethod(DigestMethod.SHA1, null); Transform transform = factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null); Reference reference = factory.newReference("", digestMethod, Collections.singletonList(transform), null, null); CanonicalizationMethod canonicalizationMethod = factory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo signedInfo = factory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyStore ks = KeyStore.getInstance("JKS"); InputStream fis = XMLSigSpike.class.getClassLoader().getResourceAsStream("dev.jks"); ks.load(fis, "devjks".toCharArray()); fis.close(); PrivateKey prv = (PrivateKey) ks.getKey("vgr-pdl", "devjks".toCharArray()); final Certificate cert = ks.getCertificate("vgr-pdl"); final Certificate cacert = ks.getCertificate("vgr-ca"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder() .parse(XMLSigSpike.class.getClassLoader().getResourceAsStream("bfr.xml")); final X509Certificate x509Cert = (X509Certificate) cert; List<X509Certificate> x509 = Arrays.asList(x509Cert); KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory(); X509Data x509Data = keyInfoFactory.newX509Data(x509); List items = new ArrayList(); items.add(x509Data); // items.add(pub); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(items); DOMSignContext dsc = new DOMSignContext(prv, doc.getDocumentElement()); XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); FileOutputStream fos = new FileOutputStream("mySignedFile.xml"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(fos)); fos.close(); Document signedDoc = dbf.newDocumentBuilder().parse(new FileInputStream("mySignedFile.xml")); // Find Signature element. NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new Exception("Cannot find Signature element"); } KeySelector selector = new KeySelector() { @Override public KeySelectorResult select( final KeyInfo keyInfo, final Purpose purpose, final AlgorithmMethod algorithmMethod, final XMLCryptoContext xmlCryptoContext) throws KeySelectorException { return new KeySelectorResult() { @Override public Key getKey() { List<X509Data> dataList = keyInfo.getContent(); List<X509Certificate> certList = dataList.get(0).getContent(); X509Certificate cert = certList.get(0); try { x509Cert.verify(cacert.getPublicKey()); } catch (CertificateException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (NoSuchProviderException e) { throw new RuntimeException(e); } catch (SignatureException e) { throw new RuntimeException(e); } return cert.getPublicKey(); } }; } }; // Create a DOMValidateContext and specify a KeySelector // and document context. DOMValidateContext valContext = new DOMValidateContext(selector, nl.item(0)); // Unmarshal the XMLSignature. XMLSignature xmlSignature = factory.unmarshalXMLSignature(valContext); // Validate the XMLSignature. boolean coreValidity = signature.validate(valContext); assertTrue(coreValidity); }
/** * Cria a assinatura para o objeto informado no construtor. * * @return Assinatura gerada. * @throws SignatureException Caso ocorra algum erro ao gerar a assinatura. */ @SuppressWarnings({"rawtypes", "unchecked"}) public SignatureType createSignature() throws SignatureException { try { final X509Certificate certificate = Configuration.getInstance().getCertificate(); // Cria a assinatura com a API do Java. final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transformList = new ArrayList<Transform>(); transformList.add(factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transformList.add( factory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)); final Reference reference = factory.newReference( this.referenceUri, factory.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null); final SignedInfo signedInfo = factory.newSignedInfo( factory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory(); final List x509Content = new ArrayList(); x509Content.add(certificate.getSubjectX500Principal().getName()); x509Content.add(certificate); final X509Data x509Data = keyInfoFactory.newX509Data(x509Content); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DOMSignContext domSignContext = new DOMSignContext( Configuration.getInstance().getPrivateKey(), this.document.getDocumentElement()); final XMLSignature newXMLSignature = factory.newXMLSignature(signedInfo, keyInfo); newXMLSignature.sign(domSignContext); // Remove tags nao recomendadas. final String[] unnecessaryElements = new String[] { "X509SubjectName", "X509IssuerSerial", "X509IssuerName", "X509IssuerName", "X509SKI", "KeyValue", "RSAKeyValue", "Modulus", "Exponent" }; final XPathFactory xpathFactory = XPathFactory.newInstance(); for (final String elementName : unnecessaryElements) { final XPathExpression xpath = xpathFactory.newXPath().compile("//*[name()='" + elementName + "']"); final Node node = (Node) xpath.evaluate(this.document, XPathConstants.NODE); if (null != node) { node.getParentNode().removeChild(node); } } final XPathExpression xpath = xpathFactory.newXPath().compile("//*[name()='Signature']"); return JAXB.unmarshal( new DOMSource((Node) xpath.evaluate(this.document, XPathConstants.NODE)), SignatureType.class); } catch (Exception e) { throw new SignatureException("Um erro ocorreu ao criar a assinatura.", e); } }