aes加密解密

最近在开发时用到了aes的加密解密技术,经过一些努力将其解决了。现将其总结下来。

  1. java端
package com.example.demo.encryp;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * aes加密解密
 */
public class EncrypAES {
    // 16秘钥字符串
    private String key = "A14D6B83A4580C4A";
    // SecretKey 负责保存对称密钥
    private SecretKey deskey = new SecretKeySpec(key.getBytes(),"AES");
    // Cipher负责完成加密或解密工作
    private static Cipher c;
    static{
        try{
            c = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密
     *
     * @param str
     * @return
     */
    public String Encrytor(String str) {
        if (str == null || str.length() <= 0) {
            return "";
        }
        String r = null;
        try {
            // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
            c.init(Cipher.ENCRYPT_MODE, deskey);
            byte[] src = str.getBytes("UTF-8");
            // 加密,结果保存进cipherByte
            byte[] cipherByte = c.doFinal(src);
            r = parseByte2HexStr(cipherByte);
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException
                | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public String Decryptor(String str) {
        if (str == null || str.length() <= 0) {
            return "";
        }
        String r = "";
        try {
            // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
            byte[] buff = parseHexStr2Byte(str);
            c.init(Cipher.DECRYPT_MODE, deskey);
            byte[] cipherByte = c.doFinal(buff);
            r = new String(cipherByte, "UTF-8");
        } catch (InvalidKeyException | UnsupportedEncodingException | IllegalBlockSizeException
                | BadPaddingException e) {
            e.printStackTrace();
        }
        return r;
    }

    public static void main(String[] args) {
        EncrypAES de1 = new EncrypAES();
        String msg = "加密";
        String encontent = de1.Encrytor(msg);
        String decontent = de1.Decryptor(encontent);
        System.out.println("明文是:" + msg);
        System.out.println("加密后:" + encontent);
        System.out.println("解密后:" + decontent);
    }

    /**
     * 2进制转16进制
     *
     * @param buf
     * @return
     */
    private String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) {
                        hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 16进制转2进制
     *
     * @param hexStr
     * @return
     */
    private byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
                return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}

运行结果:
这里写图片描述
2. js端

/**
 * aes 加密 解密
 */
// 秘钥
var key = CryptoJS.enc.Utf8.parse("A14D6B83A4580C4A");

// 加密
var encrypt = function(word){  
    var srcs = CryptoJS.enc.Utf8.parse(word);  
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});  
    return encrypted.ciphertext.toString();  
};
// 解密
var decrypt = function(word){  
    word = CryptoJS.enc.Hex.parse(word);
    word = CryptoJS.enc.Base64.stringify(word);  
    var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});  
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();  
};

运行结果:
这里写图片描述

注:完整代码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值