All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yaoqiang.util.Encryptor Maven / Gradle / Ivy

There is a newer version: 2.2.18
Show newest version
package org.yaoqiang.util;

import java.security.Key;

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

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

/**
 * Encryptor
 * 
 * @author Shi Yaoqiang([email protected])
 */
public class Encryptor {

	private static final String algorithm = "AES";
	private static final byte[] secretKey = new byte[] { 'r', 'd', 'V', 't', 'I', '=', 'a', 'y', 'W', 'S', 'e', '/', 'e', 'U', 'n', 'g' };

	public static String encrypt(String data) {
		try {
			Key key = generateKey();
			Cipher c = Cipher.getInstance(algorithm);
			c.init(Cipher.ENCRYPT_MODE, key);
			byte[] encVal = c.doFinal(data.getBytes());
			String encryptedValue = new BASE64Encoder().encode(encVal);
			return encryptedValue;
		} catch (Exception e) {
		}
		return data;
	}

	public static String decrypt(String encryptedData) {
		try {
			Key key = generateKey();
			Cipher c = Cipher.getInstance(algorithm);
			c.init(Cipher.DECRYPT_MODE, key);
			byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
			byte[] decValue = c.doFinal(decordedValue);
			String decryptedValue = new String(decValue);
			return decryptedValue;
		} catch (Exception e) {
		}
		return encryptedData;
	}

	private static Key generateKey() throws Exception {
		return new SecretKeySpec(secretKey, algorithm);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy