对称加密解密

package cn.necsthz.cjzbapi.utils;

import java.util.Random;

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

public class DesUtil {
    //加密/解密算法/工作模式/填充方式 
    public static final String CIPHER_ALGORITHM="DES/CBC/PKCS5Padding";
    //密码
    public static final String KEY_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    //生成8位固定长密码
    public static String getKey() throws Exception{
        String sKey = "";
        Random random = new Random();
        
        for (int i=0;i<8; i++)
        {
            int ind = random.nextInt(61); 
            sKey = sKey + KEY_STRING.substring(ind,ind+1);
        }    
        return sKey;
    }
      
    //使用Base64加密 return
    private static byte[] decodeStr(String encodeStr) throws Exception{
        byte[] debytes = org.apache.commons.codec.binary.Base64.decodeBase64(new String(encodeStr).getBytes("UTF-8"));
        return debytes;  
    }

    //使用Base64加密算法加密字符串 return
    private static String encodeStr(byte[] plainText) throws Exception {
        byte[] enbytes = org.apache.commons.codec.binary.Base64.encodeBase64(plainText,false);  
        return new String(enbytes,"UTF-8");
    }
    
    /**
     *     解密
     * @param message
     * @param key
     * @return
     * @throws Exception
     */
    public static String Decrypt(String message, String key) throws Exception {
          byte[] bytesrc = decodeStr(message);
           Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
           DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
           IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
           cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);           
           byte[] retByte = cipher.doFinal(bytesrc);
           return new String(retByte,"UTF-8");
    }
    
    /**
     * 加密
     * @param message
     * @param key
     * @return
     * @throws Exception
     */
    public static String Encrypt(String message, String key) throws Exception {
           Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
           DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
           IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
           cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
           byte[] a = message.getBytes("UTF-8");
           byte[] encryptbyte = cipher.doFinal(a);
           return encodeStr(encryptbyte);
    }
}

你可能感兴趣的:(对称加密解密)