DES加密

简单的DES加密解密方法

import java.security.Key;

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

import org.apache.commons.codec.binary.Base64;


public class DESCodecTest
{
    public static final String ALGORITHM_DES = "DES/ECB/PKCS5Padding";

    public static String encode(String key,String data) throws Exception
    {
        return encode(key, data.getBytes());
    }

    public static String encode(String key,byte[] data) throws Exception
    {
        try
        {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(data);
            return bytes == null ? null : new String(Base64.encodeBase64(bytes));
           // return bytes;
        } catch (Exception e){
            throw new Exception(e);
        }
    }
   
   
    public static String decode(String key,String data) throws Exception
    {
        return decode(key, data.getBytes());
    }


    public static String decode(String key,byte[] data) throws Exception
    {
        try
        {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte [] bytes = cipher.doFinal(Base64.decodeBase64(data));
            return bytes == null ? null : new String(bytes);
            //return bytes;
        } catch (Exception e)
        {
            throw new Exception(e);
        }
    }
   
    public static void main(String [] args) throws Exception{
     String en = DESCodecTest.encode("20160113SS000020", "PASSWORD");
     System.out.println(en);
     String  result = DESCodecTest.decode("20160113SS000020", en);
     System.out.println(result);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值