AES对称加密

一、byte和hex的相互转换:

    byte->String :Hex.encodeHexString(byte[]);

    String->byte[]:Hex.decodeHex(str.toCharArray());

 二、实例代码:

package com.szy.project.test;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

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

/**对称加解密
 * @author sunzy
 */
public class AES  {

	/**秘钥*/
	private static String KEY = "wszsdaaa";
	
	/**初始化向量参数*/
	private static String IV = "reshengdeyixjhoa";
	
	public static void main(String[] args) {  
        String content="我喜欢美女";  
        try {
        	System.out.println("加密前:"+content);
        	String encrypt = encrypt(content);
			System.out.println("加密后:"+encrypt);
			System.out.println("解密后:"+decrypt(encrypt));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}  
    
	/**
	 * 加密
	 * @param content 加密信息
	 * @return
	 * @throws Exception
	 */
    public static String encrypt(String content) throws Exception{  
        KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");  
        keyGenerator.init(128, new SecureRandom(KEY.getBytes()));  
        SecretKey key=keyGenerator.generateKey();  
        Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");  
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));  
        return Hex.encodeHexString(cipher.doFinal(content.getBytes()));  
    }  
    
    /**
     * 解密
     * @param content 解密信息
     * @return
     * @throws Exception
     */
    public static String decrypt(String content) throws Exception{  
        KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");  
        keyGenerator.init(128, new SecureRandom(KEY.getBytes())); 
        SecretKey key=keyGenerator.generateKey();  
        Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");  
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));  
        return new String(cipher.doFinal(Hex.decodeHex(content.toCharArray())));  
    }  
          
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值