Have been trying to upload files using HTTP PUT requests in C#. The environment I am using Digitalocean Spaces is in Unity. The SDK for unity/C# is quite unstable in Unity. As in it will work for a platform, but can fail completely in a different platform. As a result just trying to get basic http requests to work. I also tried generating many different keys (so the access key and secret are definitely correct). The requests do work fine in postman. But postman I’m not sure how postman signs the request headers. Here is my code so far. What am I doing wrong?
public void RestAPI()
**{**
byte[] fileBytes = File.ReadAllBytes(filePath);
// Calculate the content length
long contentLength = fileBytes.Length;
// Calculate the content SHA-256 hash
string contentSha256 = ComputeSHA256Hash(fileBytes);
// Prepare the URL and object key
string objectKey = "testFile.png"; // The key (name) for your object in the Space
string url = $"{endpointURL}/{bucketName}/{objectKey}";
string contentType = "application/octet-stream";
string acl = "x-amz-acl:private";
// Get the current date in UTC format
DateTime now = DateTime.UtcNow;
string amzDate = now.ToString("yyyyMMddTHHmmssZ");
string dateStamp = now.ToString("yyyyMMdd");
var hostName = endpointURL.Replace("https://", "");
// Create the canonical request
string canonicalRequest = $"PUT\n/{bucketName}/{objectKey}\n\nhost:{hostName}\n" +
$"x-amz-content-sha256:{contentSha256}\nx-amz-date:{amzDate}\n\n" +
"host;x-amz-content-sha256;x-amz-date\n" + contentSha256;
// Create the string to sign
string stringToSign = $"AWS4-HMAC-SHA256\n{amzDate}\n{dateStamp}/{regionSlug}/s3/aws4_request\n" +
ComputeSHA256Hash(canonicalRequest);
// Generate the signing key
byte[] signingKey = GetSignatureKey(secretKey, dateStamp, regionSlug, "s3");
// Calculate the signature
byte[] signatureBytes = HmacSHA256(signingKey, stringToSign);
// Convert the signature to hexadecimal
string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();
HttpClient client = new HttpClient();
ByteArrayContent contentBinary = new ByteArrayContent(fileBytes, "application/x-www-form-urlencoded");
contentBinary.Headers.Add("Content-Length", contentLength.ToString());
contentBinary.Headers.Add("Authorization", $"AWS4-HMAC-SHA256 Credential={accessKey}/{dateStamp}/{regionSlug}/execute-api/aws4_request, " +
$"SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature={signature}");
contentBinary.Headers.Add("x-amz-date", amzDate);
contentBinary.Headers.Add("x-amz-content-sha256", contentSha256);
contentBinary.Headers.Add("Host", $"{hostName}");
contentBinary.Headers.Add("Connection", "keep-alive");
client.Put(new System.Uri(url), contentBinary, HttpCompletionOption._AllResponseContent_, (response) =>
{
if (response.Exception != null)
{
Debug.Log(response.Exception);
return; }
string responseData = response.ReadAsString();
Debug.Log(responseData);
});
}
private byte[] HmacSHA256(byte[] key, string data)
{
using (HMACSHA256 hmac = new HMACSHA256(key))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
}
}
private byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName)
{
byte[] kDate = HmacSHA256(Encoding.UTF8.GetBytes("AWS4" + key), dateStamp);
byte[] kRegion = HmacSHA256(kDate, regionName);
byte[] kService = HmacSHA256(kRegion, serviceName);
return HmacSHA256(kService, "aws4_request");
}
private string ComputeSHA256Hash(byte[] input)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(input);
StringBuilder builder = new StringBuilder();
foreach (byte b in hashBytes)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
}
private string ComputeSHA256Hash(string input)
**{**
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
foreach (byte b in hashBytes)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
**}**
Been at it for days, with little to no decent V4 examples out there am at the end of my wits. Please help.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
This is difficult. maybe even impossible. but bump