1. 程式人生 > >Des 加密演算法java工具類

Des 加密演算法java工具類

package com.lock.demo.service;

import org.apache.tomcat.util.codec.binary.Base64;

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

/**
 * @author niunafei
 * @function
 *         des 對稱性演算法加密 解密工具類 可逆性演算法
 * @email 
[email protected]
* @date 2018/12/12 下午2:05
*/ public class DesUtils { private static final String DES="DES"; /** * 公鑰 8位以上 */ private static final String SECRET_KEY="12345678"; /** * 獲取祕鑰物件 * @return * @throws Exception */ private static final SecretKey getSecretKeyFactory() throws
Exception { SecretKeyFactory des = SecretKeyFactory.getInstance(DES); SecretKey secretKey = des.generateSecret(new DESKeySpec(SECRET_KEY.getBytes())); return secretKey; } /** * 加密 * @param param * @return * @throws Exception */ public static
final String encryption(String param) throws Exception { Cipher cipher = Cipher.getInstance(DES); SecretKey secretKey = getSecretKeyFactory(); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return new String(Base64.encodeBase64(cipher.doFinal(param.toString().getBytes()))); } /** * 解密 * @param value * @return * @throws Exception */ public static final String decrypt(String value) throws Exception { Cipher cipher = Cipher.getInstance(DES); SecretKey secretKey = getSecretKeyFactory(); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes()))); } /** 測試 */ public static void main(String[] args) throws Exception { String key="123"; System.out.println(" key="+key); //輸出 key=123 String value=DesUtils.encryption(key); System.out.println("encryption value="+value); //輸出 encryption value=LDiFUdf0iew= System.out.println("decrypt key="+DesUtils.decrypt(value)); //輸出 decrypt key=123 } }

 

 

比較簡單無腦~~~~~