Base64编码与DES加密解密工具类

301次阅读
没有评论

共计 4000 个字符,预计需要花费 10 分钟才能阅读完成。

70197-gwykkafngsv.png


Base64 编码 

是网络上最常见的用于传输 8Bit 字节代码的编码方式之一,可用于在 HTTP 环境下传递较长的标识信息。(来自百度百科)

运算原理:

38=4

大家都知道,计算机是 8 位的存数,所以计算机将字符转换成二进制后,base64 则会按照 6 位进行抽取,这样就可以将 24 位字符分解成 4 组 6 位的字符,然后计算机会对每一组进行高位补 0,补足 8 位,最后转成 ascii 码,再对照 base64 的 RFC2045~RFC2049 表进行转换。

工具类:

package com.chat.util;

import java.io.UnsupportedEncodingException;

import sun.misc.*;

public class Base64Util {

    /**

     * base64 编码

     * @param 要编码的字符串

     * @return 编码后的字符串

     */

    public static String encode(String str) {byte[] b = null;

        String s = null;

        try {b = str.getBytes("utf-8");  // 获取 byte 编码

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

        }

        if (b != null) {s = new BASE64Encoder().encode(b);  // 对字符串进行编码

        }

        return s;

    }

    /**

     * base64 解码

     * @param 要解码的字符串

     * @return 解码后的字符串

     */

    public static String decode(String s) {byte[] b = null;

        String result = null;

        if (s != null) {BASE64Decoder decoder = new BASE64Decoder();

            try {b = decoder.decodeBuffer(s);

                result = new String(b, "utf-8");    // 对字符串进行解码

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

            }

        }

        return result;

    }

    public static void main(String[] args) {

        String str = " 清明上河图 ";

        System.out.println(encode(str));

        System.out.println(decode(encode(str)));

    }

}

打印结果:
5riF5piO5LiK5rKz5Zu+ 
清明上河图


DES 
对称加密算法。所谓对称加密算法即:加密和解密使用相同密钥的算法。这个就不多做介绍了,java 对 DES 加密做了封装,下面就直接贴代码。
工具类:

package com.chat.util;

import java.security.Key;

import javax.crypto.Cipher;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

public class DesUtil {

    public static final String ALGORITHM_DES = "DES";  // 指定算法名称

    public static final String SIGN_KEY = "20170313EHR";    // 指定密钥

    /**

     * DES 加密 

     * @param 要加密的字符串

     * @return 加密完成的字符串

     */

    public static String encode(String data) {if(data == null)  

            return null;  

        try{

            String key = SIGN_KEY;

            DESKeySpec dks = new DESKeySpec(key.getBytes());              

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  

            //key 的长度不能够小于 8 位字节  

            Key secretKey = keyFactory.generateSecret(dks);  

            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);  

            cipher.init(Cipher.ENCRYPT_MODE, secretKey);             

            byte[] bytes = cipher.doFinal(data.getBytes());              

            return byte2str(bytes);  

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

            return data;  

        }  

    }  

    /**

     * DES 解密 

     * @param 要解密的字符串

     * @return 解密完成的字符串

     */

    public static String decode(String data) {if(data == null)  

            return null;  

        try {  

            String key = SIGN_KEY;

            DESKeySpec dks = new DESKeySpec(key.getBytes());    

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  

            //key 的长度不能够小于 8 位字节  

            Key secretKey = keyFactory.generateSecret(dks);  // 获取 init 需要的 key

            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);  

            cipher.init(Cipher.DECRYPT_MODE, secretKey);  

            return new String(cipher.doFinal(str2byte(data.getBytes())));  

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

            return data;  

        }  

    }  

    /** 

     * 字节数组转字符串 

     * @param 字节数组

     * @return 转换之后的字符串

     */  

    private static String byte2str(byte[] b) {StringBuilder hs = new StringBuilder();  

        String stmp;  

        for (int n = 0; b!=null && n < b.length; n++) {stmp = Integer.toHexString(b[n] & 0XFF);    // 将 int 转换成 base16 的字符串,

                                                        //b[n] & 0XFF 将会判断 b[n] 的值,如果为正,则不变化,如果为负,则转换成对应的 byte 的 1~255 的值

            if (stmp.length() == 1)  

                hs.append('0');  

            hs.append(stmp);  

        }  

        return hs.toString().toUpperCase();  

    }  

     /**

      * 字符串转字节数组

      * @param 字符串的字节数组

      * @return 字节数组

      */

    private static byte[] str2byte(byte[] b) {if((b.length%2)!=0)     // 判断是否为偶数

            throw new IllegalArgumentException();  

        byte[] b2 = new byte[b.length/2];  

        for (int n = 0; n < b.length; n+=2) {String item = new String(b,n,2);  

            b2[n/2] = (byte)Integer.parseInt(item,16);  // 将字符串转换成 16 进制的 byte

        }  

        return b2;  

    } 

    public static void main(String[] args) {

        String enStr = " 贝壳 hanmu";

        System.out.println(encode(enStr));

        System.out.println(decode(encode(enStr)));

    }

}

打印结果:
C06605C127DEA39218BDF8C49B8A832D 
贝壳 hanmu

现在淡淡用一种加密的算法已经不那么安全了,很多时候 base64 会和 MD5 一起使用

转自:https://blog.csdn.net/TianXieZuoMaiKong/article/details/61931192

正文完
 
alecctv
版权声明:本站原创文章,由 alecctv 2019-11-03发表,共计4000字。
转载说明:除特殊说明外本站文章皆由ooly.cc发布,转载请注明出处。
评论(没有评论)
验证码