华为云差旅服务-证书FAQ:实现AES加密

时间:2023-11-01 16:16:03

实现AES加密

  1. Java
import org.apache.commons.ssl.util.Hex;import java.nio.charset.StandardCharsets;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.GCMParameterSpec;import javax.crypto.spec.SecretKeySpec;public class AES {    private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding";    private static final int GCM_TAG_LENGTH = 16;    private static final int GCM_IV_LENGTH = 12;private static final String AES_KEY = "a5lDXRV5D8hTcDAh";//该字段为平台分配的AESKEY    private static final char IV_SEP = ':';    /**     * 加密     *     * @param plaintext 明文     * @return 密文     */     public static String encrypt(String data, String secret) throws AuthException {        byte[] vector = new byte[GCM_IV_LENGTH];        (new SecureRandom()).nextBytes(vector);        SecretKey secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "AES");        GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, vector);        try {            Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);            cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);            byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));            // 将随机IV和密文拼接起来            return HexUtils.toHexString(vector) + IV_SEP + HexUtils.toHexString(encrypted);        } catch (Exception e) {            log.error("encrypt fail", e);            throw new AuthException("encrypt fail");        }    }    /**     * 解密     *     * @param cipherText 密文     * @return 明文     */  public static String decrypt(String data, String secret) throws AuthException {        int idx = data.indexOf(IV_SEP);        byte[] vector = HexUtils.fromHexString(data.substring(0, idx));        byte[] encrypt = HexUtils.fromHexString(data.substring(idx + 1));        SecretKey secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "AES");        GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, vector);        try {            Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);            cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);            return new String(cipher.doFinal(encrypt, 0, encrypt.length), StandardCharsets.UTF_8);        } catch (Exception e) {            log.error("decrypt fail", e);            throw new AuthException("decrypt body fail");        }    }}

support.huaweicloud.com/api-hctms/hctms-0035.html