Add integer initialisers on Certificate.SerialNumber (#106)

* Add integer initialisers on `Certificate.SerialNumber`

`Certificate.SerialNumber` can now be constructed from any `FixedWidthInteger` and also from `StaticBigInt`

* `StaticBigInt` is only available in Swift 5.8

* Do not realloc storage if we trim leading zeros
This commit is contained in:
David Nadoba authored and GitHub committed 2023-06-30 12:15:07 +01:00
1 parent e8f5dadf79
commit edf406c600
3 files changed
+86 -6

No files matched your search

+49 -5
View File
@@ -12,6 +12,8 @@
//
//===----------------------------------------------------------------------===//
import SwiftASN1
extension Certificate {
/// A number that uniquely identifies a certificate issued by a specific
/// certificate authority.
@@ -28,21 +30,21 @@ extension Certificate {
/// - Parameter bytes: The raw big-endian bytes of the serial number.
@inlinable
public init(bytes: ArraySlice<UInt8>) {
self.bytes = bytes
self.bytes = ArraySlice(normalisingToASN1IntegerForm: bytes)
}
/// Construct a serial number from its raw big-endian bytes.
/// - Parameter bytes: The raw big-endian bytes of the serial number.
@inlinable
public init(bytes: [UInt8]) {
self.bytes = bytes[...]
self.bytes = ArraySlice(normalisingToASN1IntegerForm: bytes[...])
}
/// Construct a serial number from its raw big-endian bytes.
/// - Parameter bytes: The raw big-endian bytes of the serial number.
@inlinable
public init<Bytes: Collection>(bytes: Bytes) where Bytes.Element == UInt8 {
self.bytes = ArraySlice(bytes)
self.bytes = ArraySlice(normalisingToASN1IntegerForm: bytes)
}
/// Construct a serial number from a fixed width integer.
@@ -50,11 +52,15 @@ extension Certificate {
/// In general this API should only be used for testing, as fixed width integers
/// are not sufficiently large for use in certificates. Using this API for production
/// use-cases may expose users to hash collision attacks on generated certificates.
///
///
/// Prefer using ``Certificate/SerialNumber-swift.struct/init(integerLiteral:)``
/// with a `StaticBigInt` which enables arbitrary-precision.
///
/// - Parameter bytes: The raw big-endian bytes of the serial number.
@inlinable
public init<Number: FixedWidthInteger>(_ number: Number) {
fatalError("TODO: Need ASN1 to implement")
// `IntegerBytesCollection` already trims leading zeros
self.bytes = ArraySlice(IntegerBytesCollection(number))
}
/// Construct a random 20-byte serial number.
@@ -67,6 +73,11 @@ extension Certificate {
self.init(generator: &rng)
}
/// Construct a random 20-byte serial number.
///
/// Serial numbers should be generated randomly, and may contain up to 20 bytes. This
/// initializer generates a serial number with random numbers from the given `generator`.
/// - Parameter generator: the generator used to generate random number for the serial number
@inlinable
internal init(generator: inout some RandomNumberGenerator) {
// drop leading zeros as required by the ASN.1 spec for INTEGERs
@@ -84,3 +95,36 @@ extension Certificate.SerialNumber: CustomStringConvertible {
return self.bytes.lazy.map { String($0, radix: 16) }.joined(separator: ":")
}
}
#if swift(>=5.8)
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension Certificate.SerialNumber: ExpressibleByIntegerLiteral {
/// Constructs a serial number from an integer.
///
/// - Parameter integerLiteral: The raw big-endian bytes of the serial number.
@inlinable
public init(integerLiteral number: StaticBigInt) {
var bytes = Array<UInt8>()
let wordCount = (number.bitWidth - 1) / (MemoryLayout<UInt>.size * 8) + 1
bytes.reserveCapacity(wordCount / MemoryLayout<UInt>.size)
for wordIndex in (0..<wordCount).reversed() {
bytes.appendBigEndianBytes(number[wordIndex])
}
self.bytes = ArraySlice(normalisingToASN1IntegerForm: bytes)
}
}
#endif
extension Array<UInt8> {
@inlinable
mutating func appendBigEndianBytes(_ number: UInt) {
let number = number.bigEndian
for byte in 0..<(MemoryLayout<UInt>.size) {
let shifted = number >> (byte * 8)
self.append(UInt8(truncatingIfNeeded: shifted))
}
}
}
@@ -174,8 +174,18 @@ extension ArraySlice where Element == UInt8 {
///
/// This means we strip leading zero bytes.
@inlinable
init<Bytes: RandomAccessCollection>(normalisingToASN1IntegerForm bigEndianRawInteger: Bytes) where Bytes.Element == UInt8 {
init<Bytes: Collection>(normalisingToASN1IntegerForm bigEndianRawInteger: Bytes) where Bytes.Element == UInt8 {
let realBytes = bigEndianRawInteger.drop(while: { $0 == 0 })
self = ArraySlice(realBytes)
}
@inlinable
init(normalisingToASN1IntegerForm bigEndianRawInteger: ArraySlice<UInt8>) {
self = bigEndianRawInteger.drop(while: { $0 == 0 })
}
@inlinable
init(normalisingToASN1IntegerForm bigEndianRawInteger: Array<UInt8>) {
self.init(normalisingToASN1IntegerForm: bigEndianRawInteger[...])
}
}
+26
View File
@@ -24,6 +24,32 @@ final class CertificateTests: XCTestCase {
let s = String(describing: serial)
XCTAssertEqual(s, "a:14:1e:28")
}
#if swift(>=5.8)
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
func testSerialNumberStaticBigInt() {
XCTAssertEqual(
(
0b0000_0001__0000_0010__0000_0011__0000_0100__0000_0101__0000_0110__0000_0111__0000_1000__0000_1001__0000_1010__0000_1011__0000_1100__0000_1101__0000_1110 as Certificate.SerialNumber
).bytes,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
)
XCTAssertEqual(
(
0x00_01_02_03_04_05_06_07_08_09_0A_0B_0C_0D_0E_0F_10_11_12_13_14 as Certificate.SerialNumber
).bytes,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
)
XCTAssertEqual(Certificate.SerialNumber(123456789), 123456789)
}
#endif
func testSerialNumberInits() {
XCTAssertEqual(Certificate.SerialNumber(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
XCTAssertEqual(Certificate.SerialNumber(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8][...]).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
XCTAssertEqual(Certificate.SerialNumber(bytes: AnyCollection([0, 1, 2, 3, 4, 5, 6, 7, 8])).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
}
func testPrintingVersions() {
XCTAssertEqual(String(describing: Certificate.Version.v1), "X509v1")