package com.example.studyapp.update;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class ArmCloudSignatureV2 {
    public static final String ALGORITHM = "HmacSHA256";
    public static final String SECRET_KEY = "gz8f1u0t63byzdu6ozbx8r5qs3e5lipt";
    public static final String SECRET_ID = "3yc8c8bg1dym0zaiwjh867al";

    public static String calculateSignature(String timestamp, String path, String body) throws Exception {
        String stringToSign = timestamp + path + (body != null ? body : "");
        Mac hmacSha256 = Mac.getInstance(ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_ID.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        hmacSha256.init(secretKeySpec);
        byte[] hash = hmacSha256.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hash);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
