当前位置:   article > 正文

AES加密解密工具类_aes格式加密工具

aes格式加密工具
package com.unionx.core.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @description: AES加密工具类
 * @author: ly
 */
public class AESUtils {

    static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    // 秘钥 16
    //private static final String SECRET_KEY = "1111111111111111";
    // 秘钥 24
    //private static final String SECRET_KEY = "111111111111111111111111";
    // 秘钥 32
    private static final String SECRET_KEY = "11111111111111111111111111111111";

    // 算法
    private static final String ALGORITHM = "AES";

    private static final String UTF8 = StandardCharsets.UTF_8.name();

    /**
     * 字符串加密
     *
     * @param message   明文字符串
     * @param secretKey 秘钥
     * @return 加密字符串
     */
    public static String encryption(String message)throws Exception {
        if (!StringUtils.hasLength(message)) {
            log.error("encryption message should not be null or empty.");
        }
        byte[] encodeBytes = encryption(message.getBytes(StandardCharsets.UTF_8), SECRET_KEY);
        return Base64.encodeBase64String(encodeBytes);
    }

    /**
     * 字符串加密
     *
     * @param messageBytes 明文字节数组
     * @param secretKey    秘钥
     * @return 加密字节数组
     */
    public static byte[] encryption(byte[] messageBytes, String secretKey) throws Exception {
        if (ArrayUtils.isEmpty(messageBytes)) {
            log.error("encryption message should not be empty.");
        }
        if (!StringUtils.hasLength(secretKey)) {
            log.error("secretKey {}, encryption key should not be null or empty.", secretKey);
        }
        Cipher cipher = getCipher(secretKey, Cipher.ENCRYPT_MODE);
        byte[] encryptionBytes = null;
        //try {
            encryptionBytes = cipher.doFinal(messageBytes);
        //} catch (Exception e) {
            //log.error("encryption fail. ", e);
        //}
        return encryptionBytes;
    }

    /**
     * 字符串解密
     *
     * @param encryptionMessage 解密字符串
     * @param secretKey         秘钥
     * @return 明文字符串
     */
    public static String decrypt(String encryptionMessage) {
        if (!StringUtils.hasLength(encryptionMessage)) {
            log.error("decrypt encryptionMessage should not be null or empty.");
        }
        byte[] decodeBytes = decrypt(Base64.decodeBase64(encryptionMessage.getBytes(StandardCharsets.UTF_8)), SECRET_KEY);
        return new String(decodeBytes, StandardCharsets.UTF_8);
    }


    /**
     * 字符串加密
     *
     * @param encryptedBytes 加密字节数组
     * @param secretKey      秘钥
     * @return 明文字节数组
     */
    public static byte[] decrypt(byte[] encryptedBytes, String secretKey) {
        if (ArrayUtils.isEmpty(encryptedBytes)) {
            log.error("decrypt encryptedBytes should not be empty.");
        }
        if (!StringUtils.hasLength(secretKey)) {
            log.error("secretKey {}, decrypt key should not be null or empty.", secretKey);
        }
        Cipher cipher = getCipher(secretKey, Cipher.DECRYPT_MODE);
        byte[] decodeBytes = null;
        try {
            decodeBytes = cipher.doFinal(encryptedBytes);
        } catch (Exception e) {
            log.error("decrypt fail. ", e);
        }
        return decodeBytes;
    }

    private static Cipher getCipher(String key, int mode) {
        Cipher cipher = null;
        SecretKey secretKey;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            byte[] keyBytes = key.getBytes(UTF8);
            secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
            cipher.init(mode, secretKey);
        } catch (Exception e) {
            log.error("getAESCipher fail. ", e);
        }
        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String data = "明文密码";
        log.info("AES秘钥长度只能为16、24、32:{}", SECRET_KEY.getBytes(StandardCharsets.UTF_8).length);
        String encryptionData = encryption(data);
        log.info("加密后:{}", encryptionData);
        String decryptData = decrypt(encryptionData);
        log.info("解密后:{}", decryptData);
    }

    static {
        String errorString = "Failed manually overriding key-length permissions.";
        int newMaxKeyLength;
        try {
            if ((newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES")) < 256) {
                Class c = Class.forName("javax.crypto.CryptoAllPermissionCollection");
                Constructor con = c.getDeclaredConstructor();
                con.setAccessible(true);
                Object allPermissionCollection = con.newInstance();
                Field f = c.getDeclaredField("all_allowed");
                f.setAccessible(true);
                f.setBoolean(allPermissionCollection, true);

                c = Class.forName("javax.crypto.CryptoPermissions");
                con = c.getDeclaredConstructor();
                con.setAccessible(true);
                Object allPermissions = con.newInstance();
                f = c.getDeclaredField("perms");
                f.setAccessible(true);
                ((Map) f.get(allPermissions)).put("*", allPermissionCollection);

                c = Class.forName("javax.crypto.JceSecurityManager");
                f = c.getDeclaredField("defaultPolicy");
                f.setAccessible(true);
                Field mf = Field.class.getDeclaredField("modifiers");
                mf.setAccessible(true);
                mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
                f.set(null, allPermissions);

                newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES");
            }
        } catch (Exception e) {
            throw new RuntimeException(errorString, e);
        }
        if (newMaxKeyLength < 256)
            throw new RuntimeException(errorString); // hack failed
    }

}

  • 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
  • 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
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/511712
推荐阅读
相关标签
  

闽ICP备14008679号