Encryption and Decryption in Java

Encoding vs Encryption (Both Encoding n Encryption is used in this program)

Encoding can be reversed by employing the same algorithm that encoded the content, i.e. no key is used.
Encryption requires the use of a key (kept secret) in order to return plaintext.

Download org-apache-commons-codec.jar

AesBase64Wrapper.java
  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
package com.passionatecodes.encryptionDecryption;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.Key;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/*
 Note: Encoding vs Encryption (Both Encoding n Encryption is used in this program)
 Encoding can be reversed by employing the same algorithm that encoded the content, i.e. no key is used. 
 Encryption is for maintaining data confidentiality and requires the use of a key (kept secret) 
 in order to return plaintext.
 */
public class AesBase64Wrapper {
 
  
    private static String IV = "IV_VANIC_16_BYTE"; 
    private static String PASSWORD = "PASSWNIC_VALUE"; 
    private static String SALT = "SALTNICVAL"; 
   
    //test using main method
    public static void main(String args[])
    {              
  try {
   AesBase64Wrapper aesBase64Wrapper=new AesBase64Wrapper();
      
   String text="abc";
   System.out.println("Before encryption: "+text);
   
      String encryptAndEncode=aesBase64Wrapper.encryptAndEncode(text);
         System.out.println("After encryptAndEncode: "+encryptAndEncode);
         
         String decodeAndDecrypt = aesBase64Wrapper.decodeAndDecrypt(encryptAndEncode);
   System.out.println("After decodeAndDecrypt: "+decodeAndDecrypt);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
        
     
    }
    
    public String encryptAndEncode(String raw) {
        try {         
            Cipher c = getCipher(Cipher.ENCRYPT_MODE);
            byte[] encryptedVal = c.doFinal(getBytes(raw));
            String s = getString(Base64.encodeBase64(encryptedVal));
            s = URLEncoder.encode(s, "UTF-8");  //encode                        
            return s;
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
        
    }
 
    public String decodeAndDecrypt(String encrypted) throws Exception {
     encrypted=java.net.URLDecoder.decode(encrypted, "UTF-8");  // decode
        byte[] decodedValue = Base64.decodeBase64(getBytes(encrypted));
        Cipher c = getCipher(Cipher.DECRYPT_MODE);
        byte[] decValue = c.doFinal(decodedValue);
        return new String(decValue);
    }
        
 
    private String getString(byte[] bytes) throws UnsupportedEncodingException {
        return new String(bytes, "UTF-8");
    }
 
    private byte[] getBytes(String str) throws UnsupportedEncodingException {
        return str.getBytes("UTF-8");
    }
 
    private Cipher getCipher(int mode) throws Exception {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = getBytes(IV);
        c.init(mode, generateKey(), new IvParameterSpec(iv));
        return c;
    }
 
    private Key generateKey() throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        char[] password = PASSWORD.toCharArray();
        byte[] salt = getBytes(SALT);
 
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        byte[] encoded = tmp.getEncoded();
        return new SecretKeySpec(encoded, "AES");
    }
                 
}

Output:
Before encryption: abc
After encryptAndEncode: uJnRM%2BdZWMBTmJPS1oZ%2Fmw%3D%3D
After decodeAndDecrypt: abc

No comments:

Post a Comment