java常用加解密工具类

摘要:
key.getBytes():key.getBytes;sk=newSecretKeySpec;}Macmac=Mac.getInstance;mac.init;byte[]result=mac.doFinal;returnbase64;}catch{e.printStackTrace();}returnnull;}/***使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错*@paramres加密的原文*@paramalgorithm加密使用的算法名称*@paramkey加密的秘钥*@paramkeysize*@paramisEncode*@return*/privateStringkeyGeneratorES{try{KeyGeneratorkg=KeyGenerator.getInstance;if{byte[]keyBytes=charset==null?
packagecom.sh.springboottdemo2.util;


importcom.sun.org.apache.xerces.internal.impl.dv.util.Base64;

importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.Mac;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.SecretKeySpec;
importjava.security.MessageDigest;
importjava.security.SecureRandom;

public classEncryptUtil {
    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA1";
    public static final String HmacMD5 = "HmacMD5";
    public static final String HmacSHA1 = "HmacSHA1";
    public static final String DES = "DES";
    public static final String AES = "AES";

    /**编码格式;默认使用uft-8*/
    public String charset = "utf-8";
    /**DES*/
    public int keysizeDES = 0;
    /**AES*/
    public int keysizeAES = 128;

    public staticEncryptUtil me;

    privateEncryptUtil(){
        //单例
}
    //双重锁
    public staticEncryptUtil getInstance(){
        if (me==null) {
           synchronized (EncryptUtil.class) {
               if(me == null){
                   me = newEncryptUtil();
               }
           }
        }
        returnme;
    }

    /*** 使用MessageDigest进行单向加密(无密码)
     * @paramres 被加密的文本
     * @paramalgorithm 加密算法名称
     * @return
     */
    privateString messageDigest(String res,String algorithm){
        try{
            MessageDigest md =MessageDigest.getInstance(algorithm);
            byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
            returnbase64(md.digest(resBytes));
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*** 使用KeyGenerator进行单向/双向加密(可设密码)
     * @paramres 被加密的原文
     * @paramalgorithm  加密使用的算法名称
     * @paramkey 加密使用的秘钥
     * @return
     */
    privateString keyGeneratorMac(String res,String algorithm,String key){
        try{
            SecretKey sk = null;
            if (key==null) {
                KeyGenerator kg =KeyGenerator.getInstance(algorithm);
                sk =kg.generateKey();
            }else{
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                sk = newSecretKeySpec(keyBytes, algorithm);
            }
            Mac mac =Mac.getInstance(algorithm);
            mac.init(sk);
            byte[] result =mac.doFinal(res.getBytes());
            returnbase64(result);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*** 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错
     * @paramres 加密的原文
     * @paramalgorithm 加密使用的算法名称
     * @paramkey  加密的秘钥
     * @paramkeysize
     * @paramisEncode
     * @return
     */
    private String keyGeneratorES(String res,String algorithm,String key,int keysize,booleanisEncode){
        try{
            KeyGenerator kg =KeyGenerator.getInstance(algorithm);
            if (keysize == 0) {
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                kg.init(newSecureRandom(keyBytes));
            }else if (key==null) {
                kg.init(keysize);
            }else{
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                kg.init(keysize, newSecureRandom(keyBytes));
            }
            SecretKey sk =kg.generateKey();
            SecretKeySpec sks = newSecretKeySpec(sk.getEncoded(), algorithm);
            Cipher cipher =Cipher.getInstance(algorithm);
            if(isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
                returnparseByte2HexStr(cipher.doFinal(resBytes));
            }else{
                cipher.init(Cipher.DECRYPT_MODE, sks);
                return newString(cipher.doFinal(parseHexStr2Byte(res)));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String base64(byte[] res){
        returnBase64.encode(res);
    }

    /**将二进制转换成16进制 */
    public static String parseByte2HexStr(bytebuf[]) {
        StringBuffer sb = newStringBuffer();
        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());
        }
        returnsb.toString();
    }
    /**将16进制转换为二进制*/
    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);
        }
        returnresult;
    }

    /*** md5加密算法进行加密(不可逆)
     * @paramres 需要加密的原文
     * @return
     */
    publicString MD5(String res) {
        returnmessageDigest(res, MD5);
    }

    /*** md5加密算法进行加密(不可逆)
     * @paramres  需要加密的原文
     * @paramkey  秘钥
     * @return
     */
    publicString MD5(String res, String key) {
        returnkeyGeneratorMac(res, HmacMD5, key);
    }

    /*** 使用SHA1加密算法进行加密(不可逆)
     * @paramres 需要加密的原文
     * @return
     */
    publicString SHA1(String res) {
        returnmessageDigest(res, SHA1);
    }

    /*** 使用SHA1加密算法进行加密(不可逆)
     * @paramres 需要加密的原文
     * @paramkey 秘钥
     * @return
     */
    publicString SHA1(String res, String key) {
        returnkeyGeneratorMac(res, HmacSHA1, key);
    }

    /*** 使用DES加密算法进行加密(可逆)
     * @paramres 需要加密的原文
     * @paramkey 秘钥
     * @return
     */
    publicString DESencode(String res, String key) {
        return keyGeneratorES(res, DES, key, keysizeDES, true);
    }

    /*** 对使用DES加密算法的密文进行解密(可逆)
     * @paramres 需要解密的密文
     * @paramkey 秘钥
     * @return
     */
    publicString DESdecode(String res, String key) {
        return keyGeneratorES(res, DES, key, keysizeDES, false);
    }

    /*** 使用AES加密算法经行加密(可逆)
     * @paramres 需要加密的密文
     * @paramkey 秘钥
     * @return
     */
    publicString AESencode(String res, String key) {
        return keyGeneratorES(res, AES, key, keysizeAES, true);
    }

    /*** 对使用AES加密算法的密文进行解密
     * @paramres 需要解密的密文
     * @paramkey 秘钥
     * @return
     */
    publicString AESdecode(String res, String key) {
        return keyGeneratorES(res, AES, key, keysizeAES, false);
    }

    /*** 使用异或进行加密
     * @paramres 需要加密的密文
     * @paramkey 秘钥
     * @return
     */
    publicString XORencode(String res, String key) {
        byte[] bs =res.getBytes();
        for (int i = 0; i < bs.length; i++) {
            bs[i] = (byte) ((bs[i]) ^key.hashCode());
        }
        returnparseByte2HexStr(bs);
    }

    /*** 使用异或进行解密
     * @paramres 需要解密的密文
     * @paramkey 秘钥
     * @return
     */
    publicString XORdecode(String res, String key) {
        byte[] bs =parseHexStr2Byte(res);
        for (int i = 0; i < bs.length; i++) {
            bs[i] = (byte) ((bs[i]) ^key.hashCode());
        }
        return newString(bs);
    }

    /*** 直接使用异或(第一调用加密,第二次调用解密)
     * @paramres 密文
     * @paramkey 秘钥
     * @return
     */
    public int XOR(intres, String key) {
        return res ^key.hashCode();
    }

    /*** 使用Base64进行加密
     * @paramres 密文
     * @return
     */
    publicString Base64Encode(String res) {
        returnBase64.encode(res.getBytes());
    }

    /*** 使用Base64进行解密
     * @paramres
     * @return
     */
    publicString Base64Decode(String res) {
        return newString(Base64.decode(res));
    }
}

免责声明:文章转载自《java常用加解密工具类》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Golang 的 go mod 管理包Ubuntu 更换阿里云软件源(转)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

webapi获取请求地址的IP

using System.Net.Http; public static class HttpRequestMessageExtensions { private const string HttpContext = "MS_HttpContext"; private const string RemoteEndpointMessa...

玩转Android Camera开发(一):Surfaceview预览Camera,基础拍照功能完整demo

是在2012年的除夕之夜仓促完成,后来很多人指出了一些问题,琐事缠身一直没有进行升级。后来随着我自己的使用,越来越发现不出个升级版的demo是不行了。有时候就连我自己用这个demo测一些性能、功能点,用着都不顺手。当初代码是在linux下写的,弄到windows里下全是乱码。还要自己改几分钟才能改好。另外,很多人说不能正常预览,原因是我在布局里把Surfa...

springboot后端实现条件查询,要配合使用mybatis

packagecn.com.dyg.work.sqlgen; importcn.com.dyg.work.common.exception.DefException; importcn.com.dyg.work.common.utils.CamelAndUnderLineConverter; importcom.alibaba.fastjson.JSON...

FLINK基础(104): DS算子与窗口(15)多流转换算子(6) CONNECT, COMAP和COFLATMAP(2)CoProcessFunction

CoProcessFunction   对于两条输入流,DataStream API提供了CoProcessFunction这样的low-level操作。CoProcessFunction提供了操作每一个输入流的方法: processElement1()和processElement2()。   类似于ProcessFunction,这两种方法都通过Con...

【转帖】C# DllImport 系统调用使用详解 托管代码的介绍 EntryPoint的使用

1 DLLImport的使用 using System; using System.Runtime.InteropServices; //命名空间 class Example { //用DllImport 导入Win32的MessageBox函数 [DllImport("user32.dll", CharSet = CharSet.Unicode)] p...

[MyBatis]五分钟向MySql数据库插入一千万条数据 批量插入 用时5分左右

本例代码下载:https://files.cnblogs.com/files/xiandedanteng/InsertMillionComparison20191012.rar 我的数据库环境是mysql Ver 14.14 Distrib 5.6.45, for Linux (x86_64) using EditLine wrapper 这个数据库是安装...