• AES对称加密


    题记:项目中对于一些不太重要的功能点,可以使用对称加密,但如果是针对用户密码之类的,请使用MD5等加密技术。

    对称加密:是指对字符串的加密和解密是同一个密钥,因此是存在风险的,一旦拿到了你的密钥,内容就完全暴露了哦。

    AES代码如下:

    package com.test.shiro.config;
    
    import javax.crypto.*;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.util.Base64;
    
    /**
     * AES-128-CBC加解密模式
     */
    public class AES {
    
        /**
         * 加密
         *
         * @param encData   要加密的数据
         * @param secretKey 密钥 ,16位的数字和字母
         * @param vector    初始化向量,16位的数字和字母
         * @return
         */
        public static String encrypt(String encData, String secretKey, String vector)
                throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
                InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    
            if (secretKey == null) {
                return null;
            }
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(encData.getBytes());
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(encrypted);
    
        }
    
    
        /**
         * 解密
         *
         * @param decData
         * @param secretKey 密钥
         * @param vector    盐
         * @return
         */
        public static String decrypt(String decData, String secretKey, String vector)
                throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
                InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    
            if (secretKey == null) {
                return null;
            }
            if (vector == null) {
                return null;
            }
            byte[] raw = secretKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] original = cipher.doFinal(decoder.decode(decData));
            String originalString = new String(original);
            return originalString;
        }
    
        /**
         * 使用指定的字符串生成秘钥
         */
        public static String getKeyByPass(String password) {
            //生成秘钥
            //String password="testkey00";
            try {
                KeyGenerator kg = KeyGenerator.getInstance("AES");
                // kg.init(128);//要生成多少位,只需要修改这里即可128, 192或256
                //SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以生成的秘钥就一样。
                kg.init(128, new SecureRandom(password.getBytes()));
                SecretKey sk = kg.generateKey();
                byte[] b = sk.getEncoded();
                String s = byteToHexString(b);
                return s;
            }
            catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                System.out.println("没有此算法。");
            }
            return "";
        }
        public static byte[] generateDesKey(int length) throws Exception {
            //实例化
            KeyGenerator kgen = null;
            kgen = KeyGenerator.getInstance("AES");
            //设置密钥长度
            kgen.init(length);
            //生成密钥
            SecretKey skey = kgen.generateKey();
            //返回密钥的二进制编码
            return skey.getEncoded();
        }
    
        public static String byteToHexString(byte[] bytes) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String strHex = Integer.toHexString(bytes[i]);
                if (strHex.length() > 3) {
                    sb.append(strHex.substring(6));
                } else {
                    if (strHex.length() < 2) {
                        sb.append("0" + strHex);
                    } else {
                        sb.append(strHex);
                    }
                }
            }
            return sb.toString();
        }
    
        public static void main(String[] args) {
            String initPsd = "werweferwer";
            String secretKey =getKeyByPass(initPsd);
            System.out.println(secretKey);
            String vector= "1234rt5t34tergy6";
            String encrptyData = "yangweref";
            try {
                String encryptPassword = encrypt(encrptyData, secretKey, vector);
                System.out.println(encryptPassword);
                String decrptyPassword = decrypt(encryptPassword,secretKey,vector);
                System.out.println(decrptyPassword);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

      fight!一起加油哦!

  • 相关阅读:
    C# 异步锁
    C#异步编程基础入门总结
    C#异步编程基础入门总结
    C#与数据结构--图的遍历
    C#中IEumerable的简单了解
    C# prism 框架 MVVM框架 Prism系列之事件聚合器
    .NET Core 3 WPF MVVM框架 Prism系列之对话框服务
    C# prism 框架
    TaskAwaiter<TResult> 结构
    利用Eventlog Analyzer分析日志
  • 原文地址:https://www.cnblogs.com/ywjfx/p/10075208.html
Copyright © 2020-2023  润新知