Sử dụng API key trên với các ngôn ngữ#

Với một số ngôn ngữ chưa hỗ trợ cung cấp bộ công cụ SDK, nhà phát triển phần mềm có thể dùng ngôn ngữ bất kỳ để generate ra API key(token) sau đó integrate với Sun S3 thông qua hệ thống Sun S3 Api. Bài viết sau sẽ hướng dẫn generate API key từ accessKey và secretKey. Sau khi có API key, người dùng có thể integrate với S3 bằng http api request.

Java#

Setup - Generate API key

private static String generateApiKey(String accessKey, String secretKey, String timeStamp) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    String stringToSign = secretKey + ":" + timeStamp;
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] encodedhash = digest.digest(stringToSign.getBytes(StandardCharsets.UTF_8));
    byte[] hexChars = new byte[encodedhash.length * 2];
    for (int j = 0; j < encodedhash.length; j++) {
        int v = encodedhash[j] & 0xFF;
        hexChars[j * 2] = (byte) HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = (byte) HEX_ARRAY[v & 0x0F];
    }
    String hexString = new String(hexChars);
    String apikey = Base64Utils.encodeToString(String.format("%s:%s:%s", accessKey,
            timeStamp, hexString.toLowerCase()).getBytes(StandardCharsets.UTF_8));
    return apikey;
}

Test Connection

String apikey = generateApiKey("<accessKey>","<secretKey>", "<timestamp>");
String url = "https://client-access.sunteco.vn/s3/v1/bucket?uniqcode=<bucket-code>";
HttpRequest.Builder b = HttpRequest.newBuilder(new URI(url));
b.header("api-key", apikey).GET();
HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(b.build(), HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

JavaScript / Node.js / ReactJs/ TypeScript#

Setup - Generate API key

const generateApiKey = (accessKey, secretKey, timestamp) => {
    const hashedKey = CryptoJS.SHA256(`${secretKey}:${timestamp}`).toString()
    const apikey = btoa(`${accessKey}:${timestamp}:${hashedKey}`, 'base64')
    return apikey
  }

Python#

Setup - Generate API key

def generateApiKey(accessKey, secretKey, timeStamp):
  input = secretKey+':'+str(timeStamp)
  sha256endcoded = sha256(input.encode('utf-8')).hexdigest()
  message = accessKey+':'+str(timeStamp) + ':'+ sha256endcoded
  message_bytes = message.encode('utf-8')
  base64_bytes = base64.b64encode(message_bytes)
  api_key = base64_bytes.decode('utf-8')
  return api_key

Csharp#

Setup - Generate API key

// Generate api key
static string GenerateApiKey(string accessKey, string secretKey, string timestamp)
{
     var hashedKey = ComputeSha256Hash(accessKey, secretKey, timestamp);
     var preEncodeString = System.Text.Encoding.UTF8.GetBytes(accessKey+":"+timestamp+":"+hashedKey);
     return System.Convert.ToBase64String(preEncodeString);
         
}
// Encrypt timestamp vs secret
static string ComputeSha256Hash(string accessKey, string secretKey, string timestamp) 
{ 
    // Create a SHA256  
    using (SHA256 sha256Hash = SHA256.Create()) 
    { 
        // ComputeHash - returns byte array 
        byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(secretKey+":"+timestamp)); 
        // Convert byte array to a string  
        StringBuilder builder = new StringBuilder(); 
        for (int i = 0; i < bytes.Length; i++) 
        { 
            builder.Append(bytes[i].ToString("x2")); 
        } 
        return builder.ToString(); 
    } 
}