aes 加密算法。

  • 在以前公司时。使用过sum4加密算法,但是原来demo找不到了。这次在新的公司需要加密。关于对对称加密的选择。我选择了AES算法来加密。
  • 废话我也多说了。直接上代码。
  • /**将16进制转换为二进制
    <ul><li>@param hexStr </li>
    <li>@return
    */
    public static byte[] parseHexStr2Byte(String hexStr) {
    if (hexStr.length() < 1)
    return null;
    byte[] result = new byte[hexStr.length()/2];
    for (int i = 0;i< hexStr.length()/2; i++) {
    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
    result[i] = (byte) (high * 16 + low);
    }
    return result;
    }
    /**将二进制转换成16进制 </li>
    <li>@param buf </li>
    <li>@return
    */
    public static String parseByte2HexStr(byte buf[]) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buf.length; i++) {
    String hex = Integer.toHexString(buf[i] & 0xFF);
    if (hex.length() == 1) {
    hex = '0' + hex;
    }
    sb.append(hex.toUpperCase());
    }
    return sb.toString();
    }
  • 存到数据库存的是16进制。所以这边需要一个二进制和16进制的转换。
  • 加密:

    
        /***
         * 将加密之后的密文转换成 16 进制
         * @param content
         * @param password
         * @return
         *
         */
        public static String encrypt216Hex(String content, String password) {
            if(StringUtils.isBlank(content)){
                return "";
            }
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
                SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(password.getBytes());
                kgen.init(128, random);// 利用用户密码作为随机数初始化出
                                                                        // 128位的key生产者
                //加密没关系,SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
    
                SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
    
                byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回
                                                                // null。
    
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
    
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    
    
    
                byte[] byteContent = content.getBytes("utf-8");
    
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
    
                byte[] result = cipher.doFinal(byteContent);// 加密
                String parseByte2HexStr = parseByte2HexStr(result);
                return parseByte2HexStr;
    
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }

    解密:

      /**
         * 传入16进制的密文 然后解密
         * @param content
         * @param password
         * @return
         *
         */
        public static String decryptHex(String content, String password) {
            if(content == null){
                return "";
            }
            if(StringUtils.isBlank(new String(content))){
                return "";
            }
            byte[] parseHexStr2Byte = parseHexStr2Byte(content);
    
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
                 SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
                 random.setSeed(password.getBytes());
                kgen.init(128, random);//加密解密都需要加
                SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
                byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
                byte[] result = cipher.doFinal(parseHexStr2Byte);  
                String string = new String(result);
                return string; // 明文   
    
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }

    测试代码:

     public static void main(String[] args) {
    
            String a = "xxx";
            String key = "111";
            String encrypt216Hex = AESUtils.encrypt216Hex(a, key);
            System.out.println(key);
            System.out.println("16进制密文:" +encrypt216Hex);
            System.out.println("16进制明文:" +AESUtils.decryptHex(encrypt216Hex, key));
        }
     输出:
    111
    16进制密文:DD08EDCCC2B00B43E197C9A7D72AB6A3
    16进制明文:xxx
    
    • 特别注意
      SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
      random.setSeed(password.getBytes());
      kgen.init(128, random);// 利用用户密码作为随机数初始化出

    这几行代码。之前没有这几行代码在服务器上 加密了解密报错。导致服务的电话号码数据丢失。。真是人生的一大败笔。加了这几行代码后。可以在本地和服务器上加密解密。

    欢迎加 QQ群:373899683 一起讨论技术(一群菜鸟)

    猜你喜欢

    转载自blog.csdn.net/qq_29371103/article/details/78366996