微信小程序 AES 敏感消息 解密 java AES 加密 解密

概述

今天在寫微信的接口的時候,需要解密微信的敏感信息。根據微信的文檔可以知道,微信使用的是AES解密。正好之前是沒有接觸過這種解密。所以就記錄一下開發過程。
在這裏插入圖片描述

什麼AES解密?

AES解密是一種對稱密鑰加密方法。所謂的對稱就是加密和解密的時候的密鑰是相同的,也有非對稱加密比如RSA加密。具體的原理我們就不說了。(其實我也不太懂),我們目前先知道如何讓使用就行了。

AES算法模式是把明文分成很多個區塊然後分別進行加密。解密同理
AES固定每個區塊的128位,而密鑰則是128位192位和256位。

密鑰的生成算法下面的方法也有寫。本文是固定128位。如果有需要可以修改。

微信敏感信息解密

微信使用的是算法是 AES-128-CBC 算法。

AES=加密方式
128=密碼位數
CBC=AES的加密模式 (CBC就是帶有IV初始變量模式)

我們直接看代碼吧。

    public static String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";
    private static final String UTF8 = "UTF-8";
    private static final String SECURERANDOM_MODE = "SHA1PRNG";


    /**
     * 帶有初始變量的解密(微信用)
     *
     * @param content     密文
     * @param skey        密鑰
     * @param ivParameter 初始向量
     * @return
     * @throws Exception
     */
    public static String weixinDecrypt(String content, String skey, String ivParameter) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // 根據微信文檔要求需要把 密文、密鑰、iv 使用BASE64進行解碼
            byte[] keyByte = new BASE64Decoder().decodeBuffer(skey);
            byte[] contentByte = decoder.decodeBuffer(content);
            byte[] ivByte = decoder.decodeBuffer(ivParameter);
            // 生成密碼
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, KEY_ALGORITHM);
            // 生成IvParameterSpec
            IvParameterSpec iv = new IvParameterSpec(ivByte);
            // 初始化解密 指定模式 AES/CBC/PKCS5Padding
            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            // 指定解密模式 傳入密碼 iv
            cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
            // 解密
            byte[] result = cipher.doFinal(contentByte);
            return new String(result, UTF8);
        } catch (Exception ex) {
            log.error("【解密錯誤】{}", ex.getMessage());
            return null;
        }
    }

如果有需要的同學可以直接拷貝。

下面順便奉上整個AES加密解密的工具類

package com.xmhmyh.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Author: buding
 * @DateTime: 2020/3/4 4:39 下午
 */
@Slf4j
public class AESUtils {

    public static String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    public static String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";
    private static final String UTF8 = "UTF-8";
    private static final String SECURERANDOM_MODE = "SHA1PRNG";


    /**
     * 帶有初始變量的解密(微信用)
     *
     * @param content     密文
     * @param skey        密鑰
     * @param ivParameter 初始向量
     * @return
     * @throws Exception
     */
    public static String weixinDecrypt(String content, String skey, String ivParameter) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] keyByte = new BASE64Decoder().decodeBuffer(skey);
            byte[] contentByte = decoder.decodeBuffer(content);
            byte[] ivByte = decoder.decodeBuffer(ivParameter);
            // 生成密碼
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, KEY_ALGORITHM);
            // 生成IvParameterSpec
            IvParameterSpec iv = new IvParameterSpec(ivByte);
            // 初始化解密 指定模式 AES/CBC/PKCS5Padding
            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            // 指定解密模式 傳入密碼 iv
            cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
            // 解密
            byte[] result = cipher.doFinal(contentByte);
            return new String(result, UTF8);
        } catch (Exception ex) {
            log.error("【解密錯誤】{}", ex.getMessage());
            return null;
        }
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密內容
     * @param key     加密密鑰
     * @return 返回Base64轉碼後的加密數據
     */
    public static String encrypt(String content, String key) {
        try {
            // 密文轉換 byte[]
            byte[] byteContent = content.getBytes(UTF8);
            // 創建密碼器
            Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM);
            // 初始化爲加密模式 並傳入密碼 密碼器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通過Base64轉碼返回
            return new BASE64Encoder().encode(result);
        } catch (Exception ex) {
            log.error("【加密錯誤】{}", ex.getMessage());
            return null;
        }
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {
        try {
            // 創建密碼器
            Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM);
            // 初始化爲解密模式 並傳入密碼 密碼器
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            // 執行解密操作
            byte[] result = cipher.doFinal(new BASE64Decoder().decodeBuffer(content));
            // 轉換成 string
            return new String(result, UTF8);
        } catch (Exception ex) {
            log.error("【解密錯誤】{}", ex.getMessage());
            return null;
        }
    }

    /**
     * 生成加密祕鑰
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
        //生成指定算法密鑰的生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        //================重點========================
        // 指定隨機數算法 防止win linux 生成的隨機數不一致
        SecureRandom secureRandom = SecureRandom.getInstance(SECURERANDOM_MODE);
        secureRandom.setSeed(password.getBytes());
        keyGenerator.init(128, secureRandom);
        //===============重點=========================
        //生成密鑰
        SecretKey secretKey = keyGenerator.generateKey();
        //轉換成AES的密鑰
        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
    }

}

注意:這裏最好指定一下隨機數的生成算法。不然win和linux系統生成的可能不一致導致最終解密失敗

        SecureRandom secureRandom = SecureRandom.getInstance(SECURERANDOM_MODE);
        secureRandom.setSeed(password.getBytes());
        keyGenerator.init(128, secureRandom);

使用代碼

 private static String key = "testPassword";

    @IgnoreAuth
    @PostMapping("test")
    @WxApi
    public Response test() {
        String content = "這是一串加密的代碼";
        return Response.success(AESUtils.encrypt(content, key));
    }

    @IgnoreAuth
    @PostMapping("test2")
    @WxApi
    public Response test2(String content, String key) {
        return Response.success(AESUtils.decrypt(content, key));
    }

加密結果
在這裏插入圖片描述
解密結果

在這裏插入圖片描述

好了,以上就是本人在寫微信敏感消息解密的一點心得。如果有哪裏不對,還請大家多多指出。謝謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章