几种加密算法

Base64加密:

1.org.apache.commons.codec,加密后没有换行

package util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;


/**
 * @todo Apache的 commons-codec.jar得到的编码字符串是不带换行符的
 * @author zhangyanan
 * @date 2018年8月7日
 */
public class CommonsCodecEncodeDecode {
    /**
     * 加密str
     * 
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s=Base64.encodeBase64String(b);
        }
        return s;
    }

    
    /**
     * 解密s
     * 
     * @param str
     * @return
     */
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            try {
                b = Base64.decodeBase64(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
View Code

2.sun.misc.BASE64,不推荐使用,加密后有换行回车

package util;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @todo BASE64加密解密类
 * @author zhangyanan
 * @date 2018年8月6日
 */
@SuppressWarnings("restriction")
public class EncodeAndDecode {
    public static void main(String[] args) {
        String base64 = getBase64("http:www.baidu.comasdfsdfcaewfsdcsdfqweafd输入1230.,。");
        String fromBase64 = getFromBase64(base64);
        System.out.println(base64);
        System.out.println();
        System.out.println(fromBase64);
        
    }

    /**
     * 加密str
     * 
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    
    /**
     * 解密s
     * 
     * @param str
     * @return
     */
    public static String getFromBase64(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 boolean GenerateImage(String base64str, String savepath) { // 对字节数组字符串进行Base64解码并生成图片
        if (base64str == null) // 图像数据为空
            return false;
        // System.out.println("开始解码");
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            // System.out.println("解码完成");
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // System.out.println("开始生成图片");
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(savepath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
View Code

3.javax.xml.bind.DatatypeConverter 推荐使用 简洁速度快,没有换行,java1.6开始内置

package util;

import javax.xml.bind.DatatypeConverter;

/**
 * @todo
 * @author zhangyanan
 * @date 2018年8月7日
 */
public class DatatypeConverterTest {
    public static void main(String[] args){
        String s="www.bai注释";
        String printBase64Binary = DatatypeConverter.printBase64Binary(s.getBytes());
        System.out.println(printBase64Binary);
        byte[] parseBase64Binary = DatatypeConverter.parseBase64Binary(printBase64Binary);
        System.out.println(new String(parseBase64Binary));
        System.out.println("----------");
    }
}
View Code

4.java.util.Base64 推荐使用,速度最快、简洁,没有换行,但要java1.8环境(@参考博客

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @todo java8 java.util.Base64测试
 * @author zhangyanan
 * @date 2018年8月7日
 */
public class TestBase64 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 编码
        String asB64 = Base64.getEncoder().encodeToString("聊聊ss33!%".getBytes("utf-8"));
        System.out.println(asB64);// 输出为: c29tZSBzdHJpbmc=
        // 解码
        byte[] asBytes = Base64.getDecoder().decode(asB64);
        System.out.println(new String(asBytes, "utf-8"));// 输出为: some string
    }
    
}
View Code

20180813:des加密解密

des加密解密算法

import java.security.*;  
import javax.crypto.*;  
  
/** 
 * DES加解密算法 
 */  
public class DES {  
  
    private static String strDefaultKey = "abcDEF123";  
    private Cipher encryptCipher = null;  
    private Cipher decryptCipher = null;  
  
  
    /** 
     * 默认构造方法,使用默认密钥 
     * @throws Exception 
     */  
    public DES() throws Exception {  
        this(strDefaultKey);  
    }  
  
  
    /** 
     * 指定密钥构造方法 
     * @param strKey 指定的密钥 
     * @throws Exception 
     */  
    public DES(String strKey) throws Exception {  
        Security.addProvider(new com.sun.crypto.provider.SunJCE());  
        Key key = getKey(strKey.getBytes());  
        encryptCipher = Cipher.getInstance("DES");  
        encryptCipher.init(Cipher.ENCRYPT_MODE, key);  
        decryptCipher = Cipher.getInstance("DES");  
        decryptCipher.init(Cipher.DECRYPT_MODE, key);  
    }  
  
  
    /** 
     * 加密字符串 
     * @param strIn 需加密的字符串 
     * @return 加密后的字符串 
     * @throws Exception 
     */  
    public String encrypt(String strIn) throws Exception {  
        return byteArr2HexStr(encrypt(strIn.getBytes()));  
    }  
      
      
    /** 
     * 加密字节数组 
     * @param arrB 需加密的字节数组 
     * @return 加密后的字节数组 
     * @throws Exception 
     */  
    public byte[] encrypt(byte[] arrB) throws Exception {  
        return encryptCipher.doFinal(arrB);  
    }  
  
      
      
    /** 
     * 解密字符串 
     * @param strIn 需解密的字符串 
     * @return 解密后的字符串 
     * @throws Exception 
     */  
    public String decrypt(String strIn) throws Exception {  
        return new String(decrypt(hexStr2ByteArr(strIn)));  
    }  
      
      
    /** 
     * 解密字节数组 
     * @param arrB 需解密的字节数组 
     * @return 解密后的字节数组 
     * @throws Exception 
     */  
    public byte[] decrypt(byte[] arrB) throws Exception {  
        return decryptCipher.doFinal(arrB);  
    }  
  
  
      
    /** 
     * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 
     * 不足8位时后面补0,超出8位只取前8位 
     * @param arrBTmp 构成该字符串的字节数组 
     * @return 生成的密钥 
     * @throws java.lang.Exception 
     */  
    private Key getKey(byte[] arrBTmp) throws Exception {  
        byte[] arrB = new byte[8];  
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {  
            arrB[i] = arrBTmp[i];  
        }  
        Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");  
        return key;  
    }  
  
      
      
    /** 
     * 将byte数组转换为表示16进制值的字符串, 
     * 如:byte[]{8,18}转换为:0813, 
     * 和public static byte[] hexStr2ByteArr(String strIn) 
     * 互为可逆的转换过程 
     * @param arrB 需要转换的byte数组 
     * @return 转换后的字符串 
     * @throws Exception 本方法不处理任何异常,所有异常全部抛出 
     */  
    public static String byteArr2HexStr(byte[] arrB) throws Exception {  
        int iLen = arrB.length;  
        StringBuffer sb = new StringBuffer(iLen * 2);  
        for (int i = 0; i < iLen; i++) {  
            int intTmp = arrB[i];  
            while (intTmp < 0) {  
                intTmp = intTmp + 256;  
            }  
            if (intTmp < 16) {  
                sb.append("0");  
            }  
            sb.append(Integer.toString(intTmp, 16));  
        }  
        return sb.toString();  
    }  
  
      
  
    /** 
     * 将表示16进制值的字符串转换为byte数组, 
     * 和public static String byteArr2HexStr(byte[] arrB) 
     * 互为可逆的转换过程 
     * @param strIn 需要转换的字符串 
     * @return 转换后的byte数组 
     * @throws Exception 本方法不处理任何异常,所有异常全部抛出 
     */  
    public static byte[] hexStr2ByteArr(String strIn) throws Exception {  
        byte[] arrB = strIn.getBytes();  
        int iLen = arrB.length;  
        byte[] arrOut = new byte[iLen / 2];  
        for (int i = 0; i < iLen; i = i + 2) {  
            String strTmp = new String(arrB, i, 2);  
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);  
        }  
        return arrOut;  
    }  
  
  
}  
View Code

加密解密工具类

/**
 * 加密解密工具类
 */
public class EncryUtil {
    
    /**
     * 使用默认密钥进行DES加密
     */
    public static String encrypt(String plainText) {
        try {
            return new DES().encrypt(plainText);
        } catch (Exception e) {
            return null;
        }
    }

    
    /**
     * 使用指定密钥进行DES解密
     */
    public static String encrypt(String plainText, String key) {
        try {
            return new DES(key).encrypt(plainText);
        } catch (Exception e) {
            return null;
        }
    }
    

    /**
     * 使用默认密钥进行DES解密
     */
    public static String decrypt(String plainText) {
        try {
            return new DES().decrypt(plainText);
        } catch (Exception e) {
            return null;
        }
    }

    
    /**
     * 使用指定密钥进行DES解密
     */
    public static String decrypt(String plainText, String key) {
        try {
            return new DES(key).decrypt(plainText);
        } catch (Exception e) {
            return null;
        }
    }
    
    public static void main(String[] args) {
        String key="3123_";
        String encrypt = encrypt("12345624389pq234@Q*&*(",key);
        System.out.println("加密的:"+encrypt);
        System.out.println("解密的:"+decrypt(encrypt,key));
    }

}
View Code

相关推荐