zoukankan      html  css  js  c++  java
  • java-----DES加密解密

    DES简介:

             DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,DES是一个分组加密算法,典型的DES以64位为分组对数据加密,加密和解密用的是同一个算法。它的密钥长度是56位(因为每个第8 位都用作奇偶校验),密钥可以是任意的56位的数,而且可以任意时候改变。其中有极少数被认为是易破解的弱密钥,但是很容易避开它们不用。所以保密性依赖于密钥。需要注意的是,在某些文献中,作为算法的DES称为数据加密算法(Data Encryption Algorithm,DEA),已与作为标准的DES区分开来。

    DES算法入口参数

             DES算法的入口参数有三个:Key、Data、Mode。其中Key为7个字节共56位,是DES算法的工作密钥;Data为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。

    DES基本原则

    DES设计中使用了分组密码设计的两个原则:混淆(confusion)和扩散(diffusion),其目的是抗击敌手对密码系统的统计分析。混淆是使密文的统计特性与密钥的取值之间的关系尽可能复杂化,以使密钥和明文以及密文之间的依赖性对密码分析者来说是无法利用的。扩散的作用就是将每一位明文的影响尽可能迅速地作用到较多的输出密文位中,以便在大量的密文中消除明文的统计结构,并且使每一位密钥的影响尽可能迅速地扩展到较多的密文位中,以防对密钥进行逐段破译。

    算法步骤

    DES算法把64位的明文输入块变为64位的密文输出块,它所使用的密钥也是64位(实际用到了56位,第8、 16、24、32、40、48、56、64位是校验位, 使得每个密钥都有奇数个1),其算法主要分为两步:

    1)初始置换

    其功能是把输入的64位数据块按位重新组合,并把输出分为L0、R0两部分,每部分各长32位,其置换规则为将输入的第58位换到第一位,第50位换到第2位……依此类推,最后一位是原来的第7位。L0、R0则是换位输出后的两部分,L0是输出的左32位,R0是右32位,例:设置换前的输入值为D1D2D3……D64,则经过初始置换后的结果为:L0=D58D50……D8;R0=D57D49……D7。

    其置换规则见下表:

    58,50,42,34,26,18,10,2,

    60,52,44,36,28,20,12,4,

    62,54,46,38,30,22,14,6,

    64,56,48,40,32,24,16,8,

    57,49,41,33,25,17,9,1,

    59,51,43,35,27,19,11,3,

    61,53,45,37,29,21,13,5,

    63,55,47,39,31,23,15,7,

    2)逆置换

    经过16次迭代运算后,得到L16、R16,将此作为输入,进行逆置换,逆置换正好是初始置换的逆运算,由此即得到密文输出。

    此算法是对称加密算法体系中的代表,在计算机网络系统中广泛使用。

     

    DES与3DES

    编辑

    3DES(即Triple DES)是DES向AES过渡的加密算法,它使用3条56位的密钥对数据进行三次加密。是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加密算法。比起最初的DES,3DES更为安全。

    该方法使用两个密钥,执行三次DES算法,加密的过程是加密-解密-加密,解密的过程是解密-加密-解密。

    3DES加密过程为:C=Ek3(Dk2(Ek1(P)))

    3DES解密过程为:P=Dk1(EK2(Dk3(C)))

    采用两个密钥进行三重加密的好处有:

    ①两个密钥合起来有效密钥长度有112bit,可以满足商业应用的需要,若采用总长为168bit的三个密钥,会产生不必要的开销。

    ②加密时采用加密-解密-加密,而不是加密-加密-加密的形式,这样有效的实现了与现有DES系统的向后兼容问题。因为当K1=K2时,三重DES的效果就和原来的DES一样,有助于逐渐推广三重DES。

    ③三重DES具有足够的安全性,目前还没有关于攻破3DES的报道。

    详细介绍参考:http://blog.chinaunix.net/uid-29106641-id-4032988.html

    DESUtil类:

    package com.lz.test;
    
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException; 
    import java.security.NoSuchAlgorithmException; 
    import java.security.SecureRandom; 
    import java.security.spec.InvalidKeySpecException;   
    import javax.crypto.BadPaddingException; 
    import javax.crypto.Cipher; 
    import javax.crypto.IllegalBlockSizeException; 
    import javax.crypto.KeyGenerator; 
    import javax.crypto.NoSuchPaddingException; 
    import javax.crypto.SecretKey; 
    import javax.crypto.SecretKeyFactory; 
    import javax.crypto.spec.DESKeySpec; 
    
    public class DESUtil {
        /** 安全密钥 */
        private String keyData = "1f4$1eg14#23423#gjkd3#sdf2#";
    
        /**
         * 功能:构造
         * 
         * @author lizhen
         * @date 2017-11-03
         */
        public DESUtil() {
        }
    
        /**
         * 功能:构造
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param keyData
         *  key
         */
        public DESUtil(String key) {
            this.keyData = key;
        }
    
        /**
         * 功能:加密 (UTF-8)
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param source
         *  源字符串
         * @param charSet
         *  编码
         * @return String
         * @throws UnsupportedEncodingException
         *  编码异常
         */
        public String encrypt(String source) throws UnsupportedEncodingException {
            return encrypt(source, "UTF-8");
        }
    
        /**
         * 
         * 功能:解密 (UTF-8)
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param encryptedData
         *  被加密后的字符串
         * @return String
         * @throws UnsupportedEncodingException
         *  编码异常
         */
        public String decrypt(String encryptedData)
                throws UnsupportedEncodingException {
            return decrypt(encryptedData, "UTF-8");
        }
    
        /**
         * 功能:加密
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param source
         *  源字符串
         * @param charSet
         *  编码
         * @return String
         * @throws UnsupportedEncodingException
         *  编码异常
         */
        public String encrypt(String source, String charSet)
                throws UnsupportedEncodingException {
            String encrypt = null;
            byte[] ret = encrypt(source.getBytes(charSet));
            encrypt = new String(Base64.encode(ret));
            return encrypt;
        }
    
        /**
         * 
         * 功能:解密
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param encryptedData
         *  被加密后的字符串
         * @param charSet
         *  编码
         * @return String
         * @throws UnsupportedEncodingException
         *  编码异常
         */
        public String decrypt(String encryptedData, String charSet)
                throws UnsupportedEncodingException {
            String descryptedData = null;
            byte[] ret = descrypt(Base64.decode(encryptedData.toCharArray()));
            descryptedData = new String(ret, charSet);
            return descryptedData;
        }
    
        /**
         * 加密数据 用生成的密钥加密原始数据
         * 
         * @param primaryData
         *  原始数据
         * @return byte[]
         * @author lizhen
         * @date 2017-11-03
         */
        private byte[] encrypt(byte[] primaryData) {
    
            /** 取得安全密钥 */
            byte rawKeyData[] = getKey();
    
            /** DES算法要求有一个可信任的随机数源 */
            SecureRandom sr = new SecureRandom();
    
            /** 使用原始密钥数据创建DESKeySpec对象 */
            DESKeySpec dks = null;
            try {
                dks = new DESKeySpec(keyData.getBytes());
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
    
            /** 创建一个密钥工厂 */
            SecretKeyFactory keyFactory = null;
            try {
                keyFactory = SecretKeyFactory.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
    
            /** 用密钥工厂把DESKeySpec转换成一个SecretKey对象 */
            SecretKey key = null;
            try {
                key = keyFactory.generateSecret(dks);
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }
    
            /** Cipher对象实际完成加密操作 */
            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
    
            /** 用密钥初始化Cipher对象 */
            try {
                cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
    
            /** 正式执行加密操作 */
            byte encryptedData[] = null;
            try {
                encryptedData = cipher.doFinal(primaryData);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
    
            /** 返回加密数据 */
            return encryptedData;
        }
    
        /**
         * 用密钥解密数据
         * 
         * @param encryptedData
         *  加密后的数据
         * @return byte[]
         * @author lizhen
         * @date 2017-11-03
         */
        private byte[] descrypt(byte[] encryptedData) {
    
            /** DES算法要求有一个可信任的随机数源 */
            SecureRandom sr = new SecureRandom();
    
            /** 取得安全密钥 */
            byte rawKeyData[] = getKey();
    
            /** 使用原始密钥数据创建DESKeySpec对象 */
            DESKeySpec dks = null;
            try {
                dks = new DESKeySpec(keyData.getBytes());
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
    
            /** 创建一个密钥工厂 */
            SecretKeyFactory keyFactory = null;
            try {
                keyFactory = SecretKeyFactory.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
    
            /** 用密钥工厂把DESKeySpec转换成一个SecretKey对象 */
            SecretKey key = null;
            try {
                key = keyFactory.generateSecret(dks);
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }
    
            /** Cipher对象实际完成加密操作 */
            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
    
            /** 用密钥初始化Cipher对象 */
            try {
                cipher.init(Cipher.DECRYPT_MODE, key, sr);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
    
            /** 正式执行解密操作 */
            byte decryptedData[] = null;
            try {
                decryptedData = cipher.doFinal(encryptedData);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
    
            return decryptedData;
        }
    
        /**
         * 取得安全密钥 此方法作废,因为每次key生成都不一样导致解密加密用的密钥都不一样, 从而导致Given final block not
         * properly padded错误.
         * 
         * @return byte数组
         * @author lizhen
         * @date 2017-11-03
         */
        private byte[] getKey() {
    
            /** DES算法要求有一个可信任的随机数源 */
            SecureRandom sr = new SecureRandom();
    
            /** 为我们选择的DES算法生成一个密钥生成器对象 */
            KeyGenerator kg = null;
            try {
                kg = KeyGenerator.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            kg.init(sr);
    
            /** 生成密钥工具类 */
            SecretKey key = kg.generateKey();
    
            /** 生成密钥byte数组 */
            byte rawKeyData[] = key.getEncoded();
    
            return rawKeyData;
        }
    
    }

    Base64类:

    package com.lz.test;
    
    import java.io.*;
    
    
    public class Base64 {
    
        public Base64() {
        }
    
        /**
         * 功能:编码字符串
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param data
         *  源字符串
         * @return String
         */
        public static String encode(String data) {
            return new String(encode(data.getBytes()));
        }
    
        /**
         * 功能:解码字符串
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param data
         *  源字符串
         * @return String
         */
        public static String decode(String data) {
            return new String(decode(data.toCharArray()));
        }
    
        /**
         * 功能:编码byte[]
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param data
         *  源
         * @return char[]
         */
        public static char[] encode(byte[] data) {
            char[] out = new char[((data.length + 2) / 3) * 4];
            for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
                boolean quad = false;
                boolean trip = false;
    
                int val = (0xFF & (int) data[i]);
                val <<= 8;
                if ((i + 1) < data.length) {
                    val |= (0xFF & (int) data[i + 1]);
                    trip = true;
                }
                val <<= 8;
                if ((i + 2) < data.length) {
                    val |= (0xFF & (int) data[i + 2]);
                    quad = true;
                }
                out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
                val >>= 6;
                out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
                val >>= 6;
                out[index + 1] = alphabet[val & 0x3F];
                val >>= 6;
                out[index + 0] = alphabet[val & 0x3F];
            }
            return out;
        }
    
        /**
         * 功能:解码
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param data
         *  编码后的字符数组
         * @return byte[]
         */
        public static byte[] decode(char[] data) {
    
            int tempLen = data.length;
            for (int ix = 0; ix < data.length; ix++) {
                if ((data[ix] > 255) || codes[data[ix]] < 0) {
                    --tempLen; // ignore non-valid chars and padding
                }
            }
            // calculate required length:
            // -- 3 bytes for every 4 valid base64 chars
            // -- plus 2 bytes if there are 3 extra base64 chars,
            // or plus 1 byte if there are 2 extra.
    
            int len = (tempLen / 4) * 3;
            if ((tempLen % 4) == 3) {
                len += 2;
            }
            if ((tempLen % 4) == 2) {
                len += 1;
    
            }
            byte[] out = new byte[len];
    
            int shift = 0; // # of excess bits stored in accum
            int accum = 0; // excess bits
            int index = 0;
    
            // we now go through the entire array (NOT using the 'tempLen' value)
            for (int ix = 0; ix < data.length; ix++) {
                int value = (data[ix] > 255) ? -1 : codes[data[ix]];
    
                if (value >= 0) { // skip over non-code
                    accum <<= 6; // bits shift up by 6 each time thru
                    shift += 6; // loop, with new bits being put in
                    accum |= value; // at the bottom.
                    if (shift >= 8) { // whenever there are 8 or more shifted in,
                        shift -= 8; // write them out (from the top, leaving any
                        out[index++] = // excess at the bottom for next iteration.
                        (byte) ((accum >> shift) & 0xff);
                    }
                }
            }
    
            // if there is STILL something wrong we just have to throw up now!
            if (index != out.length) {
                throw new Error("Miscalculated data length (wrote " + index
                        + " instead of " + out.length + ")");
            }
    
            return out;
        }
    
        /**
         * 功能:编码文件
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param file
         *  源文件
         */
        public static void encode(File file) throws IOException {
            if (!file.exists()) {
                System.exit(0);
            }
    
            else {
                byte[] decoded = readBytes(file);
                char[] encoded = encode(decoded);
                writeChars(file, encoded);
            }
            file = null;
        }
    
        /**
         * 功能:解码文件。
         * 
         * @author lizhen
         * @date 2017-11-03
         * @param file
         *  源文件
         * @throws IOException
         */
        public static void decode(File file) throws IOException {
            if (!file.exists()) {
                System.exit(0);
            } else {
                char[] encoded = readChars(file);
                byte[] decoded = decode(encoded);
                writeBytes(file, decoded);
            }
            file = null;
        }
    
        //
        // code characters for values 0..63
        //
        private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
                .toCharArray();
    
        //
        // lookup table for converting base64 characters to value in range 0..63
        //
        private static byte[] codes = new byte[256];
        static {
            for (int i = 0; i < 256; i++) {
                codes[i] = -1;
                // LoggerUtil.debug(i + "&" + codes[i] + " ");
            }
            for (int i = 'A'; i <= 'Z'; i++) {
                codes[i] = (byte) (i - 'A');
                // LoggerUtil.debug(i + "&" + codes[i] + " ");
            }
    
            for (int i = 'a'; i <= 'z'; i++) {
                codes[i] = (byte) (26 + i - 'a');
                // LoggerUtil.debug(i + "&" + codes[i] + " ");
            }
            for (int i = '0'; i <= '9'; i++) {
                codes[i] = (byte) (52 + i - '0');
                // LoggerUtil.debug(i + "&" + codes[i] + " ");
            }
            codes['+'] = 62;
            codes['/'] = 63;
        }
    
        private static byte[] readBytes(File file) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] b = null;
            InputStream fis = null;
            InputStream is = null;
            try {
                fis = new FileInputStream(file);
                is = new BufferedInputStream(fis);
                int count = 0;
                byte[] buf = new byte[16384];
                while ((count = is.read(buf)) != -1) {
                    if (count > 0) {
                        baos.write(buf, 0, count);
                    }
                }
                b = baos.toByteArray();
    
            } finally {
                try {
                    if (fis != null)
                        fis.close();
                    if (is != null)
                        is.close();
                    if (baos != null)
                        baos.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
    
            return b;
        }
    
        private static char[] readChars(File file) throws IOException {
            CharArrayWriter caw = new CharArrayWriter();
            Reader fr = null;
            Reader in = null;
            try {
                fr = new FileReader(file);
                in = new BufferedReader(fr);
                int count = 0;
                char[] buf = new char[16384];
                while ((count = in.read(buf)) != -1) {
                    if (count > 0) {
                        caw.write(buf, 0, count);
                    }
                }
    
            } finally {
                try {
                    if (caw != null)
                        caw.close();
                    if (in != null)
                        in.close();
                    if (fr != null)
                        fr.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
    
            return caw.toCharArray();
        }
    
        private static void writeBytes(File file, byte[] data) throws IOException {
            OutputStream fos = null;
            OutputStream os = null;
            try {
                fos = new FileOutputStream(file);
                os = new BufferedOutputStream(fos);
                os.write(data);
    
            } finally {
                try {
                    if (os != null)
                        os.close();
                    if (fos != null)
                        fos.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    
        private static void writeChars(File file, char[] data) throws IOException {
            Writer fos = null;
            Writer os = null;
            try {
                fos = new FileWriter(file);
                os = new BufferedWriter(fos);
                os.write(data);
    
            } finally {
                try {
                    if (os != null)
                        os.close();
                    if (fos != null)
                        fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    }

    test测试类:

    package com.lz.test;
    
    import java.io.UnsupportedEncodingException;
    
    public class test {
        public static void main(String[] args) throws UnsupportedEncodingException {
            String uit="1234567893";
            String str =new  DESUtil().encrypt(uit, "utf-8");
            System.out.println(str);
            System.out.println(new  DESUtil().decrypt(str, "utf-8"));
        }
    }
  • 相关阅读:
    一种针对SOA的消息类型架构
    许可方式 到底"非商业用途"意味着什么?
    Windows 7的CMD中 Telnet 无法执行的解决办法
    ASP.NET MVC 2.0 中文正式版发布
    什么是REST?
    架构、框架的区别
    Firefox 火狐下自动刷新的插件 ReloadEvery
    ASP.NET与JQUERY的AJAX文件上传 视频课件+源码Demo
    给吸烟的园友们:一个被烟草行业隐瞒了十年的秘密,烟真不是人吸的
    Echo Server,AsyncSocket,SocketAsyncEvent,SocketAsyncEventArgs,AsyncQueue
  • 原文地址:https://www.cnblogs.com/lizhen-home/p/7776931.html
Copyright © 2011-2022 走看看