首页 > 其他分享 >加密工具类

加密工具类

时间:2023-06-12 15:11:17浏览次数:38  
标签:return String bytes static new 加密 工具 byte

package com.yashi.common.utils;

import javafx.util.Pair;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Base64;

/** 加密功能 **/
public final class EncryptHelper {
    private static final String SALT = "2_~!@=?=#$++%^&*:(121)";
    private static final AesAlgorithm AES = new AesAlgorithm(SALT);
    private static final DesAlgorithm DES = new DesAlgorithm(SALT);
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private static MessageDigest SHA1;
    private static MessageDigest MD5;
    static {
        try {
            SHA1 = MessageDigest.getInstance("sha1");
            MD5 = MessageDigest.getInstance("MD5");
        } catch (Exception e){
            throw new RuntimeException("no md5 algorithm error...", e);
        }
    }

    /** SHA1 混淆加密 */
    public static String cryptogram(String val) {
        if(StringHelper.isBlank(val)){
            return val;
        }
        synchronized (SHA1) {
            return toHex(SHA1.digest(BytesHelper.utf8Bytes(val + SALT)));
        }
    }

    /** SHA1 加密 **/
    public static String sha1(String val){
        if(StringHelper.isBlank(val)){
            return val;
        }
        synchronized (SHA1) {
            return toHex(SHA1.digest(BytesHelper.utf8Bytes(val)));
        }
    }

    /** MD5 加密 **/
    public static String md5(String val) {
        if(StringHelper.isBlank(val)){
            return val;
        }
        return md5(BytesHelper.utf8Bytes(val));
    }
    /** MD5 加密 **/
    public static String md5(byte[] bytes) {
        if(null == bytes || bytes.length < 1){
            return StringHelper.EMPTY;
        }
        synchronized(MD5) {
            return toHex(MD5.digest(bytes));
        }
    }

    /** MD5 加密 **/
    public static String md5(File file) {
        FileInputStream fis = null;
        DigestInputStream dis = null;
        try {
            fis = new FileInputStream(file);
            synchronized (MD5) {
                dis = new DigestInputStream(fis, MD5);
                byte[] buffer = new byte[256 * 1024];
                while (dis.read(buffer) > 0) ;
                return toHex(dis.getMessageDigest().digest());
            }
        } catch (Exception e) {
            throw new RuntimeException("File " + file.getName() + " encrypt MD5 error... ", e);
        } finally {
            BytesHelper.close(dis);
            BytesHelper.close(fis);
        }
    }

    /** AES加密字符串 **/
    public static String encryptAES(String strIn){
        try {
            return toHex(AES.encrypt(BytesHelper.utf8Bytes(strIn)));
        } catch (Exception e){
            throw new RuntimeException("AES algorithm encrypt error.....", e);
        }
    }

    /** AES解密字符串 **/
    public static String decryptAES(String strIn) {
        try {
            return new String(AES.decrypt(hex2Bytes(strIn)));
        } catch (Exception e){
            throw new RuntimeException("AES algorithm decrypt error.....", e);
        }
    }

    /** 3DES加密字符串 **/
    public static String encrypt3DES(String strIn){
        try {
            return toHex(DES.encrypt(strIn.getBytes()));
        } catch (Exception e){
            throw new RuntimeException("3DES algorithm encrypt error.....", e);
        }
    }

    /** 3DES解密字符串 **/
    public static String decrypt3DES(String strIn) {
        try {
            return new String(DES.decrypt(hex2Bytes(strIn)));
        } catch (Exception e){
            throw new RuntimeException("3DES algorithm decrypt error.....", e);
        }
    }


    /** Base64 Encode **/
    public static String encode64(String val){
        if(StringHelper.isBlank(val)){
            return val;
        }
        return BytesHelper.string(Base64.getEncoder().encode(BytesHelper.utf8Bytes(val)));
    }

    public static String encode64(byte [] bytes){
        if(null == bytes){
            return StringHelper.EMPTY;
        }
        return BytesHelper.string(Base64.getEncoder().encode(bytes));
    }

    /** Base64 decode byte[] **/
    public static byte[] decode64Bytes(String val){
        val = StringHelper.defaultString(val).replaceAll("\\s+", "");
        if(StringHelper.isBlank(val)){
            return new byte[0];
        }
        try {
            return Base64.getDecoder().decode(BytesHelper.utf8Bytes(val));
        }catch (Exception e){
            throw new RuntimeException("decode base64 error...", e);
        }
    }
    /** Base64 decode string**/
    public static String decode64String(String val){
        return BytesHelper.string(decode64Bytes(val));
    }
    /** Base64 decode InputStream **/
    public static InputStream decode64Stream(String val){
        return new ByteArrayInputStream(decode64Bytes(val));
    }

    /** 字符串转为 16 进制字符串 **/
    public static String toHex(String src) {
        if(StringHelper.isBlank(src)){
            return src;
        }
        return toHex(BytesHelper.utf8Bytes(src));
    }
    /** 字节数组转 16 进制字符串 **/
    public static String toHex(byte[] bytes) {
        char[] rs = new char[bytes.length * 2];
        for (int i = 0; i < rs.length; i = i + 2) {
            byte b = bytes[i / 2];
            rs[i] = HEX_DIGITS[(b >>> 0x4) & 0xf];
            rs[i + 1] = HEX_DIGITS[b & 0xf];
        }
        return new String(rs);
    }

    /** 16 进制字符串反解 **/
    public static String hex2String(String src) {
        if(StringHelper.isBlank(src)){
            return src;
        }
        return BytesHelper.string(hex2Bytes(src));
    }

    /** 16 进制字符串字节数组 **/
    public static byte[] hex2Bytes(String src){
        byte[] res = new byte[ src.length() / 2];
        char[] chs = src.toCharArray();
        for(int i = 0, c = 0; i < chs.length; i += 2, c++){
            res[c] = (byte) (Integer.parseInt(new String(chs,i,2), 16));
        }
        return res;
    }

    private static byte[] bytes(byte[] bytes, Cipher cipher, int times) throws IllegalBlockSizeException, BadPaddingException {
        byte[] b = bytes;
        for (int i = 0; i < times; i++) {
            b = cipher.doFinal(b);
        }
        return b;
    }
    private static Key createKey(String secret, int bits, String spec){
        byte[] bs = new byte[bits];
        byte[] bytes = BytesHelper.utf8Bytes(secret);
        for (int i = 0; i < bytes.length && i < bs.length; i++) {
            bs[i] = bytes[i];
        }
        return new SecretKeySpec(bs, spec);
    }
    private static Pair<Cipher, Cipher> initialize(String secret, String cipher, int bits, String spec) throws Exception {
        Key key = createKey(secret, bits, spec);
        Cipher encrypt = Cipher.getInstance(cipher);
        encrypt.init(Cipher.ENCRYPT_MODE, key);
        Cipher decrypt = Cipher.getInstance(cipher);
        decrypt.init(Cipher.DECRYPT_MODE, key);
        return new Pair<>(encrypt, decrypt);
    }

    private static final class AesAlgorithm {
        private static final int AES_TIMES = 1, BITS = 16;
        private static final String CIPHER = "AES/ECB/PKCS5Padding", SPEC = "AES";
        private final Cipher encryptCipher, decryptCipher;
        //指定密钥构造方法
        private AesAlgorithm(String secret) {
            try {
                Pair<Cipher, Cipher> pair = initialize(secret, CIPHER, BITS, SPEC);
                this.encryptCipher = pair.getKey(); this.decryptCipher = pair.getValue();
            } catch (Exception e){
                throw new RuntimeException("new AES algorithm error.....", e);
            }
        }

        //加密字节数组
        private byte[] encrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
            return bytes(bytes, encryptCipher, AES_TIMES);
        }
        //解密字节数组
        private byte[] decrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
            return bytes(bytes, decryptCipher, AES_TIMES);
        }
    }

    private static final class DesAlgorithm {
        private static final String CIPHER = "DES";
        private static final int DES_TIMES = 3, BITS = 8;
        private final Cipher encryptCipher, decryptCipher;
        //指定密钥构造方法
        private DesAlgorithm(String secret) {
            try {
                Pair<Cipher, Cipher> pair = initialize(secret, CIPHER, BITS, CIPHER);
                this.encryptCipher = pair.getKey(); this.decryptCipher = pair.getValue();
            } catch (Exception e){
                throw new RuntimeException("new DES algorithm error.....", e);
            }
        }
        //加密字节数组
        private byte[] encrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
            return bytes(bytes, encryptCipher, DES_TIMES);
        }
        //解密字节数组
        private byte[] decrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
            return bytes(bytes, decryptCipher, DES_TIMES);
        }
    }

    public static void main(String[] args) {
        String a="aa";
        String s = EncryptHelper.encode64(a);
        System.out.println("s = " + s);
    }
}

 

