码迷,mamicode.com
首页 > 编程语言 > 详细

Java对称加密算法DES实现

时间:2017-07-26 21:49:20      阅读:204      评论:0      收藏:0      [点我收藏+]

标签: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实现

标签:str   factory   tin   turn   log   encode   data   param   word   

原文地址:http://www.cnblogs.com/wenhui92/p/7241774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!