Skip to content

Commit 580925b

Browse files
committed
Ensure BigIntegers N and C are positive
1 parent 0c49144 commit 580925b

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

runtime/auth/aws-signing-default/common/src/aws/smithy/kotlin/runtime/auth/awssigning/SigV4aSignatureCalculator.kt

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ internal class SigV4aSignatureCalculator(override val sha256Provider: HashSuppli
2727
var privateKey: ByteArray
2828

2929
// N value from NIST P-256 curve, minus two.
30-
val nMinusTwo = BigInteger("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC63254F".decodeHexBytes())
30+
val nMinusTwo = "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC63254F".decodeHexBytes().toPositiveBigInteger()
3131

3232
// FIXME Public docs say secret access key needs to be Base64 encoded, that's not right.
3333
// (or maybe it's already base64-encoded, and they are just repeating it)
@@ -38,7 +38,7 @@ internal class SigV4aSignatureCalculator(override val sha256Provider: HashSuppli
3838
val k0 = hmac(inputKey, fixedInputString(config.credentials.accessKeyId, counter), sha256Provider)
3939

4040
// 2: Compute the ECC key pair
41-
val c = BigInteger(k0)
41+
val c = k0.toPositiveBigInteger()
4242

4343
privateKey = (c + BigInteger("1")).toByteArray()
4444

@@ -64,4 +64,13 @@ internal class SigV4aSignatureCalculator(override val sha256Provider: HashSuppli
6464
accessKeyId.encodeToByteArray() +
6565
counter +
6666
byteArrayOf(0x00, 0x00, 0x01, 0x00) // FIXME CRT implementation (4 bytes) and internal docs (2 bytes) conflict.
67-
}
67+
}
68+
69+
// Convert [this] [ByteArray] to a positive [BigInteger]
70+
private fun ByteArray.toPositiveBigInteger(): BigInteger {
71+
return if (isNotEmpty() && (get(0).toInt() and 0x80) != 0) {
72+
BigInteger(byteArrayOf(0x00) + this) // Prepend 0x00 to ensure positive value
73+
} else {
74+
BigInteger(this)
75+
}
76+
}

0 commit comments

Comments
 (0)