Skip to content

Commit 8aa3724

Browse files
authored
Blank copied key after deriving iKey and oKey (#32)
1 parent debb09f commit 8aa3724

File tree

1 file changed

+14
-7
lines changed
  • library/hmac/hmac/src/commonMain/kotlin/org/kotlincrypto/macs

1 file changed

+14
-7
lines changed

library/hmac/hmac/src/commonMain/kotlin/org/kotlincrypto/macs/Hmac.kt

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,16 +67,23 @@ public abstract class Hmac: Mac {
6767
constructor(key: ByteArray, algorithm: String, digest: Digest): super(key) {
6868
this.algorithm = algorithm
6969

70-
val preparedKey = if (key.size > digest.blockSize()) {
71-
digest.digest(key).copyOf(digest.blockSize())
72-
} else if (key.size < digest.blockSize()) {
73-
key.copyOf(digest.blockSize())
70+
val sizedKey = if (key.size > digest.blockSize()) {
71+
val keyHash = digest.digest(key)
72+
keyHash.copyOf(digest.blockSize()).also { keyHash.fill(0) }
7473
} else {
75-
key
74+
// Even if provided key is the correct size, still
75+
// create a copy so sizedKey can always be blanked
76+
// after deriving iKey and oKey.
77+
//
78+
// If the provided key is undersized, it will be
79+
// padded with 0's.
80+
key.copyOf(digest.blockSize())
7681
}
7782

78-
this.iKey = ByteArray(digest.blockSize()) { i -> preparedKey[i] xor I_PAD }
79-
this.oKey = ByteArray(digest.blockSize()) { i -> preparedKey[i] xor O_PAD }
83+
this.iKey = ByteArray(digest.blockSize()) { i -> sizedKey[i] xor I_PAD }
84+
this.oKey = ByteArray(digest.blockSize()) { i -> sizedKey[i] xor O_PAD }
85+
86+
sizedKey.fill(0)
8087

8188
digest.update(iKey)
8289
this.digest = digest

0 commit comments

Comments
 (0)