1
Decrypt XML File
  • public void decryptData(String encryptedData)
    {
    String encryptedFile = "C:\\Program Files\\Apache Group\\jakarta-tomcat-4.1.27\\webapps\\cs5890project\\WEB-INF\\encryptedpaymentfile.xml";
    String decryptedFile = "C:\\Program Files\\Apache Group\\jakarta-tomcat-4.1.27\\webapps\\cs5890project\\WEB-INF\\decryptedpaymentfile.xml";

    // Testing the provider for TripleDES encryption support.
    try {
    Cipher testCipher = Cipher.getInstance("DESede");
    }//try
    catch(Exception e) {
    // JCE provider not installed on this system.
    // Installing the JCE provider.
    System.err.println("INSTALLING PROVIDER: SunJCE");
    Provider sunjceprov = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunjceprov);
    System.err.println("PROVIDER INSTALLED... CONTINUING");
    }//catch

    // Creating a new XmlEncryption Object for decryption
    XmlEncryption bXmlEnc = new XmlEncryption();
    // Decrypting the XML Encrypted file String
    String bFileString = bXmlEnc.getDecryptedData(encryptedData.toString());  //Encrypted data which was in the form of StringBuffer is written to a File

    System.out.println("bFileString is " + bFileString);

    try
    {
    File xmlFile = new File(decryptedFile);
    BufferedWriter out = new BufferedWriter(new FileWriter(xmlFile));

    StringBuffer stringBuffer = new StringBuffer(bFileString);

    out.write(stringBuffer.toString()); // Decrypted data is returned as a String, this is written to a file
    out.close();

    System.out.println("Decrypted Xml File built successfully");
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }

  • Actual Decryption in the XmlEncryption class

    //Decrypting the XML Encrypted file
    public String getDecryptedData(String encString) {
    String decString = "";


    try {
    //get the encrypted XML file string parsed into a Document object
    ByteArrayInputStream bais = new ByteArrayInputStream(encString.getBytes());
    Document encDoc = docBuilder.parse(bais);
    //Get a list of all the EncryptedData tags
    NodeList nl = encDoc.getElementsByTagName("EncryptedData");
    //Load, decrypt and replace each EncryptedData tag in the Document object


    for(int i=0;i<nl.getLength();i++) {
    //Loading an element
    Node edata = nl.item(i);
    //Extracting the values of Algorithm, KeyName,
    //Type(of encryption) and CipherValue
    String algo = null;
    String keyname = null;
    String encType = null;
    String ciphervalue = null;
    //Setting the values
    edata.normalize();
    //Setting the value of encType
    encType = edata.getAttributes().getNamedItem("Type").getNodeValue();
    //Setting the values of the remaining parameters
    NodeList algoNL = edata.getChildNodes();
    for(int j=0;j<algoNL.getLength();j++) {
            //Setting the value of algo
           if(algoNL.item(j).getNodeName().equals("EncryptionMethod"))
          algo = algoNL.item(j).getAttributes().
          getNamedItem("Algorithm").getNodeValue();
         //Setting the value of keyname
        if(algoNL.item(j).getNodeName().equals("ds:KeyInfo")) {
               NodeList knNL = algoNL.item(j).getChildNodes();
              for(int k=0;k<knNL.getLength();k++) {
                    if(knNL.item(k).getNodeName().equals("KeyName"))
                    keyname = (knNL.item(k).getFirstChild().
                    getNodeValue());
                                                                                                    }
                                                            }
    //Setting the value of ciphervalue
    if(algoNL.item(j).getNodeName().equals("CipherData")) {
    NodeList cvNL = algoNL.item(j).getChildNodes();


              for(int v=0;v<cvNL.getLength();v++) {
             if(cvNL.item(v).getNodeName().equals
             ("CipherValue"))
             ciphervalue = (cvNL.item(v).getFirstChild().
             getNodeValue());
                                                                       }
                                                                                                     }
    }


    if (algo.equals("http://www.w3.org/2001/04/xmlenc#tripledes-cbc"))
    algo = "DESede";
    //Reading the key file and generating/setting decKey
    this.generateDecKey(keyname, algo);
    //Decrypt the cipher
    String decbit = Decrypt(ciphervalue,this.decKey,algo).trim();
    //Replacement Logic
    //For replacing an entire XML file
    if(encType.equals(
    "http://www.isi.edu/in-notes/iana/assignments/media-types/text/xml"))
    decString = decbit;


    }
    catch(org.xml.sax.SAXParseException spe) {
      spe.printStackTrace();
    }
    decString = (getString((XmlDocument)encDoc));
    }
    }
    }
    catch(Exception e) {
    e.printStackTrace();
    }
    return decString;
    }// End getDecryptedData()

    // This is where the actual JCA/JCE data decryption takes place.


    private String Decrypt(String encString, Key decKey, String algo) {
    // Decoding the Base 64 Encoded IV+cipher String into a byte array
    byte[] g = getBase64Decoded(encString);
    int glen = g.length;
    // Separating the IV from the byte array
    byte [] iv = new byte[8];
    for(int t=0;t<8;t++)
    iv[t] = g[t];
    // Separating the cipher from the byte array
    byte [] Enc = new byte[glen-8];
    for(int p=8;p<glen;p++)
    Enc[p-8] = g[p];
    // This will hold the decrypted String
    String decString = null;
    // Decrypting the cipher and setting decString:
    try {
    IvParameterSpec ivps = new IvParameterSpec(iv);
    AlgorithmParameters aparam = AlgorithmParameters.getInstance(algo);
    aparam.init(ivps);
    Cipher cipherObj = Cipher.getInstance(algo+"/CBC/NoPadding");
    cipherObj.init(Cipher.DECRYPT_MODE, decKey, aparam);
    decString = new String(cipherObj.update(Enc));
    }
    catch(Exception e) {
    System.out.println("Problem in Decrypt()");
    e.printStackTrace();
    }
    return decString;
    }//End Decrypt

     

  • <?xml version="1.0" encoding="UTF-8"?>

    <EncryptedData xmlns="http://www.w3.org/2001/04/xmlenc#" Id="Test" Type="http://www.isi.edu/in-notes/iana/assignments/media-types/text/xml">
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <KeyName>theKey</KeyName>
    </ds:KeyInfo>
    <CipherData>
    <CipherValue>W/HrN6WyPC7ieE41K9UVOPTD1Y0lX8/62zuxp1Z+dTekAoa+6HG6A9BxSyUABOKY
    cbxEx35BOrRu1J0P8EGe7mpoNWTufilvz4PkN8cI5DtnWvhamix6Dseju1au0izD
    qVViSPjRrDTmMUM+hItji/O5vQMHDZ4nVulrras8NlrDaTbBzq6ZMP0lpzHjFia+
    ij+Xj06+N7ojM6qDpFqEGz43PqG61XGzD4jSp3l3M5y4qggZ/R7XVB0D30iktggm
    IFC3HwEp9PaKhdEZlvbOlRODN8sLXU+hOGIRKgFjSSZkgINwb9hyEG3ZNzvgyL2A
    e0ZQerfPMKwo6sGXPP+cNuqM5Ilp/fsHlN1fF2LtGk7Qyq60U9WPYk8OQtZVy37R
    AkxmVXG/ctXwwiavo5HdSd8EMcxTI/GwLXyyfqD16Jd4Z+8dWNU8kHtCtnqJZKcN
    o7re+PwzZiCqrVHzFFknc1wW0uydItc3UyVylFPWzr1OJPi40fMyx3lUlmhFxviZ
    GsBMuEB++hCul4ksDrjaM+iVxbrYcuJ5Ibw+3tfyVUp2ihfi130s8jYhq3vhvDuk
    rk6kb/a5pJ71+0RkLBboFIPQDCkMPBGG/gaMWl0TXle4v7Rfp4fvx8JFAscI13bz
    KMkcR73XBoNGLX190rEBT3V8vUtcKDU0TfmJB7GBUgX4lO4ltAwBTjUVmxxFHahj
    3KuzFy1MLvXSmVRVx6R9TWwoqe6tOETw7BxsRMAhisAiQFeudOiFisel7ue3fTcP
    Qhh+j9IDvTmfgix0K6yf/Q7Yz/6MPJD4I1aMPuHslBC1uMoIBhlvwCsaTLCYRbgM
    3WuXZ15iE+o4toEgGravnPbFs080bUlkVDLFv3i6Eb56jkx5RlVILhXtajkNwPaf
    JW/Ex2Px9+tObfK20N0Rb++a6lcXvWRBcYN3i8N7ON8vKp7hhZeDIpIvfQ7afOJN
    O4GQaNpSJyTooCtr5fehjOGPCv3aH890Nvk0LfVxGA4TfhldezusIW3AHBSi45Vg
    xXMNguYshVpVOa3fUxyyVkA/UTge9HJQXixEdFTBAm4JSR33DrBlwg==</CipherValue>
    </CipherData>
    </EncryptedData>

    <?xml version="1.0" encoding="UTF-8"?>

    <creditcardpayment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" payerid="123456789">
    <paymentamount>800</paymentamount>
    <paymentdate>2004/04/15</paymentdate>
    <paymentdesc>This is payment for student fee</paymentdesc>
    <customer>

    <firstname>ZAHEER</firstname>
    <lastname>SHAIK</lastname>
    <address>

    <street1>7575 W 106 th St</street1>
    <street2>Apt 297</street2>
    <city>Overland park</city>
    <state>KS</state>
    <zip>66212</zip>
    </address>
    </customer>
    <creditcardinfo>
    <cardnumber>1234567891234567</cardnumber>
    <cardtype>Discover</cardtype>
    <expirydate>12/31/2004</expirydate>
    <securitycode>123</securitycode>
    </creditcardinfo>
    </creditcardpayment>

    References :

    http://www-106.ibm.com/developerworks/library/x-encrypt2/