1、通过HmacSHA1加密可用过下列方法
public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes(“UTF-8”);
// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKey secretKey = new SecretKeySpec(data, “HmacSHA1”);
// 生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(“HmacSHA1”);
// 用给定密钥初始化 Mac 对象
mac.init(secretKey);
byte[] text = encryptText.getBytes("UTF-8");
// 完成 Mac 操作
return mac.doFinal(text);
}
2、将返回的byte数组进行base64的加密
bytes就是调用的HmacSHA1Encrypt方法后返回的数组
String s = new String(Base64.encodeBase64(bytes), “UTF-8”);
System.out.println(s);
public int cutFlow(Long roomId){
UserSpacePerson userSpacePerson = userSpacePersonMapper.roomInfo(roomId);
Integer createArea = userSpacePerson.getCreateArea();
String push_app = createArea == 1 ? "wx" : "lvq";
Map<String, String> args = new HashMap<>();
args.put( "action","kickoff_push");
args.put( "kick_status","2");
args.put( "app_name",push_app);
args.put( "stream_name",userSpacePerson.getPushAppStream());
try {
Map argsSign = makeSignV1(args);
String url="https://api-livecontrol.nuoyun.tv/v1/LiveControl/PublishControl/";
requestService.sendPost(url,argsSign);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
/**
* 使用 HMAC-SHA1 签名算法对data进行签名
* @param data 被签名的字符串
* @param key 密钥
* @return 加密后的字符串
*/
public String getSignature(String data, String key) throws Exception {
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
String HmacSHA1 = "HmacSHA1";
SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HmacSHA1);
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(HmacSHA1);
//用给定密钥初始化 Mac 对象
mac.init(signinKey);
//完成 Mac 操作
byte[] rawHmac = mac.doFinal(data.getBytes());
String hexBytes = bytesToHexString(rawHmac);
return hexBytes;
}
// 将字节数组转换为十六进制二进制字符串
private static String bytesToHexString(byte[] bytes) {
StringBuilder hexBuilder = new StringBuilder();
for (byte b : bytes) {
hexBuilder.append(String.format("%02x", b));
}
return hexBuilder.toString();
}
public String hashHamcSha1(String message,String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKeySpec);
byte[] hmacBytes = mac.doFinal(message.getBytes("UTF-8"));
byte[] base64Bytes = Base64.getEncoder().encode(hmacBytes);
// System.out.println(new String(base64Bytes, "UTF-8"));
return new String(base64Bytes, "UTF-8");
}
public Map makeSignV1(Map param) throws Exception {
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
String secretId="POIDgGApFPs0gH";
String secretKey = "L9eaGgMsdw";
Map<String, String> stock = new HashMap<>();
stock.put( "Format","JSON");
stock.put( "RegionId","cn-zhengzhou");
stock.put( "SecretId",secretId);
stock.put( "SignatureMethod","HMAC-SHA1");
stock.put( "SignatureVersion","1.0");
stock.put( "SignatureNonce",generateRandomLowercase(32));
stock.put( "TimeStamp", dateFormat.format(date));
stock.put( "Version","2019-11-15");
Map<String, String> paramNew = mergeMaps(stock, param);
String kSortStr= kSort(paramNew);
String base64encodedString= hashHamcSha1(kSortStr,secretKey);
paramNew.put( "Signature",base64encodedString);
return paramNew;
}
public String kSort(Map<String, String> map) {
String sb = "";
String[] key = new String[map.size()];
int index = 0;
for (String k : map.keySet()) {
key[index] = k;
index++;
}
Arrays.sort(key);
for (String s : key) {
sb += s + "=" + map.get(s) + "&";
}
sb = sb.substring(0, sb.length() - 1);
// 将得到的字符串进行处理得到目标格式的字符串
try {
sb = URLEncoder.encode(sb, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 使用常见的UTF-8编码
sb = sb.replace("%3D", "=").replace("%26", "&").replace("%3A", ":");
return sb;
}
public <K, V> Map<K, V> mergeMaps(Map<K, V> map1, Map<K, V> map2) {
Map<K, V> result = new HashMap<>(map1);
for (Map.Entry<K, V> entry : map2.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
if (value != null) {
result.put(key, value);
} else if (!result.containsKey(key)) {
result.put(key, null);
}
}
return result;
}
public String generateRandomLowercase(int length) {
String chars = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
int index = random.nextInt(chars.length());
sb.append(chars.charAt(index));
}
return sb.toString();
}
package com.ruoyi.nuoyun.tool.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.nuoyun.tool.service.RequestService;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
@Service
@DataSource(value = DataSourceType.SLAVE)
public class RequestServiceImpl implements RequestService {
@Override
public void sendPost(String apiPath, Map<String, String> paramMap) {
String type="POST";
OutputStreamWriter out = null;
InputStream is = null;
String result = null;
try{
URL url = new URL(apiPath);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type) ; // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
//connection.setRequestProperty("Authorization","Basic XXXXXXXXXXXXXX"); //base 64加密 username:password方式。若用不到可注释
connection.connect();
if(type.equals("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(JSON.toJSONString(paramMap));
out.flush();
out.close();
}
// 读取响应
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8"); // utf-8编码
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// return result;
System.out.println(result);
}
//获取httpbasic的串
private String getHttpBasic(String clientId, String clientSecret) {
String string = clientId + ":" + clientSecret;
//将串进行base64编码
byte[] encode = Base64Utils.encode(string.getBytes());
return "Basic " + new String(encode);
}
public static JSONObject readJsonFile(String filename){
String jsonString = "";
File jsonFile = new File(filename);
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer stringBuffer = new StringBuffer();
while ((ch = reader.read()) != -1){
stringBuffer.append((char) ch);
}
fileReader.close();
reader.close();
jsonString = stringBuffer.toString();
} catch (FileNotFoundException e){
JSONObject notFoundJson = new JSONObject();
notFoundJson.put("code","503");
notFoundJson.put("msg","该地区GeoJson文件不存在!");
return notFoundJson;
} catch (IOException e) {
e.printStackTrace();
}
return JSONObject.parseObject(jsonString);
}
}