This discussion is archived
4 Replies Latest reply: Aug 28, 2008 5:34 AM by 807589 RSS

XML Encryption and Decryption

807589 Newbie
Currently Being Moderated
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import javax.crypto.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class EncrypterAndEncrypter {
     Cipher ecipher;
     Cipher dcipher;
     
     DesEncrypter(SecretKey key) {
          
          try {
               ecipher = Cipher.getInstance("DESede");
               dcipher = Cipher.getInstance("DESede");
               ecipher.init(Cipher.ENCRYPT_MODE, key);
               dcipher.init(Cipher.DECRYPT_MODE, key);
          } catch (javax.crypto.NoSuchPaddingException e) {
               System.out.println("NoSuchPaddingException-->"+e.toString());
          } catch (java.security.NoSuchAlgorithmException e) {
               System.out.println("NoSuchAlgorithmException-->"+e.toString());
          } catch (java.security.InvalidKeyException e) {
               System.out.println("InvalidKeyException-->"+e.toString());
          }
     }

     public static void main(String args[]){

          try {
               // Generate a temporary key. In practice, you would save this key.
               // See also e464 Encrypting with DES Using a Pass Phrase.
               SecretKey key = KeyGenerator.getInstance("DESede").generateKey();

               DesEncrypter encrypter = new DesEncrypter(key);

               //get the XML file to be encrypted
               String fileName = "D:/Encrypt.xml";
               Document doc = parseFile(fileName);
               String encryptValue = doc.getFirstChild().toString();
               System.out.println("encryptValue-->"+encryptValue);               
               
               
               // Encrypt
               String encrypted = encrypter.encrypt(encryptValue);
               System.out.println("Encrypted Data"+encrypted);
               
               //Save Encrypted value to disk
               String position = "D:/Encrypted.xml";
               saveEncryptedFile(encrypted, position);
               
               //get encrypted file
               String encryptedFile = loadEncryptedFile(position);
               
               // Decrypt
               String decrypted = encrypter.decrypt(encryptedFile);
               System.out.println("decrypted Data"+decrypted);

          } catch (Exception e) {
          }
     }
     
     //Get XML File to be Encrypted
     private static Document parseFile(String fileName)throws Exception {
          
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document document = db.parse(fileName);
          System.out.println("document-->"+fileName);
          
          return document;
}     

     //ENCRYPT
     public String encrypt(String str) {
          try {
               // Encode the string into bytes using utf-8
               byte[] utf8 = str.getBytes("UTF8");
          
               // Encrypt
               byte[] enc = ecipher.doFinal(utf8);
          
               // Encode bytes to base64 to get a string
               return new sun.misc.BASE64Encoder().encode(enc);
          } catch (javax.crypto.BadPaddingException e) {
               System.out.println("BadPaddingException-->"+e.toString());
          } catch (IllegalBlockSizeException e) {
               System.out.println("IllegalBlockSizeException-->"+e.toString());
          } catch (java.io.UnsupportedEncodingException e) {
               System.out.println("UnsupportedEncodingException-->"+e.toString());
          }
          return null;
     }
     
     //DECRYPT
     public String decrypt(String str) {
          try {
               // Decode base64 to get bytes
               byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
          
               // Decrypt
               byte[] utf8 = dcipher.doFinal(dec);
          
               // Decode using utf-8
               return new String(utf8, "UTF8");
          } catch (javax.crypto.BadPaddingException e) {
               System.out.println("BadPaddingException-->"+e.toString());
          } catch (IllegalBlockSizeException e) {
               System.out.println("IllegalBlockSizeException-->"+e.toString());
          } catch (java.io.UnsupportedEncodingException e) {
               System.out.println("UnsupportedEncodingException-->"+e.toString());
          } catch (java.io.IOException e) {
               System.out.println("IOException-->"+e.toString());
          }
          return null;
     }
     
     // For saving encryptedfile
public static void saveEncryptedFile(String file, String pos)
{                
     try {                 
     FileOutputStream f = new FileOutputStream(pos);
ObjectOutput s = new ObjectOutputStream(f);
s.writeObject(file);
s.flush();
     } catch (Exception e) {              
          System.out.println("Exception-->"+e.toString());
     }
}

//For loading encrypted file
public static String loadEncryptedFile(String loc) {
     
     String encryptedFile = null;
     try {              
          FileInputStream in = new FileInputStream(loc);
ObjectInputStream s = new ObjectInputStream(in);
encryptedFile = (String) s.readObject();
     } catch (Exception e) {     
          System.out.println("Exception-->"+e.toString());
     }
     return encryptedFile;
}

     
}
  • 1. Re: XML Encryption and Decryption
    807589 Newbie
    Currently Being Moderated
    Is there a question here?
  • 2. Re: XML Encryption and Decryption
    807589 Newbie
    Currently Being Moderated
    Nope...
    Just pasted for users
  • 3. Re: XML Encryption and Decryption
    807589 Newbie
    Currently Being Moderated
    leopala79 wrote:
    Nope...
    Just pasted for users
    Please don't to that unless you are very sure of yourself. That code is very poor and someone will now have to write a response to show how it should be done.
  • 4. Re: XML Encryption and Decryption
    807589 Newbie
    Currently Being Moderated
    leopala79 wrote:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutput;
    import java.io.ObjectOutputStream;
    import javax.crypto.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;

    import org.w3c.dom.Document;

    public class EncrypterAndEncrypter {
         Cipher ecipher;
         Cipher dcipher;
         
         DesEncrypter(SecretKey key) {
    Since the class name is EncrypterAndEncrypter, this constructor should not even compile.
              
              try {
                   ecipher = Cipher.getInstance("DESede");
    This defaults to a block mode of ECB with PKCS5 padding. ECB should never be used as it has many weaknesses - see section 5.2 of Practial Cryptography by Ferguson and Schneier.

    DESede is now outdated and users would do better to go for AES.
                   dcipher = Cipher.getInstance("DESede");
                   ecipher.init(Cipher.ENCRYPT_MODE, key);
                   dcipher.init(Cipher.DECRYPT_MODE, key);
              } catch (javax.crypto.NoSuchPaddingException e) {
                   System.out.println("NoSuchPaddingException-->"+e.toString());
              } catch (java.security.NoSuchAlgorithmException e) {
                   System.out.println("NoSuchAlgorithmException-->"+e.toString());
              } catch (java.security.InvalidKeyException e) {
                   System.out.println("InvalidKeyException-->"+e.toString());
              }
    This exception handing is very poor. All these exceptions represent system errors so they should be wrapped in an Error (or an Exception derived from Error) and re-thrown.
         }

         public static void main(String args[]){

              try {
                   // Generate a temporary key. In practice, you would save this key.
                   // See also e464 Encrypting with DES Using a Pass Phrase.
                   SecretKey key = KeyGenerator.getInstance("DESede").generateKey();

                   DesEncrypter encrypter = new DesEncrypter(key);

                   //get the XML file to be encrypted
                   String fileName = "D:/Encrypt.xml";
                   Document doc = parseFile(fileName);
                   String encryptValue = doc.getFirstChild().toString();
                   System.out.println("encryptValue-->"+encryptValue);               
                   
                   
                   // Encrypt
                   String encrypted = encrypter.encrypt(encryptValue);
    How does this represent XML encryption? You take the string representation of the first child and encrypt that!
                   System.out.println("Encrypted Data"+encrypted);
                   
                   //Save Encrypted value to disk
                   String position = "D:/Encrypted.xml";
                   saveEncryptedFile(encrypted, position);
                   
                   //get encrypted file
                   String encryptedFile = loadEncryptedFile(position);
                   
                   // Decrypt
                   String decrypted = encrypter.decrypt(encryptedFile);
                   System.out.println("decrypted Data"+decrypted);

              } catch (Exception e) {
              }
    Swallowing exception like this is the biggest no-no in exception handling - http://today.java.net/lpt/a/280
         }
         
         //Get XML File to be Encrypted
         private static Document parseFile(String fileName)throws Exception {
              
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);
              DocumentBuilder db = dbf.newDocumentBuilder();
              Document document = db.parse(fileName);
              System.out.println("document-->"+fileName);
              
              return document;
    }     

         //ENCRYPT
         public String encrypt(String str) {
              try {
                   // Encode the string into bytes using utf-8
                   byte[] utf8 = str.getBytes("UTF8");
              
                   // Encrypt
                   byte[] enc = ecipher.doFinal(utf8);
              
                   // Encode bytes to base64 to get a string
                   return new sun.misc.BASE64Encoder().encode(enc);
    Classes in the 'sun' package should not be used. Much better to use one of the free libraries such as Jakarta Commons Codec.
              } catch (javax.crypto.BadPaddingException e) {
                   System.out.println("BadPaddingException-->"+e.toString());
              } catch (IllegalBlockSizeException e) {
                   System.out.println("IllegalBlockSizeException-->"+e.toString());
              } catch (java.io.UnsupportedEncodingException e) {
                   System.out.println("UnsupportedEncodingException-->"+e.toString());
              }
              return null;
    Once again, really bad exception handling. By not propagating the exceptions to the calling class and returning null instead, if one of these exception does occur then it will manifest itself as a NullPointerException which will be hard to trace.
         }
         
         //DECRYPT
         public String decrypt(String str) {
              try {
                   // Decode base64 to get bytes
                   byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    Once more the use of the 'sun' private classes.
              
                   // Decrypt
                   byte[] utf8 = dcipher.doFinal(dec);
              
                   // Decode using utf-8
                   return new String(utf8, "UTF8");
              } catch (javax.crypto.BadPaddingException e) {
                   System.out.println("BadPaddingException-->"+e.toString());
              } catch (IllegalBlockSizeException e) {
                   System.out.println("IllegalBlockSizeException-->"+e.toString());
              } catch (java.io.UnsupportedEncodingException e) {
                   System.out.println("UnsupportedEncodingException-->"+e.toString());
              } catch (java.io.IOException e) {
                   System.out.println("IOException-->"+e.toString());
              }
              return null;
    Once more, piss-poor exception handling.
         }
         
         // For saving encryptedfile
    public static void saveEncryptedFile(String file, String pos)
    {                
         try {                 
         FileOutputStream f = new FileOutputStream(pos);
    ObjectOutput s = new ObjectOutputStream(f);
    s.writeObject(file);
    s.flush();
         } catch (Exception e) {              
              System.out.println("Exception-->"+e.toString());
         }
    }
    This does not do as it says on the can. The 'file' argument is not the file name but the file content! The 'pos' argument is the file name! Why do you serialize the file in order to save it?

    Once more poor exception handling.

    >
    //For loading encrypted file
    public static String loadEncryptedFile(String loc) {
         
         String encryptedFile = null;
         try {              
              FileInputStream in = new FileInputStream(loc);
    ObjectInputStream s = new ObjectInputStream(in);
    encryptedFile = (String) s.readObject();
         } catch (Exception e) {     
              System.out.println("Exception-->"+e.toString());
         }
         return encryptedFile;
    }
    Same basic comments as for the saveEncryptedFile() method.
         
    }
    There is a specification for encrypting XML - http://www.w3.org/TR/xmlenc-core/ and there is a Java implementation from Apache http://xml.apache.org/ which has many examples.

    Edited by: sabre150 on Aug 28, 2008 1:32 PM