Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Sources/CryptoExtras/AES/AES_CBC.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ extension AES {
throw CryptoKitError.incorrectKeySize
}

guard ciphertext.count % AES._CBC.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}

var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)

Expand Down
17 changes: 17 additions & 0 deletions Tests/CryptoExtrasTests/AES_CBCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,23 @@ final class CBCTests: XCTestCase {
}
}

func testDecryptRejectsNonBlockAlignedCiphertext() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))

// 17 bytes — not a multiple of the 16-byte block size.
let nonAligned = try Data(hexString: "00112233445566778899aabbccddeeff00")

for noPadding in [false, true] {
XCTAssertThrowsError(try AES._CBC.decrypt(nonAligned, using: key, iv: iv, noPadding: noPadding)) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error for noPadding=\(noPadding): \(error)")
return
}
}
}
}

func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
Expand Down