標籤:str factory tin turn log encode data param word
import java.util.Base64;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;public class SecurityUtil { private static final String PASSWORD = "DES20170726202423156END"; private static final String ALGORITHM = "DES/CBC/PKCS5Padding"; private static final byte[] iv = {1,2,3,4,5,6,7,8}; /** * 加密 * @param data * @return * @throws Exception */ public static String encrypt(String data) throws Exception{ if(data==null||data.length()==0){ return ""; } IvParameterSpec param = new IvParameterSpec(iv); DESKeySpec desKey = new DESKeySpec(PASSWORD.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey, param); byte[] bytes = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(bytes); } /** * 解密 * @param data * @return * @throws Exception */ public static String decrypt(String data) throws Exception{ if(data==null||data.length()==0){ return ""; } IvParameterSpec param = new IvParameterSpec(iv); DESKeySpec desKey = new DESKeySpec(PASSWORD.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey, param); byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(data.getBytes())); return new String(bytes); }
Java對稱式加密演算法DES實現