下面是一个简单的示例,展示了如何使用javax.websocket实现前后端的签名校验。
WebSocket服务端代码:
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@ServerEndpoint("/websocket")
public class WebSocketServer {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connection opened from client");
// 生成并发送服务器的签名给客户端
String signature = generateSignature("your_secret_key");
try {
session.getBasicRemote().sendText(signature);
} catch (Exception e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message from client: " + message);
// 在此处进行签名校验逻辑,验证客户端发送的签名是否合法
// 假设校验通过,则向客户端发送回复消息
String replyMessage = "Hello client";
try {
session.getBasicRemote().sendText(replyMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
@OnClose
public void onClose() {
System.out.println("Connection closed by client");
}
private String generateSignature(String secretKey) throws NoSuchAlgorithmException {
long timestamp = System.currentTimeMillis() / 1000L; // 获取当前时间戳(秒)
// 生成签名字符串,这里仅为示例,具体签名逻辑请根据实际需求进行调整
String signatureString = secretKey + timestamp;
// 计算SHA-256哈希值,作为签名传输给客户端
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(signatureString.getBytes(StandardCharsets.UTF_8));
return bytesToHexString(hashBytes);
}
private String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
WebSocket客户端代码:
import org.apache.commons.codec.binary.Base64;
import javax.websocket.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@ClientEndpoint
public class WebSocketClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message from server: " + message);
// 在此处进行服务器发送的签名校验逻辑,验证服务器发送的签名是否合法
// 假设校验通过,则继续处理其他业务逻辑...
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
public static void main(String[] args) throws Exception {
String serverUrl = "ws://localhost:8080/websocket";
String secretKey = "your_secret_key";
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
WebSocketClient client = new WebSocketClient();
// 生成并发送客户端的签名给服务器
String signature = client.generateSignature(secretKey);
try {
Session session = container.connectToServer(client, new URI(serverUrl));
// 发送签名给服务器
session.getBasicRemote().sendText(signature);
// 继续处理其他业务逻辑...
} catch (DeploymentException | URISyntaxException e) {
e.printStackTrace();
}
}
private String generateSignature(String secretKey) throws NoSuchAlgorithmException {
long timestamp = System.currentTimeMillis() / 1000L; // 获取当前时间戳(秒)
// 生成签名字符串,这里仅为示例,具体签名逻辑请根据实际需求进行调整
String signatureString = secretKey + timestamp;
// 计算SHA-256哈希值并进行Base64编码,作为签名传输给服务端
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(signatureString.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(hashBytes);
}
}
上述代码仅提供了一个简单的示例,具体的签名校验逻辑需要根据实际情况进行开发和调整。请确保将相关依赖项(如javax.websocket-api、Apache Commons Codec等)添加到项目中,并注意修改代码中的URL和密钥等参数以匹配您的实际需求。
内容由零声教学AI助手提供,问题来源于学员提问




