Skip to content

The request signature we calculated does not match #5

@madhujgowda

Description

@madhujgowda

`class ImageTask(var imageArray: ArrayList, var imageStorageUrl: String) : AsyncTask<String, String, String>() {

@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun doInBackground(vararg params: String?): String {

    val uuid: String = UUID.randomUUID().toString()
    val amzDate: String = generateAmzDate()
    val host: String = URI(imageStorageUrl).host

    val signer = OkHttpAwsV4Signer(
        S3_OBJECT_STORAGE_AWS_REGION,
        S3_OBJECT_STORAGE_AWS_SERVICE_NAME
    )

    val image = imageArray[0]

    val path = Paths.get(image.toString())
    val bytes = Files.readAllBytes(path)

    val hmacSha256 = calcHmacSha256(S3_OBJECT_STORAGE_SECRET_KEY.toByteArray(), bytes)

    val sha256 = String.format("%032x", BigInteger(1, hmacSha256))

    val MEDIA_TYPE_MARKDOWN = MediaType.parse("text/plain")


    val body = RequestBody.create(MEDIA_TYPE_MARKDOWN, bytes)

    val request: Request = Request.Builder()
        .addHeader("X-Amz-Date", amzDate)
        .addHeader("host", host)
        .addHeader("X-Amz-Content-Sha256", sha256)
        .url("$imageStorageUrl$uuid.jpg")
        .method("PUT", body)
        .build()

    val newRequest = signer.sign(
        request,
        S3_OBJECT_STORAGE_ACCESS_KEY,
        S3_OBJECT_STORAGE_SECRET_KEY
    )

    val client = OkHttpClient()

    val response: Response = client.newCall(newRequest).execute()

    try {
        val responseBody = response.body()?.string()
        Log.e("responseMessage", responseBody)
    } catch (e: Exception) {
        e.stackTrace
    }

    return ""
}

private fun calcHmacSha256(secretKey: ByteArray?, message: ByteArray?): ByteArray? {
    var hmacSha256: ByteArray? = null
    hmacSha256 = try {
        val mac = Mac.getInstance("HmacSHA256")
        val secretKeySpec = SecretKeySpec(secretKey, "HmacSHA256")
        mac.init(secretKeySpec)
        mac.doFinal(message)
    } catch (e: java.lang.Exception) {
        throw RuntimeException("Failed to calculate hmac-sha256", e)
    }
    return hmacSha256
}

@SuppressLint("SimpleDateFormat")
fun generateAmzDate(): String {
    return SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'").format(Date()).toString()
}

}'

And I get the message as: The request signature we calculated does not match

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions