华为云差旅服务-证书FAQ:实现AES加密
时间:2023-11-01 16:16:03
实现AES加密
- 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
看了此文的人还看了
CDN加速
GaussDB
文字转换成语音
免费的服务器
如何创建网站
域名网站购买
私有云桌面
云主机哪个好
域名怎么备案
手机云电脑
SSL证书申请
云点播服务器
免费OCR是什么
电脑云桌面
域名备案怎么弄
语音转文字
文字图片识别
云桌面是什么
网址安全检测
网站建设搭建
国外CDN加速
SSL免费证书申请
短信批量发送
图片OCR识别
云数据库MySQL
个人域名购买
录音转文字
扫描图片识别文字
OCR图片识别
行驶证识别
虚拟电话号码
电话呼叫中心软件
怎么制作一个网站
Email注册网站
华为VNC
图像文字识别
企业网站制作
个人网站搭建
华为云计算
免费租用云托管
云桌面云服务器
ocr文字识别免费版
HTTPS证书申请
图片文字识别转换
国外域名注册商
使用免费虚拟主机
云电脑主机多少钱
鲲鹏云手机
短信验证码平台
OCR图片文字识别
SSL证书是什么
申请企业邮箱步骤
免费的企业用邮箱
云免流搭建教程
域名价格
推荐文章