您的位置:首页 > 其它

DES加密

2016-07-14 12:59 218 查看
简单的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);

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: