Skip to content

Commit

Permalink
support config common aes secret (#1683)
Browse files Browse the repository at this point in the history
Signed-off-by: tomsun28 <tomsun28@outlook.com>
Co-authored-by: 东风 <zhangyang_2002@foxmail.com>
  • Loading branch information
tomsun28 and ZY945 authored Mar 26, 2024
1 parent 1d11a97 commit 9698877
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,36 +40,36 @@ public class AlerterProperties {
/**
* WeWork webhook url
*/
private String weWorkWebHookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
private String weWorkWebhookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";

/**
* DingDing talk webhook url
*/
private String dingTalkWebHookUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
private String dingTalkWebhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=";

/**
* FlyBook webhook url
*/
private String flyBookWebHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/";
private String flyBookWebhookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/";

/**
* Telegram Bot api url
*/
private String telegramBotApiUrl = "https://api.telegram.org/bot%s/sendMessage";
private String telegramWebhookUrl = "https://api.telegram.org/bot%s/sendMessage";

/**
* Discord Notify url
*/
private String discordNotifyUrl = "https://discord.com/api/v9/channels/%s/messages";
private String discordWebhookUrl = "https://discord.com/api/v9/channels/%s/messages";

/**
* ServerChan Notify url
*/
private String serverChanNotifyUrl = "https://sctapi.ftqq.com/%s.send";
private String serverChanWebhookUrl = "https://sctapi.ftqq.com/%s.send";
/**
* Gotify Notify url
*/
private String gotifyNotifyUrl = "https://push.example.de/message?token=";
private String gotifyWebhookUrl = "https://push.example.de/message?token=";

/**
* Data entry configuration properties
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
public class CommonConfig {

public CommonConfig(CommonProperties commonProperties) {
if (commonProperties != null && commonProperties.getSecretKey() != null) {
AesUtil.setDefaultSecretKey(commonProperties.getSecretKey());
if (commonProperties != null && commonProperties.getSecret() != null) {
AesUtil.setDefaultSecretKey(commonProperties.getSecret());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class CommonProperties {
/**
* secret key for password aes entry, must 16 bits
*/
private String secretKey;
private String secret;

/**
* data queue impl
Expand All @@ -42,8 +42,8 @@ public class CommonProperties {
*/
private SmsProperties sms;

public String getSecretKey() {
return secretKey;
public String getSecret() {
return secret;
}

public DataQueueProperties getQueue() {
Expand All @@ -54,8 +54,8 @@ public SmsProperties getSms() {
return sms;
}

public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
public void setSecret(String secret) {
this.secret = secret;
}

public void setQueue(DataQueueProperties queue) {
Expand Down
43 changes: 23 additions & 20 deletions common/src/main/java/org/dromara/hertzbeat/common/util/AesUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import java.util.Base64;

/**
* AES Util
* AES Decode Encode Util
*
*/
@Slf4j
Expand All @@ -44,6 +44,8 @@ public class AesUtil {
*/
private static final String ALGORITHM_STR = "AES/CBC/PKCS5Padding";

private static final String AES = "AES";

/**
* Encryption key The AES encryption key is 16 bits. If the AES encryption key is larger than 16 bits, an error message is displayed
*/
Expand Down Expand Up @@ -76,19 +78,20 @@ public static boolean isCiphertext(String text) {
*/
public static String aesEncode(String content, String encryptKey) {
try {
SecretKeySpec keySpec = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES");
//根据指定算法AES自成密码器
// todo consider not init cipher every time and test performance
SecretKeySpec keySpec = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), AES);
// cipher based on the algorithm AES
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
//初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
// init cipher Encrypt_mode or Decrypt_mode operation, the second parameter is the KEY used
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(encryptKey.getBytes(StandardCharsets.UTF_8)));
//获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
// get content bytes, must utf-8
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
//根据密码器的初始化方式--加密:将数据加密
// encode content to byte array
byte[] byteAes = cipher.doFinal(byteEncode);
//将加密后的byte[]数据转换为Base64字符串
// base64 encode content
return new String(Base64.getEncoder().encode(byteAes), StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("密文加密失败: {}", e.getMessage(), e);
log.error("aes encode content error: {}", e.getMessage(), e);
return content;
}
}
Expand All @@ -102,24 +105,24 @@ public static String aesEncode(String content, String encryptKey) {
*/
public static String aesDecode(String content, String decryptKey) {
try {
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), "AES");

//根据指定算法AES自成密码器
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), AES);
// cipher based on the algorithm AES
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
//初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
// init cipher Encrypt_mode or Decrypt_mode operation, the second parameter is the KEY used
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(decryptKey.getBytes(StandardCharsets.UTF_8)));
//8.将加密并编码base64后的字符串内容base64解码成字节数组
// base64 decode content
byte[] bytesContent = Base64.getDecoder().decode(content);
// decode content to byte array
byte[] byteDecode = cipher.doFinal(bytesContent);
return new String(byteDecode, StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException e) {
log.error("没有指定的加密算法::{}", e.getMessage(), e);
log.error("no such algorithm: {}", e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
log.error("非法的块大小::{}", e.getMessage(), e);
log.error("illegal block size: {}", e.getMessage(), e);
} catch (NullPointerException e) {
log.error("秘钥解析空指针异常::{}", e.getMessage(), e);
log.error("null point exception: {}", e.getMessage(), e);
} catch (Exception e) {
log.error("秘钥AES解析出现未知错误::{}", e.getMessage(), e);
log.error("aes decode error: {}", e.getMessage(), e);
}
return content;
}
Expand All @@ -130,11 +133,11 @@ public static String aesDecode(String content, String decryptKey) {
* @return true-是 false-否
*/
public static boolean isCiphertext(String text, String decryptKey) {
// 先用是否被base64来判断是否已经被加密
// First use whether it is base64 to determine whether it has been encrypted
if (Base64Util.isBase64(text)) {
// 若是base64 直接解密判断
// If it is base64, decrypt directly to determine
try {
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), "AES");
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(decryptKey.getBytes(StandardCharsets.UTF_8)));
byte[] bytesContent = Base64.getDecoder().decode(text);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<DingTalkWebHookDto> httpEntity = new HttpEntity<>(dingTalkWebHookDto, headers);
String webHookUrl = alerterProperties.getDingTalkWebHookUrl() + receiver.getAccessToken();
String webHookUrl = alerterProperties.getDingTalkWebhookUrl() + receiver.getAccessToken();
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
.description(renderContent(noticeTemplate, alert))
.build()))
.build();
var url = String.format(alerterProperties.getDiscordNotifyUrl(), receiver.getDiscordChannelId());
var url = String.format(alerterProperties.getDiscordWebhookUrl(), receiver.getDiscordChannelId());
var headers = new HttpHeaders();
headers.add("Authorization", "Bot " + receiver.getDiscordBotToken());
headers.setContentType(MediaType.APPLICATION_JSON);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
zhCn.setTitle("[" + bundle.getString("alerter.notify.title") + "]");
zhCn.setContent(contents);
flyBookWebHookDto.setContent(content);
String webHookUrl = alerterProperties.getFlyBookWebHookUrl() + receiver.getWechatId();
String webHookUrl = alerterProperties.getFlyBookWebhookUrl() + receiver.getWechatId();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<FlyBookWebHookDto> flyEntity = new HttpEntity<>(flyBookWebHookDto, headers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<GotifyWebHookDto> httpEntity = new HttpEntity<>(gotifyWebHookDto, headers);
String webHookUrl = String.format(alerterProperties.getGotifyNotifyUrl(), receiver.getGotifyToken());
String webHookUrl = String.format(alerterProperties.getGotifyWebhookUrl(), receiver.getGotifyToken());
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<ServerChanAlertNotifyHandlerImpl.ServerChanWebHookDto> httpEntity = new HttpEntity<>(serverChanWebHookDto, headers);
String webHookUrl = String.format(alerterProperties.getServerChanNotifyUrl(), receiver.getServerChanToken());
String webHookUrl = String.format(alerterProperties.getServerChanWebhookUrl(), receiver.getServerChanToken());
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ final class TelegramBotAlertNotifyHandlerImpl extends AbstractAlertNotifyHandler
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {
try {
String url = String.format(alerterProperties.getTelegramBotApiUrl(), receiver.getTgBotToken());
String url = String.format(alerterProperties.getTelegramWebhookUrl(), receiver.getTgBotToken());
TelegramBotNotifyDTO notifyBody = TelegramBotNotifyDTO.builder()
.chatId(receiver.getTgUserId())
.text(renderContent(noticeTemplate, alert))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<WeWorkWebHookDto> httpEntity = new HttpEntity<>(weWorkWebHookDTO, headers);
String webHookUrl = alerterProperties.getWeWorkWebHookUrl() + receiver.getWechatId();
String webHookUrl = alerterProperties.getWeWorkWebhookUrl() + receiver.getWechatId();
ResponseEntity<CommonRobotNotifyResp> entity = restTemplate.postForEntity(webHookUrl, httpEntity, CommonRobotNotifyResp.class);
if (entity.getStatusCode() == HttpStatus.OK) {
assert entity.getBody() != null;
Expand Down
25 changes: 14 additions & 11 deletions manager/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ sureness:
LnfKefTjsIfJLBa2YkhEqEGtcHDTNe4CU6+9
8tVt4bisXQ13rbN0oxhUZR73M6EByXIO+SV5
dKhaX0csgOCTlCxq20yhmUea6H6JIpSE2Rwp'

common:
secret: 'LnfKeTjsIfJLBa2H'

---
spring:
Expand Down Expand Up @@ -162,26 +165,26 @@ warehouse:
host: 127.0.0.1
port: 6379
password: 123456
#redis使用数据库,默认为DB0
# redis db index, default: DB0
db: 0

alerter:
# custom console url
console-url: https://console.tancloud.cn
# 企业微信
wework-webHook-url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=
# 钉钉
dingtalk-webhook-url: https://oapi.dingtalk.com/robot/send?access_token=
# 飞书
flybook-webhook-url: https://open.feishu.cn/open-apis/bot/v2/hook/
# we work
we-work-webhook-url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=
# ding ding talk
ding-talk-webhook-url: https://oapi.dingtalk.com/robot/send?access_token=
# fei shu fly book
fly-book-webhook-url: https://open.feishu.cn/open-apis/bot/v2/hook/
# telegram
telegram-bot-api-url: https://api.telegram.org/bot%s/sendMessage
telegram-webhook-url: https://api.telegram.org/bot%s/sendMessage
# discord
discord-notify-url: https://discord.com/api/v9/channels/%s/messages
discord-webhook-url: https://discord.com/api/v9/channels/%s/messages
# server酱
server-chan-notify-url: https://sctapi.ftqq.com/%s.send
server-chan-webhook-url: https://sctapi.ftqq.com/%s.send
# gotify
gotify-notify-url: http://127.0.0.1/message?token=%s
gotify-webhook-url: http://127.0.0.1/message?token=%s

scheduler:
server:
Expand Down

0 comments on commit 9698877

Please sign in to comment.