对称加密之AES加密

加密和解密过程中,我们一般使用byte,因为这样不容易产生乱码,如果直接是String类型,被加密解密后的String,对中文来说,前后的Unicode是否一致,就很难保证了。

之前说了使用异或运算符加密。在Java中,有API提供,让我们实现AES对称加密。

和之前的简单加密相比,AES加密对密钥是有要求的,所以,需要设计算法,使得密钥符合要求

下面在一个类中实现AES对称加密

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

//引用下面的sun.misc.BASE64Decoder和BASE64Encoder包会有限制,不喜欢的,就加入xstream-1.4.3.jar包
import com.thoughtworks.xstream.core.util.Base64Encoder;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
/**
 * @author Administrator, 2016年4月2日 下午4:56:27
 * AES加密对长度有限制
 */
public class AESEncryption {
    private static String charset = "utf-8";

    public static String encrypt(String src, String key) {
        try {
            //创建密钥
            byte[] buf_key = key.getBytes(charset);
            //创建一个空的16位字节数组,默认0
            byte[] buf = new byte[16];
            //过短,补零;过长丢弃
            for (int i = 0; i < buf_key.length && i < buf.length; i++) {
                buf[i] = buf_key[i];
            }
            SecretKeySpec secretKey = new SecretKeySpec(buf,"AES");

            //加密
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] out = cipher.doFinal(src.getBytes(charset));

            //转为串
            return new Base64Encoder().encode(out);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String src, String key) {
        try {
            // 处理密钥
            byte[] buf_key = key.getBytes(charset);
            // 创建一个空的16位字节数组,默认0
            byte[] buf = new byte[16];
            // 过短,补零;过长丢弃
            for (int i = 0; i < buf_key.length && i < buf.length; i++) {
                buf[i] = buf_key[i];
            }
            SecretKeySpec secretKey = new SecretKeySpec(buf, "AES");

            //密码还原
            buf = new BASE64Decoder().decodeBuffer(src);

            //解密
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] out = cipher.doFinal(buf);
            //转为串
            return new String(out,charset);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String str = "eqwi&434p";
        String key = AESEncryption.encrypt(str, "Eng");
        System.out.println(key);

        String de = AESEncryption.decrypt(key, "Eng");
        System.out.println(de);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值