AES encrypt - Java Security

Java examples for Security:AES

Description

AES encrypt

Demo Code

package com.java.alogrithm.helper;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.java.alogrithm.utils.Base64;


public class AESHelper {

    private static Cipher cipher = null;

    public static void main(String args[]) {

        String password = "123321123321asdfq34xcvq4r23r4a9";
        String content = "this is a test";
        byte[] encryptResult = encrypt(content, password);

        String codedtextb = Base64.encode(encryptResult);// data transfer as text
        System.out.println("Base64 format:" + codedtextb);
        encryptResult = Base64.decode(codedtextb);

        String decryptResultb = decrypt(encryptResult, password);
        System.out.println(decryptResultb);
    }/*from w w  w  .j a  v  a 2  s. com*/

    static {
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }


    public static byte[] encrypt(String message, String passWord) {


        try {
            SecretKey secretKey = new SecretKeySpec(passWord.getBytes(),
                    "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey); 
            byte[] resultBytes = cipher.doFinal(message.getBytes("UTF-8"));
            return resultBytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(byte[] messageBytes, String passWord) {
        String result = "";
        try {
            SecretKey secretKey = new SecretKeySpec(passWord.getBytes(),
                    "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey); 
            byte[] resultBytes = cipher.doFinal(messageBytes);
            result = new String(resultBytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String filter(String str) {
        String output = "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            int asc = str.charAt(i);
            if (asc != 10 && asc != 13) {
                sb.append(str.subSequence(i, i + 1));
            }
        }
        output = new String(sb);
        return output;
    }

}

Related Tutorials