aes+base64加解密

aes加解密
package com.testDynamicDa.util;

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

/**
 * aes加解密
 */
public class AESUtils {

    public static final String sKey = "123456tDS0123456";

    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static 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进制转换为二进制
     * @param hexStr
     * @return
     */
    public static 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;
    }

    /**
     * 加密
     * @param sSrc 需要加密的字符串
     * 此处使用AES-128-ECB加密模式,key需要为16位。
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc) throws Exception {

        // 判断Key是否为16位
        if (sKey.length() != 16) {
            throw new Exception("Key长度不是16位");
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return parseByte2HexStr(encrypted);
        //eturn new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }

    /**
     * 解密
     * @param sSrc 需要解密的字符串
     *  此处使用AES-128-ECB加密模式,key需要为16位。
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc){
        byte[] sSrcc = parseHexStr2Byte(sSrc);
        try {
            // 判断Key是否正确
            if (sKey == null) {
                throw new Exception("Key为空null");
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                throw new Exception("Key长度不是16位");
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(sSrcc);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}

base64加解密
package com.testDynamicDa.util;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试base64加解密
 */
@Slf4j
public class TestBase64Data {

    public static void main(String[] args) {
        Map<String,Object> bodyData =  new HashMap<>(16);
        // 账号Base64加密
        String usrname = "er";
        byte[] inputBytesUsr = usrname.getBytes(StandardCharsets.UTF_8);
        byte[] encodedBytesUsr = Base64.getEncoder().encode(inputBytesUsr);
        String encodedUsrString = new String(encodedBytesUsr, StandardCharsets.UTF_8);
        bodyData.put("userName", encodedUsrString);
        // 密码Base64加密
        String password = "dw";
        byte[] inputBytesPwd = password.getBytes(StandardCharsets.UTF_8);
        byte[] encodedBytesPwd = Base64.getEncoder().encode(inputBytesPwd);
        String encodedPwdString = new String(encodedBytesPwd, StandardCharsets.UTF_8);
        bodyData.put("password", encodedPwdString);
        //解密
        byte[] decodedBytesUser = Base64.getDecoder().decode(encodedBytesUsr);
        String decodedUsrString = new String(decodedBytesUser, StandardCharsets.UTF_8);
        byte[] decodedBytesPwd = Base64.getDecoder().decode(encodedBytesPwd);
        String decodedPwdString = new String(decodedBytesPwd, StandardCharsets.UTF_8);
        log.info(System.currentTimeMillis()+"账目密码base64解密:"+decodedUsrString+"/"+decodedPwdString);

    }
    
//文件加密
public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);;
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
 
    }
 
    /**
     * 将base64字符解码保存文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
 
    public static void decoderBase64File(String base64Code, String targetPath)
           throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath+"/1.wav");
        out.write(buffer);
        out.close();
 
    }
        public static void main(String[] args) {
       try {
           String str= AudioPlayerUtils.encodeBase64File("D:/音频/2.mp3");
           String outUrl = ResourceUtils.getURL("classpath:static").getPath().replace("%20", " ").substring(1);
           AudioPlayerUtils.decoderBase64File(str,outUrl);
       }catch (Exception e){
 
       }
	/**
     * 将base64字符转换成临时音乐文件
     */
    private File base64ToFile(String base64Str) {
        FileOutputStream outputStream = null;
        if (tempFile == null || !tempFile.exists())
            try {
                tempFile = File.createTempFile("temp", ".mp3");
                byte[] audioByte = Base64.decode(base64Str, Base64.DEFAULT);
                if (tempFile != null) {
                    outputStream = new FileOutputStream(tempFile);
                    outputStream.write(audioByte, 0, audioByte.length);
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        return tempFile;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值