Skip to content

Commit 9580d7e

Browse files
authored
Fix ASN.1 serialization when content greater than or equal to 128 bytes (#120)
1 parent 03399ef commit 9580d7e

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

Sources/Crypto/ASN1/ASN1.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ extension ASN1 {
438438
for shift in (0..<(lengthBytesNeeded - 1)).reversed() {
439439
// Shift and mask the integer.
440440
self.serializedBytes.formIndex(after: &writeIndex)
441-
self.serializedBytes[writeIndex] = UInt8(truncatingIfNeeded: (contentLength >> (shift * 8)) | 0x80 )
441+
self.serializedBytes[writeIndex] = UInt8(truncatingIfNeeded: contentLength >> (shift * 8))
442442
}
443443

444444
assert(writeIndex == self.serializedBytes.index(lengthIndex, offsetBy: lengthBytesNeeded - 1))

Tests/CryptoTests/ASN1/ASN1Tests.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1689,7 +1689,7 @@ A5UvlNrk6ioTg2tumXD3Co06r1Hn+7lkkcjfT5mZO4jy7vP9ItvprJrIa6ySzVQ8
16891689
func testWeirdBigIntSerialization() throws {
16901690
// This is a bigint we can hook to get the test function to do weird things.
16911691
// We just take and accept arbitrary bytes.
1692-
struct BigIntOfBytes: ASN1IntegerRepresentable {
1692+
struct BigIntOfBytes: ASN1IntegerRepresentable, Equatable {
16931693
var bytes: [UInt8]
16941694

16951695
static let isSigned: Bool = false
@@ -1729,6 +1729,13 @@ A5UvlNrk6ioTg2tumXD3Co06r1Hn+7lkkcjfT5mZO4jy7vP9ItvprJrIa6ySzVQ8
17291729
// And a leading zero is removed for unsigned bigints.
17301730
let leadingZeroFromWire = try oneShotDecode([0x02, 0x02, 0x00, 0x80])
17311731
XCTAssertEqual(leadingZeroFromWire.bytes, [0x80])
1732+
1733+
// Check encoding and decoding results should be same
1734+
let smallBytes = BigIntOfBytes(bytes: [1, 1, 1])
1735+
XCTAssertEqual(smallBytes, try oneShotDecode(oneShotSerialize(smallBytes)))
1736+
1737+
let largeBytes = BigIntOfBytes(bytes: .init(repeating: 1, count: 1024))
1738+
XCTAssertEqual(largeBytes, try oneShotDecode(oneShotSerialize(largeBytes)))
17321739
}
17331740
}
17341741

0 commit comments

Comments
 (0)