babbel / okhttp-aws-signer

AWS V4 signing algorithm for OkHttp requests
MIT License
33 stars 3 forks source link

The request signature we calculated does not match #5

Open madhujgowda opened 3 years ago

madhujgowda commented 3 years ago

`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

s-ka commented 3 years ago

Hey, sorry but I think we never tried the signing with a put request. Do you still require assistance with this?

madhujgowda commented 3 years ago

Yes, That would be great.

s-ka commented 3 years ago

I haven't had the resources to try it myself but maybe there is something in #11 that could give you a hint?