AES加密和解码案例

AES加密和解码工具类:

/**
 * AES加密、解密类
 * 
 * @author
 * 
 */
public class AESUtils {
	static String password = "niuba123";
	static int keysiz = 128;
	static String algorithmStr = "AES";

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @return 加密后的字节数组
	 */
	public static byte[] encryptByAES(String content) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmStr);
			keyGenerator.init(keysiz, new SecureRandom(password.getBytes()));
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encyptFormat = secretKey.getEncoded();
			SecretKeySpec keySpec = new SecretKeySpec(encyptFormat,
					algorithmStr);
			Cipher cipher = Cipher.getInstance(algorithmStr);// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] decrypt(byte[] content) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmStr);
			keyGenerator.init(keysiz, new SecureRandom(password.getBytes()));
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encryptFormat = secretKey.getEncoded();
			SecretKeySpec keySpec = new SecretKeySpec(encryptFormat,
					algorithmStr);
			Cipher cipher = Cipher.getInstance(algorithmStr);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			byte[] result = cipher.doFinal(content);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
}

 AES测试:

public static void main(String[] args) {
		try {
			String testStr = "13.2";
			byte[] bytes = AESUtils.encryptByAES(testStr);
			System.out.println("加密:"+new String(bytes, "utf-8"));
			byte[] bytes2 =  AESUtils.decrypt(bytes);
			System.out.println("解密:"+new String(bytes2,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

运行结果:

加密:�q&sUKva��9N�
解密:13.2
 

你可能感兴趣的:(Java,Android开发)