• java 加密与解密艺术


     视频来自黑马程序员公开课

    对称加密之后的密文可能存在乱码,这些乱码无法识别,信息经过加密后会变成一串毫无规律的二进制串,此时再选择一种编码方式来展示,通常是 BASE64 格式的编码。

    为了解决这个问题,让将加密后的密文用Base64进行加密,加密之后的字符不再是乱码

    BASE64 编码是将所有信息都编码成只用大小写字母、0-9数字以及 + 和 / 64个字符表示,所有称作 BASE64。

    不同的编码所应用的场景不同,比如 UTF-8 倾向于在终端上呈现各种复杂字符包括简体、繁体中文、日文、韩文等等数据时所使用的一种编码格式。而 BASE64 编码通常用于在网络中传输较长的信息时所使用的一种编码格式。

    基于以上种种,目前较为常见的 app 与服务端交互的一套加解密、编解码流程就是:UTF-8 + AES + BASE64

    这里我们在后面将进行详细的讲解

    这里来看下面的这个案例:

    des的加密和解密

    package com.weiyuan.test;
    
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.KeySpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    public class DESCrypt {
    
        
        public static void main(String[] args) throws Exception {
            
            String input ="黑马程序员";
            String password="2222222222";
            
            byte[] desJiami = desJiami(input, password);
            //打印加密之后的数据
            System.out.println("加密之后的数据是:"+new String(desJiami));
            
            byte[] desJianMi = desJianMi(desJiami, password);
            
            System.out.println("解密之后的数据是:"+new String(desJianMi));
            
        }
        
        /**
         * DES加密
         * */
        public static byte[] desJiami(String input ,String password) throws Exception{
            
            Cipher cipher = Cipher.getInstance("DES");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密之后的数据
            byte[] encryptBytes = cipher.doFinal(input.getBytes());
            return encryptBytes;
        }
        
        /**
         * DES加密
         * */
        public static byte[] desJianMi(byte[] encryptBytes ,String password) throws Exception{
            
            Cipher cipher = Cipher.getInstance("DES");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.DECRYPT_MODE, key);
            //加密之后的数据
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return decryptBytes;
        }
    }

    这里需要特别强调的是:

    标准DES就一个密钥64位,des的加解密的密钥长度必须是8个字节,

    String password="2222222222";

    否则有问题,这里要特别的强调

    我们来看程序运行的结果:

    我们看到经过des加密之后的密文是一个乱码,为了解决这个问题,我们可以将加密之后的密文进行base64编码

    我们来看下具体的案例

     将加密之后的数据通过base64编码之后得到不是乱码,将该数据传递到后台服务器,服务器首先使用base64解码,然后再使用des解码

    package com.weiyuan.test;
    import java.io.ByteArrayOutputStream;
     
    public class Base64Util {
        private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
     
        private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60,
                61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1,
                -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };
     
        private Base64Util() {
        }
     
        /**
         * 将字节数组编码为字符串
         *
         * @param data
         */
        public static String encode(byte[] data) {
            StringBuffer sb = new StringBuffer();
            int len = data.length;
            int i = 0;
            int b1, b2, b3;
     
            while (i < len) {
                b1 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                    sb.append("==");
                    break;
                }
                b2 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                    sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                    sb.append("=");
                    break;
                }
                b3 = data[i++] & 0xff;
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
                sb.append(base64EncodeChars[b3 & 0x3f]);
            }
            return sb.toString();
        }
     
        /**
         * 灏哹ase64瀛楃�涓茶В鐮佷负瀛楄妭鏁扮粍
         *
         * @param str
         */
        public static byte[] decode(String str) throws Exception {
            byte[] data = str.getBytes("GBK");
            int len = data.length;
            ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
            int i = 0;
            int b1, b2, b3, b4;
     
            while (i < len) {
     
                /* b1 */
                do {
                    b1 = base64DecodeChars[data[i++]];
                } while (i < len && b1 == -1);
                if (b1 == -1) {
                    break;
                }
     
                /* b2 */
                do {
                    b2 = base64DecodeChars[data[i++]];
                } while (i < len && b2 == -1);
                if (b2 == -1) {
                    break;
                }
                buf.write((b1 << 2) | ((b2 & 0x30) >>> 4));
     
                /* b3 */
                do {
                    b3 = data[i++];
                    if (b3 == 61) {
                        return buf.toByteArray();
                    }
                    b3 = base64DecodeChars[b3];
                } while (i < len && b3 == -1);
                if (b3 == -1) {
                    break;
                }
                buf.write(((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2));
     
                /* b4 */
                do {
                    b4 = data[i++];
                    if (b4 == 61) {
                        return buf.toByteArray();
                    }
                    b4 = base64DecodeChars[b4];
                } while (i < len && b4 == -1);
                if (b4 == -1) {
                    break;
                }
                buf.write(((b3 & 0x03) << 6) | b4);
            }
            return buf.toByteArray();
        }
    }
    package com.weiyuan.test;
    
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.KeySpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    public class DESCrypt {
    
        
        public static void main(String[] args) throws Exception {
            
            String input ="黑马程序员";
            String password="2222222222";
            
             String desJiami = desJiami(input, password);
            //打印加密之后的数据
            System.out.println("加密之后的数据是:"+desJiami);
            
            String desJianMi = desJianMi(desJiami, password);
            
            System.out.println("解密之后的数据是:"+desJianMi);
            
        }
        
        /**
         * DES加密
         * */
        public static String desJiami(String input ,String password) throws Exception{
            
            Cipher cipher = Cipher.getInstance("DES");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密之后的数据
            byte[] encryptBytes = cipher.doFinal(input.getBytes());
            //将加密之后的数据采用base64编码
            String encode = Base64Util.encode(encryptBytes);
            return encode;
        }
        
        /**
         * DES加密
         * */
        public static String desJianMi(String encryptData ,String password) throws Exception{
            
            //首先对数据采用base64解码
            byte[] decodeString = Base64Util.decode(encryptData);
            
            Cipher cipher = Cipher.getInstance("DES");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.DECRYPT_MODE, key);
            //加密之后的数据
            byte[] decryptBytes = cipher.doFinal(decodeString);
            
            
            return new String(decryptBytes);
        }
    }

    我们来查看运行的效果

    加密之后的数据是:RlCEwNAGmkplcZ3htThDWg==
    解密之后的数据是:黑马程序员

    我们可以看到将加密之后的数据通过base64编码之后得到的数据是

    加密之后的数据是:RlCEwNAGmkplcZ3htThDWg==

    不再是乱码

    总结:结论

    des加密的密钥长度是8个字节

    des加密之后密文的长度是8个字节的整数倍

    接下来介绍AES加密算法:

    package com.weiyuan.test;
    
    import java.security.NoSuchAlgorithmException;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.SecretKeySpec;
    
    public class AESCrypt {
    
        
        /**
         * AES的加密
         * @throws NoSuchPaddingException 
         * @throws Exception 
         * 
         * */
        public static String aesEncode(String input,String password) throws Exception{
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密
            byte[] encode = cipher.doFinal(input.getBytes());
            //将加密之后的数据进行base64编码
            String encode2 = Base64Util.encode(encode);
                    
            return encode2;
        }
        
        /**
         * AES的解密
         * @throws NoSuchPaddingException 
         * @throws Exception 
         * 
         * */
        public static String aesDecode(String encodeData,String password) throws Exception{
            //首先将数据进行base64解码
            byte[] decode = Base64Util.decode(encodeData);
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            //加密
            byte[] encode = cipher.doFinal(decode);
            
                    
            return new String(encode);
        }
        
        public static void main(String[] args) throws Exception {
            String input = "欢迎来到河马程序员";
            //这里需要特别强调的是aes的密钥长度必须是16个字节
            String password = "1234567812345678";
            String aesEncode = aesEncode(input, password);
            System.out.println("aes加密之后的数据是:"+aesEncode);
            String aesDecode = aesDecode(aesEncode, password);
            System.out.println("aes解密之后的数据是:"+aesDecode);
        }
        
    }

    需要特别强调的是AES密钥长度是16个字节。des的密钥长度是8个字节

    des的密钥长度是8个字节,每个字节是8位,一共是64位,8个字节中最后一个字节不参加加密运算,只有7个字节参与运算

    接下面我们来学习对称加密的工作模式和填充模式

    cbc和ebc就是工作模式

    接下来我们重点学习下工作模式和填充模式的使用

    我们需要在Cipher cipher = Cipher.getInstance("DES");

    这里制定算法的模式

    package com.weiyuan.test;
    
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.KeySpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    public class DESCrypt {
    
        
        public static void main(String[] args) throws Exception {
            
            String input ="黑马程序员";
            String password="2222222222";
            
             String desJiami = desJiami(input, password);
            //打印加密之后的数据
            System.out.println("加密之后的数据是:"+desJiami);
            
            String desJianMi = desJianMi(desJiami, password);
            
            System.out.println("解密之后的数据是:"+desJianMi);
            
        }
        
        /**
         * DES加密
         * */
        public static String desJiami(String input ,String password) throws Exception{
            
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密之后的数据
            byte[] encryptBytes = cipher.doFinal(input.getBytes());
            //将加密之后的数据采用base64编码
            String encode = Base64Util.encode(encryptBytes);
            return encode;
        }
        
        /**
         * DES加密
         * */
        public static String desJianMi(String encryptData ,String password) throws Exception{
            
            //首先对数据采用base64解码
            byte[] decodeString = Base64Util.decode(encryptData);
            
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            cipher.init(Cipher.DECRYPT_MODE, key);
            //加密之后的数据
            byte[] decryptBytes = cipher.doFinal(decodeString);
            
            
            return new String(decryptBytes);
        }
    }

     上面我们使用的是Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    ecb模式,如果使用的是cbc模式,需要额外的iv参数,iv的长度,对于des iv长度必须是8个字节

     接下来我们来看程序的代码

    package com.weiyuan.test;
    
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.KeySpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    
    public class DESCrypt {
    
        
        public static void main(String[] args) throws Exception {
            
            String input ="黑马程序员";
            String password="2222222222";
            
             String desJiami = desJiami(input, password);
            //打印加密之后的数据
            System.out.println("加密之后的数据是:"+desJiami);
            
            String desJianMi = desJianMi(desJiami, password);
            
            System.out.println("解密之后的数据是:"+desJianMi);
            
        }
        
        /**
         * DES加密
         * */
        public static String desJiami(String input ,String password) throws Exception{
            
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            //cbc模式init需要添加额外的参数iv,des中iv的长度必须是8个字节
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, key,iv);
            //加密之后的数据
            byte[] encryptBytes = cipher.doFinal(input.getBytes());
            //将加密之后的数据采用base64编码
            String encode = Base64Util.encode(encryptBytes);
            return encode;
        }
        
        /**
         * DES加密
         * */
        public static String desJianMi(String encryptData ,String password) throws Exception{
            
            //首先对数据采用base64解码
            byte[] decodeString = Base64Util.decode(encryptData);
            
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            KeySpec keySpec = new DESKeySpec(password.getBytes());
            Key key = skf.generateSecret(keySpec);
            //cbc模式init需要添加额外的参数iv,des中iv的长度必须是8个字节
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key,iv);
            //加密之后的数据
            byte[] decryptBytes = cipher.doFinal(decodeString);
            
            
            return new String(decryptBytes);
        }
    }

    接下来我们来介绍下AES的"aES/ECB/PKCS5Padding,使用该模式需要额外的iv,iv需要是16个字节

    package com.weiyuan.test;
    
    import java.security.NoSuchAlgorithmException;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    public class AESCrypt {
    
        
        /**
         * AES的加密
         * @throws NoSuchPaddingException 
         * @throws Exception 
         * 
         * */
        public static String aesEncode(String input,String password) throws Exception{
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            //使用cbc模式,需要额外的iv,iv的长度必须是16个字节
            IvParameterSpec iv = new IvParameterSpec("1234567812345678".getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, key,iv);
            //加密
            byte[] encode = cipher.doFinal(input.getBytes());
            //将加密之后的数据进行base64编码
            String encode2 = Base64Util.encode(encode);
                    
            return encode2;
        }
        
        /**
         * AES的解密
         * @throws NoSuchPaddingException 
         * @throws Exception 
         * 
         * */
        public static String aesDecode(String encodeData,String password) throws Exception{
            //首先将数据进行base64解码
            byte[] decode = Base64Util.decode(encodeData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            //使用cbc模式,需要额外的iv,iv的长度必须是16个字节
                IvParameterSpec iv = new IvParameterSpec("1234567812345678".getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key,iv);
            //加密
            byte[] encode = cipher.doFinal(decode);
            
                    
            return new String(encode);
        }
        
        public static void main(String[] args) throws Exception {
            String input = "欢迎来到河马程序员";
            //这里需要特别强调的是aes的密钥长度必须是16个字节
            String password = "1234567812345678";
            String aesEncode = aesEncode(input, password);
            System.out.println("aes加密之后的数据是:"+aesEncode);
            String aesDecode = aesDecode(aesEncode, password);
            System.out.println("aes解密之后的数据是:"+aesDecode);
        }
        
    }

     总结:des模式:默认的填充模式是DES/ECB/PKCS5Padding

    如果是DES/CBC/PKCS5Padding,使用这种模式,需要额外的参数iv,iv的长度是8个字节

    对于AES模式:

    默认的填充模式是AES/ECB/PKCS5Padding

    如果是AES/CBC/PKCS5Padding,使用这种模式,需要额外的参数iv,iv的长度是16个字节

    二:

    对于des如果是nopadding的填充方式,要求输入的加密的原文长度必须是8个字节的整数倍,所以一般不使用nopadding的填充方式

    对于AES采用nopading的方式,要求输入的原文长度必须是16个字节的整数倍

     

  • 相关阅读:
    使用CSS3的@media来编写响应式的页面
    转帖 移动端h5页面不同尺寸屏幕适配兼容方法
    转 关于HTML5中meta name="viewport" 的用法 不同分辨率手机比例缩放
    转帖 移动前端开发之viewport的深入理解
    Python学习---字符串操作
    Python学习---基础篇
    Qt托盘程序
    MySQL常用语句
    C++模式学习------适配器模式
    C++模式学习------原型模式
  • 原文地址:https://www.cnblogs.com/kebibuluan/p/9452413.html
Copyright © 2020-2023  润新知