Java对称加密算法DES实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java对称加密算法DES实现相关的知识,希望对你有一定的参考价值。
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实现的主要内容,如果未能解决你的问题,请参考以下文章