标签:return,String,bytes,static,new,加密,工具,byte
From: https://www.cnblogs.com/cjxiaozhuang/p/17475076.html

相关文章

  • 在线报表怎么做?有没有好用的在线报表工具?
    随着企业数据的不断增长,数据分析和可视化已经成为了企业决策的重要手段。而在线报表则是其中的一个重要工具。本文将介绍如何制作在线报表以及几个好用的在线报表工具。一、在线报表的制作步骤制作在线报表需要经过以下步骤:收集数据:收集所需的数据,并对其进行清理和整理,确保数据的准......
  • MySQL闪回工具简介 及 binlog2sql工具用法
    一、闪回工具简介1.工具分类第一类以patch形式集成到官方工具mysqlbinlog中优点上手成本低。mysqlbinlog原有的选项都能直接利用,只是多加了一个闪回选项,未来有可能被官方收录。支持离线解析。缺点兼容性差、项目活跃度不高。难以添加新功能,实战效果欠佳。安装麻烦。需要对m......
  • 日期工具类
    packagecom.yashi.common.utils;importlombok.extern.slf4j.Slf4j;importjava.text.DateFormat;importjava.text.ParseException;importjava.text.ParsePosition;importjava.text.SimpleDateFormat;importjava.time.LocalDate;importjava.time.LocalDateTime......
  • SM2259XT2开卡长江TAS,附SM2259XT2开卡工具,我更喜欢MAS1102量产工具
    闲的没事干,测一下59xt2+TAS,用的公版主控板,跳线按官方的来,电压给1v2,vcc不用管默认,都能用。随便焊一下,ce齐全,单颗2ce128G,单帖分布2ch/1ce。跑个rdt看看,DDR800。开卡工具是从量产部落下载的YMTC_TAS开卡工具。RDTMaxECC均在十几二十,全新自封片,还算不错体质。直接开卡,轻松开出来,容量aut......
  • 13、镜像仓库Habor的安装、高可用、https加密
    Docker之分布式仓库Harbor安装Harbor下载地址:https://github.com/vmware/harbor/releases安装要求:4CPUMEM:8GBDISK:160GB环境准备:四台主机两台主机harbor服务器,地址10.0.0.101|102两台主机harbor客户端上传和下载镜像一键安装docker、docker-compose、harbor脚本#!/bi......
  • 12、容器单机编排工具Docker Compose安装
    容器单机编排工具DockerCompose安装DockerCompose离线安装,直接从github或国内镜像站下载安装对应版本https://github.com/docker/compose/releases找到docker-compose-linux-x86_64,下载拖入linux系统[root@ubuntu2004~]#mvdocker-compose-linux-x86_64-v2.12.0/usr/bin/d......
  • 常用的webshell管理工具的流量特征 4
    一、菜刀流量特征最开始是明文传输,后来采用base64加密:PHP类WebShell链接流量如下:第一:“eval”,eval函数用于执行传递的攻击payload,这是必不可少的;第二:(base64_decode(POST[z0])),(base64decode(_POST[z0])),(base64_decode(POST[z0])),(base64ecode(_PO......
  • 报表制作很复杂?用了这款报表制作工具轻松完成报表制作
    在企业管理中,报表是非常重要的一环。然而,很多人对于报表制作却感到十分困难和繁琐。事实上,报表制作并不需要太高深的技能,只要掌握了一些基本的操作技巧和使用工具,就可以轻松地完成报表制作。而VeryReport报表制作工具则是一款非常适合初学者使用的报表制作软件。编辑搜图请点击输入......
  • leangoo领歌Scrum敏捷工具中,如何快速查看项目内所有任务卡片
    ​项目管理员能不能快捷的查看整个项目内的所有任务?能不能快捷查看项目内某一个成员的所有任务?能不能快捷的在项目内通过一些条件选择查看任务?可以导出项目内某一个人的所有任务吗?方便做一些统计等等...这些现在Leangoo领歌敏捷管理工具中都可以实现啦~查看项目内所有任务进......
  • Python工具箱系列(三十五)
    前文使用了SQLAlchemy的Core层来实现数据库、表与数据的CRUD。初步体现出了SQLAlchemy的优势。但ORM的特点没有充分地表现出来。下面的代码则从Python的类出现,生成表结构,并且进行数据的CRUD操作。fromsqlalchemyimport(Column,DateTime,Float,ForeignKey,Integer,MetaDa......