cancel
Showing results for 
Search instead for 
Did you mean: 

Java Mapping - Error when parsing an XML document (Premature end of file.)

joel_langoyan
Participant
0 Kudos

Hi Experts,

I have requirement to have incoming XML payloads to be digitally signed and encrypted. I have applied the Java mapping in SAP PI/PO XML X509 signature by certificate | SAP Blogs to do the digital signing. I have created another Java mapping to do the encryption following the XML Encryption Syntax and Processing Version 1.1 (w3.org) which I have identified following the samples from recipient system. Testing local on NWDS, the code works fine but testing for operation mapping it fails with the premature end of file error.

Not surely exactly which part of the code is causing such issue. As I understand, the doFinal method modifies and generates a new XML. Any input is appreciated.

Below XML encryption code

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.EncryptedKey;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLEncryptionException;
import org.apache.xml.security.keys.KeyInfo;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.sap.aii.mapping.api.AbstractTrace;
import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;
import com.sap.aii.security.lib.KeyStoreManager;
import com.sap.security.api.ssf.ISsfProfile;

public class JM_XMLEncryption extends AbstractTransformation {
	static AbstractTrace log = null;
	@Override
	public void transform(TransformationInput arg0, TransformationOutput arg1) throws StreamTransformationException {
		log = this.getTrace();
		String encKeyView = arg0.getInputParameters().getString("encKeyView");
		String encKeyEntry = arg0.getInputParameters().getString("encKeyEntry");

		try {
			log.addInfo("START of XML Encryption");
			//load input payload as Document
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			Document document = dbf.newDocumentBuilder().parse(arg0.getInputPayload().getInputStream());

			log.addInfo("Signed Payload\n"+logPayload(document));

			//load the certificate for Key store
			ISsfProfile encryptProfile = getSsfProfileKeyStore(encKeyView,encKeyEntry);
			X509Certificate certificate = encryptProfile.getCertificate();
			log.addInfo("certificate \n"+certificate.toString());

			//generate secret key
			SecretKey skey = generateDataEncryptionKey();

			//encrypt the secret key
			PublicKey pubkey = certificate.getPublicKey();
			XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
			keyCipher.init(XMLCipher.WRAP_MODE, pubkey);
			EncryptedKey encKey = keyCipher.encryptKey(document, skey);

			//encrypt the contents of document
			XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
			xmlCipher.init(XMLCipher.ENCRYPT_MODE, skey);

			//add key info to encrypted Data
			EncryptedData encData = xmlCipher.getEncryptedData();
	        KeyInfo keyInfo = new KeyInfo(document);
	        keyInfo.add(encKey);
	        encData.setKeyInfo(keyInfo);

	        xmlCipher.doFinal(document, document.getDocumentElement(), false);
	        log.addInfo("Encrypted Payload\n"+logPayload(document));

	        //Output the resulting document.
	        OutputStream os = arg1.getOutputPayload().getOutputStream();
	        //os.write(document.toString().getBytes());
	     	TransformerFactory tf = TransformerFactory.newInstance();
	     	Transformer trans = tf.newTransformer();
	     	trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	     	trans.transform(new DOMSource(document), new StreamResult(os));
		} catch (SAXException | IOException | ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (XMLEncryptionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
     	catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static String logPayload(Document arg0) throws TransformerException {
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer trans = tf.newTransformer();
		DOMSource source = new DOMSource(arg0);
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		trans.transform(source, result);
		return writer.toString();
	}

	private static SecretKey generateDataEncryptionKey() throws Exception {
	      //String jceAlgorithmName = "DESede";
	      KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
	      keyGenerator.init(168);
	      return keyGenerator.generateKey();
	}

	private static ISsfProfile getSsfProfileKeyStore(String keyStoreAlias, String keyStoreEntry) throws StreamTransformationException {
		KeyStoreManager managerPriviliged = null;
		try {
			managerPriviliged = com.sap.aii.af.service.resource.SAPSecurityResources.getInstance().getKeyStoreManager(
					com.sap.aii.security.lib.PermissionMode.SYSTEM_LEVEL);
		} catch (KeyStoreException e) {
			throw new StreamTransformationException("SAPSecurityResources", e);
		}
		KeyStore keyStore;
		try {
			keyStore = managerPriviliged.getKeyStore(keyStoreAlias);
		} catch (KeyStoreException e) {
			throw new StreamTransformationException("managerPriviliged.getKeyStore " + keyStoreAlias, e);
		}
		ISsfProfile profile = null;
		try {
			profile = managerPriviliged.getISsfProfile(keyStore, keyStoreEntry, null);
		} catch (KeyStoreException e) {
			throw new StreamTransformationException("Failed to load SsfProfileKeyStore " + keyStoreAlias + " " + keyStoreEntry, e);
		}
		return profile;
	}
}

Accepted Solutions (0)

Answers (0)