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

Base64编码
是网络上最常见的用于传输8Bit字节代码的编码方式之一,可用于在HTTP环境下传递较长的标识信息。(来自百度百科)
运算原理:
3*8=4*6
大家都知道,计算机是8位的存数,所以计算机将字符转换成二进制后,base64则会按照6位进行抽取,这样就可以将24位字符分解成4组6位的字符,然后计算机会对每一组进行高位补0,补足8位,最后转成ascii码,再对照base64的RFC2045~RFC2049表进行转换。
base64


工具类:

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一起使用,当然还有好多的加密算法和方式,我在这里就先不介绍那么多,后续再慢慢补充。
下面贴上一篇好文:
http://www.open-open.com/lib/view/open1397274257325.html

学无止境,生生不息。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值