November 17, 2014

Java DES Encryption/Descryption Example

Sometimes we need to encrypt data and save it for later usage.

I have tried several ways and I found a suitable way for my situation that may not fit for others.
I have used the DES (AES may have more features)

Here is my example:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESEncryptionSample2 {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DES_ENCRYPTION_SCHEME = "DES";
    private KeySpec myKeySpec;
    private SecretKeyFactory mySecretKeyFactory;
    private Cipher cipher;
    byte[] keyAsBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public DESEncryptionSample2() throws Exception {
        myEncryptionKey = "ThisIsSecretEncryptionKey";
        myEncryptionScheme = DES_ENCRYPTION_SCHEME;
        keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        myKeySpec = new DESKeySpec(keyAsBytes);
        mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    }

    /**
     * Method To Encrypt The String
     */
    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            BASE64Encoder base64encoder = new BASE64Encoder();
            encryptedString = base64encoder.encode(encryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }

    /**
     * Method To Decrypt An Ecrypted String
     */
    public String decrypt(String encryptedString) {
        String decryptedText = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText = bytes2String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }

    /**
     * Returns String From An Array Of Bytes
     */
    private static String bytes2String(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        return stringBuffer.toString();
    }

    public static void saveEncrypted(String value) {
        try {
            File file = new File("Encrypted.txt");
            IOUtils.write(value, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readEncrypted() {
        try {
            File file = new File("Encrypted.txt");
            // return IOUtils.toByteArray(new FileInputStream(file));
            return IOUtils.toString(new FileInputStream(file));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * Testing the DES Encryption And Decryption Technique
     */
    public static void main(String args[]) throws Exception {
        DESEncryptionSample2 myEncryptor = new DESEncryptionSample2();

        String stringToEncrypt = "10.100.102.5";
        String encrypted = myEncryptor.encrypt(stringToEncrypt);
        System.out.println("Encrypted Value :" + encrypted);
        saveEncrypted(encrypted);

        System.out.println(readEncrypted());

        // String decrypted = myEncryptor.decrypt(encrypted);
        String decrypted = myEncryptor.decrypt(readEncrypted());

        System.out.println("String To Encrypt: " + stringToEncrypt);

        System.out.println("Decrypted Value :" + decrypted);

    }
}

March 24, 2014

Create join table with JPA annotations

Problem:

Need to create a join table in database using JPA annotations so the DATABASE design as follows:
 and it should be like this in JPA level:

Solution:

Default entities implementation:
@Entity
@Table(name="USER")
public class User implements Serializable {
//...

@ManyToOne
@JoinTable(name="USER_GROUP")
Group group;

@Entity
@Table(name="GROUP")
public class Group implements Serializable {
//...

@OneToMany(mappedBy="group")
Set<User> users;

Changes on User entity as follows:

@Entity
@Table(name="USER")
public class User implements Serializable {
//...
@ManyToOne @JoinTable(name="USER_GROUP",     joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),     inverseJoinColumns = @JoinColumn(name = "group_id", referencedColumnName = "group_id")) Group group;

Primefaces + EJB + JPA Template Project

The best project template for Primefaces + EJB + JPA and Maven I worked with.



March 23, 2014

Add Microsoft SQL JDBC driver to Maven


1. Download the JDBC driver for Microsoft SQL Server
Visit the MSDN site for SQL Server and download the latest version of the JDBC driver for your operating system.
2. Unzip the package
3. Open a command prompt and switch into the expanded directory where the jar file is located.
4. Execute the following command. Be sure to modify the jar file name and version as necessary:

mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0

5. Modify your POM
Include the new dependency by modifying your project’s pom.xml. Add the following dependency:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc4</artifactId>
    <version>4.0</version>
</dependency>

March 2, 2014

replace special characters with HTML entities ONLINE

Great website for replace special characters with HTML entities ONLINE

http://www.htmlescape.net/htmlescape_tool.html

Arabic (UTF-8) Characters encoding Issue in JSF applications

Problem:

Some times when you develop a web application using JSF you face issue posting the Arabic characters to application server with different encoding.

Solution:
Create a filter for POST requests that add character encoding to the post request as follow:

@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException   {
     request.setCharacterEncoding("UTF-8");
     chain.doFilter(request, response);
  }

  @override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

And for the GET requests you need to update the application server's deployment descriptor.
In glass fish as example, create glassfish-web.xml file under WEB-INF folder and add the following line:


<parameter-encoding default-charset="UTF-8">