poc1015b

Young-Kyoo Kim·2025년 10월 15일
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class MinioAws4Test {

    // ---------------- AWS4 helper functions ----------------
    private static byte[] hmacSHA256(byte[] key, String data) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) sb.append(String.format("%02x", b));
        return sb.toString();
    }

    private static String sha256Hex(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(md.digest());
    }

    private static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes(StandardCharsets.UTF_8);
        byte[] kDate = hmacSHA256(kSecret, dateStamp);
        byte[] kRegion = hmacSHA256(kDate, regionName);
        byte[] kService = hmacSHA256(kRegion, serviceName);
        return hmacSHA256(kService, "aws4_request");
    }
    // -------------------------------------------------------

    public static void main(String[] args) throws Exception {
        // ---------------- Configuration ----------------
        String accessKey = "YOUR_ACCESS_KEY";
        String secretKey = "YOUR_SECRET_KEY";
        String region = "us-east-1";          // 임의 region
        String service = "s3";                // S3 호환 서비스
        String endpoint = "https://minio-svc.default.svc.cluster.local:9000"; // MinIO endpoint
        String method = "GET";
        String canonicalUri = "/";            // bucket root 접근
        // ------------------------------------------------

        // ---------------- TLS TrustStore 설정 ----------------
        System.setProperty("javax.net.ssl.trustStore", "/path/to/truststore.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "123456");
        // -----------------------------------------------------

        // ---------------- Timestamp ----------------
        ZonedDateTime now = ZonedDateTime.now(java.time.ZoneOffset.UTC);
        String amzDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'", Locale.US));
        String dateStamp = now.format(DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US));
        // --------------------------------------------

        // ---------------- Canonical Request ----------------
        String host = new URL(endpoint).getHost();
        String payloadHash = sha256Hex(""); // GET 빈 body
        String canonicalRequest =
                method + "\n" +
                canonicalUri + "\n" +
                "\n" + // query string
                "host:" + host + "\n\n" +
                "host\n" +
                payloadHash;
        // ----------------------------------------------------

        // ---------------- String to Sign ----------------
        String credentialScope = dateStamp + "/" + region + "/" + service + "/aws4_request";
        String stringToSign =
                "AWS4-HMAC-SHA256\n" +
                amzDate + "\n" +
                credentialScope + "\n" +
                sha256Hex(canonicalRequest);
        // ------------------------------------------------

        // ---------------- Signature ----------------
        byte[] signingKey = getSignatureKey(secretKey, dateStamp, region, service);
        String signature = bytesToHex(hmacSHA256(signingKey, stringToSign));
        // -------------------------------------------

        // ---------------- Authorization Header ----------------
        String authHeader = "AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + credentialScope +
                ", SignedHeaders=host, Signature=" + signature;
        // --------------------------------------------------------

        // ---------------- Send HTTPS Request ----------------
        URL url = new URL(endpoint + canonicalUri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setRequestProperty("Authorization", authHeader);
        conn.setRequestProperty("x-amz-date", amzDate);
        conn.setRequestProperty("Host", host);
        conn.connect();

        System.out.println("HTTP Response Code: " + conn.getResponseCode());

        if (conn.getErrorStream() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            br.lines().forEach(System.out::println);
        }
        conn.disconnect();
        // ------------------------------------------------------
    }
}

0개의 댓글