2 回答
TA贡献1843条经验 获得超7个赞
试试这个,代码有点难看,但效果很好!
public boolean verifyAuth(JsonObject Telegram_User){
String hash = Telegram_User.remove("hash").getAsString();
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
String[] t = Telegram_User.toString().replace("{","").replace("}","").replace("\":","=").replace(",","\n").replace("\"","").split("\n");
sha256_HMAC.init(new SecretKeySpec(MessageDigest.getInstance("SHA-256").digest(BezouroBot.telegram.getBotToken().getBytes(StandardCharsets.UTF_8)),"SHA256"));
Arrays.sort(t);
StringBuilder i = new StringBuilder();
boolean First = true;
for (String s : t) if(First){ First = false; i = new StringBuilder(s);} else i.append("\n").append(s);
return Hex.encodeHexString(sha256_HMAC.doFinal(i.toString().getBytes())).equals(hash);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return false;
}
}
TA贡献1860条经验 获得超9个赞
这是我的工具
// define your token to a variable
private final String TELEGRAM_TOKEN = ""
@PostMapping("auth/telegram")
public ResponseEntity<Object> telegramAuth(@RequestBody Map<String, Object> request) {
String hash = (String) request.get("hash");
request.remove("hash");
// Prepare the string
String str = request.entrySet().stream()
.sorted((a, b) -> a.getKey().compareToIgnoreCase(b.getKey()))
.map(kvp -> kvp.getKey() + "=" + kvp.getValue())
.collect(Collectors.joining("\n"));
try {
SecretKeySpec sk = new SecretKeySpec(
// Get SHA 256 from telegram token
MessageDigest.getInstance("SHA-256").digest(TELEGRAM_TOKEN.getBytes(StandardCharsets.UTF_8)
), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(sk);
byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
// Convert the result to hex string
// Like https://stackoverflow.com/questions/9655181
String resultStr = ByteBufUtil.bytesToHex(result);
// Compare the result with the hash from body
if(hash.compareToIgnoreCase(resultStr) == 0) {
// Do other things like create a user and JWT token
return ResponseEntity.ok("ok");
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
new MessageResponse("Login info hash mismatch")
);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
new MessageResponse("Server error while authenticating")
);
}
}
添加回答
举报