Results 1 to 1 of 1
  1. #1
    bjr149 is offline Member
    Join Date
    Jan 2012
    Posts
    1
    Rep Power
    0

    Default Problem Digitally signing an xml document "Cannot resolve element"

    I am trying to sign a cXML document. I try to add 3 references to the XMLSignatureFactory but when it hits the 2nd on it throws an error "Cannot resolve element with ID cXMLData". How come I can't add more than 1? It throws the error on line 104

    Here is the stack trace :
    java.lang.RuntimeException: javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.res olver.ResourceResolverException: Cannot resolve element with ID cXMLData
    at com.praxair.security.b2b.CXMLDigitalSig.sign(CXMLD igitalSig.java:303)
    at com.praxair.security.b2b.CXMLDigitalSig.main(CXMLD igitalSig.java:359)


    Java Code:
    public class CXMLDigitalSig 
    {
    	private XMLSignatureFactory factory;
    	private KeyStore keyStore;
    	private KeyPair keyPair;
    	private KeyInfo keyInfo;
    	private X509Certificate signingCert;
    	
    	public CXMLDigitalSig()
    	{
    				
    	}
    	
    	private void loadCert() throws Exception
    	{
    		//String keystoreFile = config.getString(KEY_STORE_FILE);
    		//String password = config.getString(KEY_STORE_PASSWORD);
    		//String alias = config.getString(KEY_STORE_ALIAS);
    
    		String keystoreFile = "C:\\cxmlsign\\teststore";
    		String password = "xxxxx";
    		String alias = "xxxxx (thawte ssl ca)";
    			
    		
    		keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    		File file = new File(keystoreFile);
    		FileInputStream inStream = new FileInputStream(file);
    
    		char [] passAsChar = password.toCharArray();		
    		
    		keyStore.load(inStream, passAsChar);
    		inStream.close();
    		String providerName = System.getProperty("jsr105Provider",
    				"org.jcp.xml.dsig.internal.dom.XMLDSigRI");
    		factory = XMLSignatureFactory.getInstance("DOM", (Provider) Class
    				.forName(providerName).newInstance());
    
    		KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
    				.getEntry(alias, new KeyStore.PasswordProtection(passAsChar));
    		signingCert = (X509Certificate) entry.getCertificate();
    
    		keyPair = new KeyPair(entry.getCertificate().getPublicKey(),
    				entry.getPrivateKey());
    
    		KeyInfoFactory kFactory = factory.getKeyInfoFactory();
    		keyInfo = kFactory.newKeyInfo(Collections.singletonList(kFactory
    				.newX509Data(Collections.singletonList(entry
    						.getCertificate()))));
    
    	}
    	
    
    	/**
    	 * This method returns the message digest for given certificate.
    	 * 
    	 * @param cert
    	 * @return
    	 * @throws NoSuchAlgorithmException
    	 * @throws CertificateEncodingException
    	 */
    	private static String getThumbPrint(X509Certificate cert)
    			throws NoSuchAlgorithmException, CertificateEncodingException {
    		MessageDigest md = MessageDigest.getInstance("SHA-1");
    		byte[] der = cert.getEncoded();
    		md.update(der);
    		byte[] digest = md.digest();
    		return hexify(digest);
    	}
    
    	private static String hexify(byte bytes[]) {
    
    		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    				'a', 'b', 'c', 'd', 'e', 'f' };
    
    		StringBuffer buf = new StringBuffer(bytes.length * 2);
    
    		for (int i = 0; i < bytes.length; ++i) {
    			buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
    			buf.append(hexDigits[bytes[i] & 0x0f]);
    		}
    
    		return buf.toString();
    	}
    
    	/**
    	 * Adds an enveloped signature to the given document. The signature is
    	 * generated as per the CXML specfication outlined in the CXML user guide.
    	 * This method creates the signature and three references and also the XADES
    	 * information.
    	 */
    	public void sign(Element cxmlElement, String payloadId) throws SQLException {
    		Reference ref1;
    		Reference ref2;
    		Reference ref3;
    		
    		List<Reference> refs = new ArrayList<Reference>();
    		SignedInfo signedInfo;
    		try {
    			ref1 = factory.newReference("#cXMLSignedInfo",
    					factory.newDigestMethod(DigestMethod.SHA1, null), null,
    					null, null);
    			refs.add(ref1);
    
    			ref2 = factory.newReference("#cXMLData",
    					factory.newDigestMethod(DigestMethod.SHA1, null), null,
    					null, null);
    			refs.add(ref2);
    
    			ref3 = factory.newReference("#XAdESSignedProps",
    					factory.newDigestMethod(DigestMethod.SHA1, null));
    			refs.add(ref3);
    
    			signedInfo = factory.newSignedInfo(factory
    					.newCanonicalizationMethod(
    							CanonicalizationMethod.INCLUSIVE,
    							(C14NMethodParameterSpec) null), factory
    					.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
    		} catch (NoSuchAlgorithmException e) {
    			throw new RuntimeException(e);
    		} catch (InvalidAlgorithmParameterException e) {
    			throw new RuntimeException(e);
    		}
    
    		List<DOMStructure> xmlObjSignedInfo = new ArrayList<DOMStructure>();
    		Element signedInfoElement = createElement(cxmlElement,
    				"cXMLSignedInfo", null, null);
    		signedInfoElement.setAttributeNS(null, "Id", "cXMLSignedInfo");
    		signedInfoElement.setAttributeNS(null, "payloadID", payloadId);
    		signedInfoElement.setAttributeNS(null, "signatureVersion", "1.0");
    
    		DOMStructure signedInfoStruct = new DOMStructure(signedInfoElement);
    		xmlObjSignedInfo.add(signedInfoStruct);
    
    		String xadesNS = "http://uri.etsi.org/01903/v1.1.1#";
    
    		// Create the necessary XADES information as outlined in the CXML
    		// specification
    		Element QPElement = createElement(cxmlElement, "QualifyingProperties",
    				"xades", xadesNS);
    		QPElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
    				"xmlns:xades", xadesNS);
    		QPElement.setAttributeNS(null, "Target", "#cXMLSignature");
    
    		Element SPElement = createElement(cxmlElement, "SignedProperties",
    				"xades", xadesNS);
    		SPElement.setAttributeNS(null, "Id", "XAdESSignedProps");
    		IdResolver.registerElementById(SPElement, "XAdESSignedProps");
    		QPElement.appendChild(SPElement);
    
    		Element signedSPElement = createElement(cxmlElement,
    				"SignedSignatureProperties", "xades", xadesNS);
    
    		Element signingTimeElement = createElement(cxmlElement, "SigningTime",
    				"xades", xadesNS);
    		SimpleDateFormat dateFormatter = new SimpleDateFormat(
    				"yyyy-MM-dd'T'HH:mm:ss");
    		signingTimeElement.appendChild(cxmlElement.getOwnerDocument()
    				.createTextNode(dateFormatter.format(new Date())));
    		signedSPElement.appendChild(signingTimeElement);
    		SPElement.appendChild(signedSPElement);
    
    		String certDigest = "";
    		try {
    			certDigest = getThumbPrint(signingCert);
    		} catch (CertificateEncodingException ce) {
    			throw new RuntimeException(ce);
    		} catch (NoSuchAlgorithmException ne) {
    			throw new RuntimeException(ne);
    		}
    
    		Element signingCertificateElement = createElement(cxmlElement,
    				"SigningCertificate", "xades", xadesNS);
    
    		Element certElement = createElement(cxmlElement, "Cert", "xades",
    				xadesNS);
    		Element certDigestElement = createElement(cxmlElement, "CertDigest",
    				"xades", xadesNS);
    
    		Element digestMethodElement = createElement(cxmlElement,
    				"DigestMethod", "ds", XMLSignature.XMLNS);
    		digestMethodElement
    				.setAttributeNS(null, "Algorithm", DigestMethod.SHA1);
    
    		Element digestValueElement = createElement(cxmlElement, "DigestValue",
    				"ds", XMLSignature.XMLNS);
    		digestValueElement.appendChild(cxmlElement.getOwnerDocument()
    				.createTextNode(certDigest));
    
    		Element issuerSerialElement = createElement(cxmlElement,
    				"IssuerSerial", "xades", xadesNS);
    
    		Element x509IssuerNameElement = createElement(cxmlElement,
    				"X509IssuerName", "ds", XMLSignature.XMLNS);
    		x509IssuerNameElement
    				.appendChild(cxmlElement.getOwnerDocument().createTextNode(
    						signingCert.getIssuerX500Principal().toString()));
    
    		Element x509IssuerSerialNumberElement = createElement(cxmlElement,
    				"X509IssuerSerialNumber", "ds", XMLSignature.XMLNS);
    		x509IssuerSerialNumberElement.appendChild(cxmlElement
    				.getOwnerDocument().createTextNode(
    						signingCert.getSerialNumber().toString()));
    
    		certDigestElement.appendChild(digestMethodElement);
    		certDigestElement.appendChild(digestValueElement);
    		certElement.appendChild(certDigestElement);
    
    		issuerSerialElement.appendChild(x509IssuerNameElement);
    		issuerSerialElement.appendChild(x509IssuerSerialNumberElement);
    		certElement.appendChild(issuerSerialElement);
    
    		signingCertificateElement.appendChild(certElement);
    		signedSPElement.appendChild(signingCertificateElement);
    		DOMStructure qualifPropStruct = new DOMStructure(QPElement);
    
    		List<DOMStructure> xmlObjQualifyingProperty = new ArrayList<DOMStructure>();
    		xmlObjQualifyingProperty.add(qualifPropStruct);
    
    		XMLObject objectSingedInfo = factory.newXMLObject(xmlObjSignedInfo,
    				null, null, null);
    		XMLObject objectQualifyingProperty = factory.newXMLObject(
    				xmlObjQualifyingProperty, null, null, null);
    
    		// Create the ds:object tags
    		List<XMLObject> objects = new ArrayList<XMLObject>();
    		objects.add(objectSingedInfo);
    		objects.add(objectQualifyingProperty);
    
    		XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo,
    				objects, "cXMLSignature", null);
    		DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
    				cxmlElement);
    		signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
    		try {
    			signature.sign(signContext);
    		} catch (MarshalException e) {
    			throw new RuntimeException(e);
    		} catch (XMLSignatureException e) {
    			throw new RuntimeException(e);
    		}
     
    	}
    
    	private Element createElement(Element element, String tag, String prefix,
    			String nsURI) {
    		String qName = prefix == null ? tag : prefix + ":" + tag;
    		return element.getOwnerDocument().createElementNS(nsURI, qName);
    	}
     
    	X509Certificate getSigningCert() {
    		return signingCert;
    	}
    
    	private static String readFileAsString(String filePath)	throws java.io.IOException 
    	{
    		byte[] buffer = new byte[(int) new File(filePath).length()];
    		BufferedInputStream f = null;
    		try {
    			f = new BufferedInputStream(new FileInputStream(filePath));
    			f.read(buffer);
    		} finally {
    			if (f != null) {
    				try {
    					f.close();
    				} catch (IOException ignored) {
    				}
    			}
    		}
    		return new String(buffer);
    	}
    
    	
    	public static void main(String args[])
    	{
    		 
    		System.out.println("start");
    		CXMLDigitalSig cXMLDigitalSig = new CXMLDigitalSig(); 
    		try
    		{
    			cXMLDigitalSig.loadCert();
    			
    	   		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			
    	   		dbf.setNamespaceAware(true);
    			
    			String cXML = readFileAsString("C:\\cxmlsign\\cxml.xml");
    
    	   		Document cxmlDocument = dbf.newDocumentBuilder()
    									.parse(new ByteArrayInputStream(cXML
    											.getBytes("UTF-8")));
    		
    			System.out.println(cxmlDocument.getDocumentElement().getTagName());
    
    		
    	   		cXMLDigitalSig.sign(cxmlDocument.getDocumentElement(), "55");
    			
    		}
    		catch(Exception e)
    		{
    			//System.out.println(e.getMessage());
    			System.out.println(getStackTrace(e));
    		}
    				
       		System.out.println("end");
    	}
    
    	  public static String getStackTrace(Throwable aThrowable) {
    		    final Writer result = new StringWriter();
    		    final PrintWriter printWriter = new PrintWriter(result);
    		    aThrowable.printStackTrace(printWriter);
    		    return result.toString();
    		  }
    }
    Last edited by bjr149; 01-18-2012 at 03:50 PM. Reason: x

Similar Threads

  1. Getting "cannot resolve" errors with java.swing
    By Eleeist in forum New To Java
    Replies: 6
    Last Post: 03-29-2014, 06:22 AM
  2. Replies: 0
    Last Post: 06-24-2011, 09:14 PM
  3. How can I fix "Cannot resolve symbol" error
    By yma16 in forum IntelliJ IDEA
    Replies: 4
    Last Post: 05-16-2011, 01:28 PM
  4. genjar - "Unable to resolve:"
    By angryboy in forum New To Java
    Replies: 0
    Last Post: 06-28-2009, 07:48 AM
  5. Replies: 1
    Last Post: 10-20-2008, 08:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •