You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

63 lines
2.1 KiB

package com.inspect.tcpserver.sip.utils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
public class DigestUtil {
/**
* 计算Digest响应值
* @param username 用户名
* @param password 密码
* @param realm 域
* @param nonce 随机数
* @param method SIP请求方法,如REGISTER
* @param uri 请求URI
* @param nc 请求计数(可以传null或"00000001"初始值)
* @param cnonce 客户端随机串(可传null)
* @param qop 质量保护参数(可传null)
* @return response摘要字符串
*/
public static String computeResponse(String username, String password, String realm, String nonce,
String method, String uri, String nc, String cnonce, String qop) {
try {
String ha1 = md5Hex(username + ":" + realm + ":" + password);
String ha2 = md5Hex(method + ":" + uri);
String response;
if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) {
response = md5Hex(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
} else {
response = md5Hex(ha1 + ":" + nonce + ":" + ha2);
}
return response;
} catch (Exception e) {
throw new RuntimeException("Failed to compute digest response", e);
}
}
/**
* MD5加密,返回16进制字符串
*/
private static String md5Hex(String data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));
return byteArrayToHexString(digest);
}
/**
* 将字节数组转为16进制字符串
*/
private static String byteArrayToHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
String res = formatter.toString();
formatter.close();
return res;
}
}