Java基於base64和Md5的加密解密算法代碼分享

package net.neptune.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

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

public class CodeUtil {

public static String encoding(String str) {
    
    return Base64.encodeBase64String(str.getBytes());
}

public static String encoding(String str, String charset) throws UnsupportedEncodingException {
    
    return Base64.encodeBase64String(str.getBytes(charset));
}

public static String base64Encoding(byte[] bytes) {
    
    return Base64.encodeBase64String(bytes);
}

public static String decoding(String str) {
    
    return new String(Base64.decodeBase64(str.getBytes()));
}

public static String decoding(String str, String charset) throws UnsupportedEncodingException {
    
    return new String(Base64.decodeBase64(str.getBytes()), charset);
}

public static boolean isBase64(String str) {
    
    return Base64.isBase64(str);
}

public static String md5(String s) {
    char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    
    try {
        byte[] btInput = s.getBytes();
        // 獲得MD5摘要算法的 MessageDigest 對象
        MessageDigest mdInst = MessageDigest.getInstance("MD5");
        // 使用指定的字節更新摘要
        mdInst.update(btInput);
        // 獲得密文
        byte[] md = mdInst.digest();
        // 把密文轉換成十六進制的字符串形式
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    
}

// 創建Base64對象,用於加密和解密;
private final static Base64 base64   = new Base64();

// 加密時採用的編碼方式;
private final static String encoding = "UTF-8";

/**
 * 基於MD5算法的非對稱加密(無解密算法)
 * 
 * @param strSrc 明文
 * @return 返回密文
 */
public static String encryptMd5(String strSrc) {
    String outString = null;
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] outByte = md5.digest(strSrc.getBytes("UTF-8"));
        outString = outByte.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return outString;
}

/**
 * 用Base64對加密好的byte數組進行編碼,返回字符串
 * 
 * @param str 需要加密的字符串
 * @param sKey 加密密鑰
 * @return 經過加密的字符串
 */
public static String encryptBase64(String str, String sKey) {
    // 聲明加密後的結果字符串變量
    String result = str;
    if (str != null && str.length() > 0 && sKey != null && sKey.length() >= 8) {
        try {
            // 調用DES 加密數組的 encrypt方法,返回加密後的byte數組;
            byte[] encodeByte = encryptBasedDes(str.getBytes(encoding), sKey);
            // 調用base64的編碼方法,返回加密後的字符串;
            result = base64.encodeToString(encodeByte).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

/**
 * 用Base64對字符串進行編碼,返回byte數組
 * 
 * @param str 需要解密的字符串
 * @param sKey 解密密鑰
 * @return 經過解密的字符串
 */
public static String decryptBase64(String str, String sKey) {
    String result = str;
    if (str != null && str.length() > 0 && sKey != null && sKey.length() >= 8) {
        try {
            // 用base64進行編碼,返回byte數組
            byte[] encodeByte = base64.decode(str);
            // 調用DES 解密數組的decrypte方法,返回解密後的數組;
            byte[] decoder = decryptBasedDes(encodeByte, sKey);
            // 對解密後的數組轉化成字符串
            result = new String(decoder, encoding).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

/**
 * 先用DES算法對byte[]數組加密
 * 
 * @param byteSource 需要加密的數據
 * @param sKey 加密密鑰
 * @return 經過加密的數據
 * @throws Exception
 */
private static byte[] encryptBasedDes(byte[] byteSource, String sKey) throws Exception {
    try {
        // 聲明加密模式;
        int mode = Cipher.ENCRYPT_MODE;
        // 創建密碼工廠對象;
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 把字符串格式的密鑰轉成字節數組;
        byte[] keyData = sKey.getBytes();
        // 以密鑰數組爲參數,創建密碼規則
        DESKeySpec keySpec = new DESKeySpec(keyData);
        // 以密碼規則爲參數,用密碼工廠生成密碼
        Key key = keyFactory.generateSecret(keySpec);
        // 創建密碼對象
        Cipher cipher = Cipher.getInstance("DES");
        // 以加密模式和密碼爲參數對密碼對象 進行初始化
        cipher.init(mode, key);
        // 完成最終加密
        byte[] result = cipher.doFinal(byteSource);
        // 返回加密後的數組
        return result;
    } catch (Exception e) {
        throw e;
    }
}

/**
 * 先用DES算法對byte[]數組解密
 * 
 * @param byteSource 需要解密的數據
 * @param sKey 解密密鑰
 * @return 經過解密的數據
 * @throws Exception
 */
private static byte[] decryptBasedDes(byte[] byteSource, String sKey) throws Exception {
    try {
        // 聲明解密模式;
        int mode = Cipher.DECRYPT_MODE;
        // 創建密碼工廠對象;
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 把字符串格式的密鑰轉成字節數組;
        byte[] keyData = sKey.getBytes();
        // 以密鑰數組爲參數,創建密碼規則
        DESKeySpec keySpec = new DESKeySpec(keyData);
        // 以密碼規則爲參數,用密碼工廠生成密碼
        Key key = keyFactory.generateSecret(keySpec);
        // 創建密碼對象
        Cipher cipher = Cipher.getInstance("DES");
        // 以加密模式和密碼爲參數對密碼對象 進行初始化
        cipher.init(mode, key);
        // 完成最終解密
        byte[] result = cipher.doFinal(byteSource);
        // 返回解密後的數組
        return result;
    } catch (Exception e) {
        throw e;
    }
}

/**
 * 測試對稱加密算法
 * 
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String sKey = "ningxiayinhang";
    String str = "rootroot";
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String strDate = simpleDateFormat.format(date);
    long start = new Date().getTime();
    System.out.println("開始時間:" + strDate + "   毫秒數:" + start);
    for (int i = 0; i < 1; i++) {
        String strEncrypto = CodeUtil.encryptBase64(str, sKey);
        System.out.println("被加密的字符串:" + str + "\r\n加密後的結果:" + strEncrypto);
        String strDecrypto = CodeUtil.decryptBase64(strEncrypto, sKey);
        System.out.println("解密後的結果:" + strDecrypto);
    }
    Date date2 = new Date(System.currentTimeMillis());
    String strDate2 = simpleDateFormat.format(date2);
    long start2 = new Date().getTime();
    System.out.println("結束時間:" + strDate2 + "   毫秒數:" + start2);
    long time = start2 - start;
    System.out.println("間隔時間:" + time);
    
    System.out.println("字符串【6tFt1/dtF38COK5q2gclgA==】解密之後的結果爲:"+CodeUtil.decryptBase64("6tFt1/dtF38COK5q2gclgA==", "ningxiayinhang"));
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章