br.com.aws.odonto.utils.CipherUtil.java Source code

Java tutorial

Introduction

Here is the source code for br.com.aws.odonto.utils.CipherUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.aws.odonto.utils;

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

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 *
 * @author dawson
 */
public class CipherUtil {

    private static Base64 base64;
    private static KeyGenerator keyGenerator;
    private static SecretKey secretKey;
    private static Cipher cipher;

    static {
        try {
            base64 = new Base64(0);
            keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            secretKey = keyGenerator.generateKey();
            cipher = Cipher.getInstance("AES");
        } catch (Exception e) {
        }
    }

    public static synchronized String crypt(String str) throws Exception {
        String strCrypt = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedData = cipher.doFinal(str.getBytes());
            //System.out.println("cipher encrypt: " + new String(encryptedData));
            strCrypt = base64.encodeToString(encryptedData);
            //System.out.println("   base64 encode: " + strCrypt);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return strCrypt;
    }

    public static synchronized String decrypt(String token) throws Exception {
        String tokenDecrypt = null;
        try {
            byte[] strDecodeCipher = base64.decode(token.getBytes());
            //System.out.println("    base64 decode: "+new String(strDecodeCipher));
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedData = cipher.doFinal(strDecodeCipher);
            tokenDecrypt = new String(decryptedData);
            //System.out.println("cipher decrypt: " +tokenDecrypt);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return tokenDecrypt;
    }
}