Java 加密与解密

Java 加密与解密

package com.xu.encrypt.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

/**
 * 加密工具类
 * md5加密出来的长度是32位
 * sha加密出来的长度是40位
 */
@SuppressWarnings(value="all")
public class Encrypt {

    private static final String KEY_MAC = "HmacMD5"; 

    public static void main(String[] args) {
        //直接输入加密的类容会返回加密后的信息或秘钥
        System.out.println("encodeBase64:"+encodeBase64("a"));      //Base64加密
        System.out.println("decodeBase64:"+decodeBase64("YQ=="));   //Base64解密
        System.out.println("encodeMD5:"+encodeMD5("a"));            //MD5加密
        System.out.println("encodeHMAC:"+encodeHMAC("a"));          //HMAC加密
        System.out.println("encodeSha:"+encodeSha("a"));            //sha-1加密
        System.out.println("md5AndSha:"+md5AndSha("a"));            //加严
    }

    /**
     * 二次加密
     * @param inputText 字符串类型的加密原文(加严)
     * @return          加密后信息
     */
    public static String md5AndSha(String inputText) {
        return encodeSha(encodeMD5(inputText));
    }

    /**
     * sha-1加密
     * @param inputText 字符串类型的加密原文(sha-1加密)
     * @return          加密后信息
     */
    public static String encodeSha(String inputText) {
        return encode(inputText,"sha-1");
    }
 
    /**
     * HMAC加密
     * @param inputText 字符串类型的加密原文(HMAC加密)
     * @return          加密后信息
     */
    public static  String  encodeHMAC(String inputText){
        String  result=null;
        try {
            String key =initMacKey(); 
            result=encryptHMAC(inputText.getBytes(), key);
        } catch (Exception e) {e.printStackTrace();}  
        return result.toString();
    }
    
    /**  
     * HMAC加密:初始化HMAC密钥  
     * @return  
     * @throws Exception  
     */  
    private static String initMacKey() throws Exception {   
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);   
        SecretKey secretKey = keyGenerator.generateKey();
        return new String(secretKey.getEncoded());
    }   

    /**  
     * HMAC加密:主要方法
     * @param data  
     * @param key  
     * @return  
     * @throws Exception  
     */  
    private static String encryptHMAC(byte[] data, String key) throws Exception {   
        SecretKey secretKey = new SecretKeySpec(key.getBytes(),KEY_MAC);   
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());   
        mac.init(secretKey);
        return new String(mac.doFinal(data));   
    }  

    /**
     * md5或者sha-1加密
     * @param inputText     字符串类型的加密原文(MD5加密)
     * @param algorithmName 加密算法名称:md5或者sha-1,不区分大小写
     * @return              加密后信息
     */
    private static String encode(String inputText, String algorithmName) {
        if (inputText == null || "".equals(inputText.trim())) {
            throw new RuntimeException("请输入需要加密的信息!!!");
        }
        if (algorithmName == null || "".equals(algorithmName.trim())) {
            algorithmName = "md5";
        }
        try {
            MessageDigest m = MessageDigest.getInstance(algorithmName);
            m.update(inputText.getBytes("UTF8"));
            byte s[] = m.digest();
            // m.digest(inputText.getBytes("UTF8"));
            return hex(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param inputText 字符串类型的加密原文(MD5加密)
     * @return          加密后信息
     */
    public static String encodeMD5(String inputText){
        byte secret[] = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(inputText.getBytes("UTF8"));
            secret= digest.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hex(secret);
    }
    
    /**
     * 返回十六进制字符串
     * @param arr
     * @return
     */
    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * base64加密
     * @param inputText 字符串类型的加密原文(Base64加密)
     * @return          字符串类型的解密秘钥
     */
    public static String encodeBase64(String inputText){
        return Base64.encode(inputText.getBytes());
    }

    /**
     * base64加密
     * @param inputText 字符串类型的加密原文(Base64加密)
     * @return          字符串类型的解密秘钥
     */
    public static String encodeBase64(byte[] inputText){
        return Base64.encode(inputText);
    }

    /**
     * base64解密
     * @param inputText 字符串类型的解密秘钥(Base64解密)
     * @return          字符串类型的加密原文
     */
    public static String decodeBase64(String inputText){
        String t = null;
        try {
            t= new String(Base64.decode(inputText));
        } catch (Base64DecodingException e) {
            e.printStackTrace();
        }
        return t;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值