mirror of
https://github.com/apple/swift-asn1
synced 2026-11-22 04:10:39 +00:00
Adopt apple/swift-format (#35)
* default swift-format configuration * Adopt `apple/swift-format` * Fix soundness.sh * Fix linting warnings * update license header * Apply review comments
This commit is contained in:
1 parent
4758353894
commit
43e0170e65
23 files changed
+907
-388
No files matched your search
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"fileScopedDeclarationPrivacy" : {
|
||||
"accessLevel" : "private"
|
||||
},
|
||||
"indentation" : {
|
||||
"spaces" : 4
|
||||
},
|
||||
"indentConditionalCompilationBlocks" : false,
|
||||
"indentSwitchCaseLabels" : false,
|
||||
"lineBreakAroundMultilineExpressionChainComponents" : false,
|
||||
"lineBreakBeforeControlFlowKeywords" : false,
|
||||
"lineBreakBeforeEachArgument" : true,
|
||||
"lineBreakBeforeEachGenericRequirement" : true,
|
||||
"lineLength" : 120,
|
||||
"maximumBlankLines" : 1,
|
||||
"prioritizeKeepingFunctionOutputTogether" : true,
|
||||
"respectsExistingLineBreaks" : true,
|
||||
"rules" : {
|
||||
"AllPublicDeclarationsHaveDocumentation" : false,
|
||||
"AlwaysUseLowerCamelCase" : false,
|
||||
"AmbiguousTrailingClosureOverload" : true,
|
||||
"BeginDocumentationCommentWithOneLineSummary" : false,
|
||||
"DoNotUseSemicolons" : true,
|
||||
"DontRepeatTypeInStaticProperties" : true,
|
||||
"FileScopedDeclarationPrivacy" : true,
|
||||
"FullyIndirectEnum" : true,
|
||||
"GroupNumericLiterals" : true,
|
||||
"IdentifiersMustBeASCII" : true,
|
||||
"NeverForceUnwrap" : false,
|
||||
"NeverUseForceTry" : false,
|
||||
"NeverUseImplicitlyUnwrappedOptionals" : false,
|
||||
"NoAccessLevelOnExtensionDeclaration" : false,
|
||||
"NoAssignmentInExpressions" : true,
|
||||
"NoBlockComments" : true,
|
||||
"NoCasesWithOnlyFallthrough" : true,
|
||||
"NoEmptyTrailingClosureParentheses" : true,
|
||||
"NoLabelsInCasePatterns" : false,
|
||||
"NoLeadingUnderscores" : false,
|
||||
"NoParensAroundConditions" : true,
|
||||
"NoVoidReturnOnFunctionSignature" : true,
|
||||
"OneCasePerLine" : true,
|
||||
"OneVariableDeclarationPerLine" : true,
|
||||
"OnlyOneTrailingClosureArgument" : true,
|
||||
"OrderedImports" : false,
|
||||
"ReturnVoidInsteadOfEmptyTuple" : true,
|
||||
"UseEarlyExits" : true,
|
||||
"UseLetInEveryBoundCaseVariable" : false,
|
||||
"UseShorthandTypeNames" : true,
|
||||
"UseSingleLinePropertyGetter" : false,
|
||||
"UseSynthesizedInitializer" : true,
|
||||
"UseTripleSlashForDocumentationComments" : true,
|
||||
"UseWhereClausesInForLoops" : false,
|
||||
"ValidateDocumentationComments" : false
|
||||
},
|
||||
"spacesAroundRangeFormationOperators" : false,
|
||||
"tabWidth" : 8,
|
||||
"version" : 1
|
||||
}
|
||||
@@ -33,3 +33,11 @@ This product contains derivations of various scripts from SwiftNIO.
|
||||
* HOMEPAGE:
|
||||
* https://github.com/apple/swift-nio
|
||||
|
||||
---
|
||||
|
||||
This product contains derivations of various scripts from Swift OpenAPI Generator.
|
||||
|
||||
* LICENSE (Apache License 2.0):
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* HOMEPAGE:
|
||||
* https://github.com/apple/swift-openapi-generator
|
||||
+230
-96
@@ -14,7 +14,7 @@
|
||||
|
||||
/// ``DER`` defines a namespace that is used to store a number of helper methods and types
|
||||
/// for DER encoding and decoding.
|
||||
public enum DER { }
|
||||
public enum DER {}
|
||||
|
||||
// MARK: - Parser Node
|
||||
extension DER {
|
||||
@@ -64,14 +64,15 @@ extension DER {
|
||||
}
|
||||
}
|
||||
|
||||
extension DER.ParserNode: Hashable { }
|
||||
extension DER.ParserNode: Hashable {}
|
||||
|
||||
extension DER.ParserNode: Sendable { }
|
||||
extension DER.ParserNode: Sendable {}
|
||||
|
||||
extension DER.ParserNode: CustomStringConvertible {
|
||||
@inlinable
|
||||
var description: String {
|
||||
return "DER.ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
|
||||
return
|
||||
"DER.ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +87,11 @@ extension DER {
|
||||
/// - identifier: The ``ASN1Identifier`` that the SEQUENCE is expected to have.
|
||||
/// - builder: A closure that will be called with the collection of nodes within the sequence.
|
||||
@inlinable
|
||||
public static func sequence<T>(_ node: ASN1Node, identifier: ASN1Identifier, _ builder: (inout ASN1NodeCollection.Iterator) throws -> T) throws -> T {
|
||||
public static func sequence<T>(
|
||||
_ node: ASN1Node,
|
||||
identifier: ASN1Identifier,
|
||||
_ builder: (inout ASN1NodeCollection.Iterator) throws -> T
|
||||
) throws -> T {
|
||||
guard node.identifier == identifier, case .constructed(let nodes) = node.content else {
|
||||
throw ASN1Error.unexpectedFieldType(node.identifier)
|
||||
}
|
||||
@@ -112,7 +117,11 @@ extension DER {
|
||||
/// - rootNode: The ``ASN1Node`` to parse
|
||||
/// - returns: An array of elements representing the elements in the sequence.
|
||||
@inlinable
|
||||
public static func sequence<T: DERParseable>(of: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> [T] {
|
||||
public static func sequence<T: DERParseable>(
|
||||
of: T.Type = T.self,
|
||||
identifier: ASN1Identifier,
|
||||
rootNode: ASN1Node
|
||||
) throws -> [T] {
|
||||
guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else {
|
||||
throw ASN1Error.unexpectedFieldType(rootNode.identifier)
|
||||
}
|
||||
@@ -130,10 +139,16 @@ extension DER {
|
||||
/// - nodes: An ``ASN1NodeCollection/Iterator`` of nodes to parse.
|
||||
/// - returns: An array of elements representing the elements in the sequence.
|
||||
@inlinable
|
||||
public static func sequence<T: DERParseable>(of: T.Type = T.self, identifier: ASN1Identifier, nodes: inout ASN1NodeCollection.Iterator) throws -> [T] {
|
||||
public static func sequence<T: DERParseable>(
|
||||
of: T.Type = T.self,
|
||||
identifier: ASN1Identifier,
|
||||
nodes: inout ASN1NodeCollection.Iterator
|
||||
) throws -> [T] {
|
||||
guard let node = nodes.next() else {
|
||||
// Not present, throw.
|
||||
throw ASN1Error.invalidASN1Object(reason: "No sequence node available for \(T.self) and identifier \(identifier)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "No sequence node available for \(T.self) and identifier \(identifier)"
|
||||
)
|
||||
}
|
||||
|
||||
return try sequence(of: T.self, identifier: identifier, rootNode: node)
|
||||
@@ -148,11 +163,15 @@ extension DER {
|
||||
/// - identifier: The ``ASN1Identifier`` that the SET is expected to have.
|
||||
/// - builder: A closure that will be called with the collection of nodes within the set.
|
||||
@inlinable
|
||||
public static func set<T>(_ node: ASN1Node, identifier: ASN1Identifier, _ builder: (inout ASN1NodeCollection.Iterator) throws -> T) throws -> T {
|
||||
public static func set<T>(
|
||||
_ node: ASN1Node,
|
||||
identifier: ASN1Identifier,
|
||||
_ builder: (inout ASN1NodeCollection.Iterator) throws -> T
|
||||
) throws -> T {
|
||||
// Shhhh these two are secretly the same with identifier.
|
||||
return try sequence(node, identifier: identifier, builder)
|
||||
}
|
||||
|
||||
|
||||
/// Parse the node as an ASN.1 SET OF.
|
||||
///
|
||||
/// Constructs an array of `T` elements parsed from the set.
|
||||
@@ -163,15 +182,21 @@ extension DER {
|
||||
/// - nodes: An ``ASN1NodeCollection/Iterator`` of nodes to parse.
|
||||
/// - returns: An array of elements representing the elements in the set.
|
||||
@inlinable
|
||||
public static func set<T: DERParseable>(of: T.Type = T.self, identifier: ASN1Identifier, nodes: inout ASN1NodeCollection.Iterator) throws -> [T] {
|
||||
public static func set<T: DERParseable>(
|
||||
of: T.Type = T.self,
|
||||
identifier: ASN1Identifier,
|
||||
nodes: inout ASN1NodeCollection.Iterator
|
||||
) throws -> [T] {
|
||||
guard let node = nodes.next() else {
|
||||
// Not present, throw.
|
||||
throw ASN1Error.invalidASN1Object(reason: "No set node available for \(T.self) and identifier \(identifier)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "No set node available for \(T.self) and identifier \(identifier)"
|
||||
)
|
||||
}
|
||||
|
||||
return try Self.set(of: T.self, identifier: identifier, rootNode: node)
|
||||
}
|
||||
|
||||
|
||||
/// Parse the node as an ASN.1 SET OF.
|
||||
///
|
||||
/// Constructs an array of `T` elements parsed from the set.
|
||||
@@ -182,10 +207,14 @@ extension DER {
|
||||
/// - rootNode: The ``ASN1Node`` to parse
|
||||
/// - returns: An array of elements representing the elements in the sequence.
|
||||
@inlinable
|
||||
public static func set<T: DERParseable>(of type: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> [T] {
|
||||
public static func set<T: DERParseable>(
|
||||
of type: T.Type = T.self,
|
||||
identifier: ASN1Identifier,
|
||||
rootNode: ASN1Node
|
||||
) throws -> [T] {
|
||||
try self.lazySet(of: type, identifier: identifier, rootNode: rootNode).map { try $0.get() }
|
||||
}
|
||||
|
||||
|
||||
/// Parse the node as an ASN.1 SET OF lazily.
|
||||
///
|
||||
/// Constructs a Sequence of `T` elements that will be lazily parsed from the set.
|
||||
@@ -196,47 +225,51 @@ extension DER {
|
||||
/// - rootNode: The ``ASN1Node`` to parse
|
||||
/// - returns: A `Sequence` of elements representing the `Result` of parsing the elements in the sequence.
|
||||
@inlinable
|
||||
public static func lazySet<T: DERParseable>(of: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> LazySetOfSequence<T> {
|
||||
public static func lazySet<T: DERParseable>(
|
||||
of: T.Type = T.self,
|
||||
identifier: ASN1Identifier,
|
||||
rootNode: ASN1Node
|
||||
) throws -> LazySetOfSequence<T> {
|
||||
guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else {
|
||||
throw ASN1Error.unexpectedFieldType(rootNode.identifier)
|
||||
}
|
||||
|
||||
|
||||
guard nodes.isOrderedAccordingToSetOfSemantics() else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "SET OF fields are not lexicographically ordered")
|
||||
}
|
||||
|
||||
|
||||
return .init(nodes.lazy.map { node in Result { try T(derEncoded: node) } })
|
||||
}
|
||||
|
||||
|
||||
public struct LazySetOfSequence<T>: Sequence {
|
||||
public typealias Element = Result<T, Error>
|
||||
|
||||
|
||||
@usableFromInline
|
||||
typealias WrappedSequence = LazyMapSequence<LazySequence<(ASN1NodeCollection)>.Elements, Result<T, Error>>
|
||||
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
var wrapped: WrappedSequence.Iterator
|
||||
|
||||
|
||||
@inlinable
|
||||
mutating public func next() -> Element? {
|
||||
wrapped.next()
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
init(_ wrapped: WrappedSequence.Iterator) {
|
||||
self.wrapped = wrapped
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
var wrapped: WrappedSequence
|
||||
|
||||
|
||||
@inlinable
|
||||
init(_ wrapped: WrappedSequence) {
|
||||
self.wrapped = wrapped
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
.init(wrapped.makeIterator())
|
||||
@@ -256,7 +289,12 @@ extension DER {
|
||||
///
|
||||
/// - returns: The result of `builder` if the element was present, or `nil` if it was not.
|
||||
@inlinable
|
||||
public static func optionalExplicitlyTagged<T>(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? {
|
||||
public static func optionalExplicitlyTagged<T>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
_ builder: (ASN1Node) throws -> T
|
||||
) throws -> T? {
|
||||
var localNodesCopy = nodes
|
||||
guard let node = localNodesCopy.next() else {
|
||||
// Node not present, return nil.
|
||||
@@ -264,7 +302,7 @@ extension DER {
|
||||
}
|
||||
|
||||
let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
// assert(expectedNodeID.constructed)
|
||||
// assert(expectedNodeID.constructed)
|
||||
guard node.identifier == expectedNodeID else {
|
||||
// Node is a mismatch, with the wrong tag. Our optional isn't present.
|
||||
return nil
|
||||
@@ -281,7 +319,9 @@ extension DER {
|
||||
|
||||
var nodeIterator = nodes.makeIterator()
|
||||
guard let child = nodeIterator.next(), nodeIterator.next() == nil else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Too many child nodes in optionally tagged node of \(T.self) with identifier \(expectedNodeID)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Too many child nodes in optionally tagged node of \(T.self) with identifier \(expectedNodeID)"
|
||||
)
|
||||
}
|
||||
|
||||
return try builder(child)
|
||||
@@ -298,7 +338,10 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or `nil` if it was not.
|
||||
@inlinable
|
||||
public static func optionalImplicitlyTagged<T: DERImplicitlyTaggable>(_ nodes: inout ASN1NodeCollection.Iterator, tag: ASN1Identifier = T.defaultIdentifier) throws -> T? {
|
||||
public static func optionalImplicitlyTagged<T: DERImplicitlyTaggable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
tag: ASN1Identifier = T.defaultIdentifier
|
||||
) throws -> T? {
|
||||
var localNodesCopy = nodes
|
||||
guard let node = localNodesCopy.next() else {
|
||||
// Node not present, return nil.
|
||||
@@ -313,7 +356,7 @@ extension DER {
|
||||
// We're good: pass the node on.
|
||||
return try T(derEncoded: &nodes, withIdentifier: tag)
|
||||
}
|
||||
|
||||
|
||||
/// Parses an optional implicitly tagged element.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -335,16 +378,16 @@ extension DER {
|
||||
// Node not present, return nil.
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
guard node.identifier == expectedNodeID else {
|
||||
// Node is a mismatch, with the wrong tag. Our optional isn't present.
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// We have the right optional, so let's consume it.
|
||||
nodes = localNodesCopy
|
||||
|
||||
|
||||
// We're good: pass the node on.
|
||||
return try builder(node)
|
||||
}
|
||||
@@ -364,7 +407,12 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or the default if it was not.
|
||||
@inlinable
|
||||
public static func decodeDefault<T: DERParseable & Equatable>(_ nodes: inout ASN1NodeCollection.Iterator, identifier: ASN1Identifier, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
public static func decodeDefault<T: DERParseable & Equatable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
identifier: ASN1Identifier,
|
||||
defaultValue: T,
|
||||
_ builder: (ASN1Node) throws -> T
|
||||
) throws -> T {
|
||||
// A weird trick here: we only want to consume the next node _if_ it has the right tag. To achieve that,
|
||||
// we work on a copy.
|
||||
var localNodesCopy = nodes
|
||||
@@ -385,7 +433,10 @@ extension DER {
|
||||
// DER forbids encoding DEFAULT values at their default state.
|
||||
// We can lift this in BER.
|
||||
guard parsed != defaultValue else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "DEFAULT for \(T.self) with identifier \(identifier) present in DER but encoded at default value \(defaultValue)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason:
|
||||
"DEFAULT for \(T.self) with identifier \(identifier) present in DER but encoded at default value \(defaultValue)"
|
||||
)
|
||||
}
|
||||
|
||||
return parsed
|
||||
@@ -404,8 +455,14 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or the default if it was not.
|
||||
@inlinable
|
||||
public static func decodeDefault<T: DERParseable & Equatable>(_ nodes: inout ASN1NodeCollection.Iterator, identifier: ASN1Identifier, defaultValue: T) throws -> T {
|
||||
return try Self.decodeDefault(&nodes, identifier: identifier, defaultValue: defaultValue) { try T(derEncoded: $0) }
|
||||
public static func decodeDefault<T: DERParseable & Equatable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
identifier: ASN1Identifier,
|
||||
defaultValue: T
|
||||
) throws -> T {
|
||||
return try Self.decodeDefault(&nodes, identifier: identifier, defaultValue: defaultValue) {
|
||||
try T(derEncoded: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a value that is encoded with a DEFAULT.
|
||||
@@ -420,7 +477,10 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or the default if it was not.
|
||||
@inlinable
|
||||
public static func decodeDefault<T: DERImplicitlyTaggable & Equatable>(_ nodes: inout ASN1NodeCollection.Iterator, defaultValue: T) throws -> T {
|
||||
public static func decodeDefault<T: DERImplicitlyTaggable & Equatable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
defaultValue: T
|
||||
) throws -> T {
|
||||
return try Self.decodeDefault(&nodes, identifier: T.defaultIdentifier, defaultValue: defaultValue)
|
||||
}
|
||||
|
||||
@@ -437,18 +497,27 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or the default if it was not.
|
||||
@inlinable
|
||||
public static func decodeDefaultExplicitlyTagged<T: DERParseable & Equatable>(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
if let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder) {
|
||||
guard result != defaultValue else {
|
||||
// DER forbids encoding DEFAULT values at their default state.
|
||||
// We can lift this in BER.
|
||||
throw ASN1Error.invalidASN1Object(reason: "DEFAULT for \(T.self) with tag number \(tagNumber) and class \(tagClass) present in DER but encoded at default value \(defaultValue)")
|
||||
}
|
||||
|
||||
return result
|
||||
} else {
|
||||
public static func decodeDefaultExplicitlyTagged<T: DERParseable & Equatable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
defaultValue: T,
|
||||
_ builder: (ASN1Node) throws -> T
|
||||
) throws -> T {
|
||||
guard let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder)
|
||||
else {
|
||||
return defaultValue
|
||||
}
|
||||
guard result != defaultValue else {
|
||||
// DER forbids encoding DEFAULT values at their default state.
|
||||
// We can lift this in BER.
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason:
|
||||
"DEFAULT for \(T.self) with tag number \(tagNumber) and class \(tagClass) present in DER but encoded at default value \(defaultValue)"
|
||||
)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Parses a value that is encoded with a DEFAULT and an explicit tag.
|
||||
@@ -465,9 +534,17 @@ extension DER {
|
||||
///
|
||||
/// - returns: The parsed element, if it was present, or the default if it was not.
|
||||
@inlinable
|
||||
public static func decodeDefaultExplicitlyTagged<T: DERParseable & Equatable>(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, defaultValue: T) throws -> T {
|
||||
public static func decodeDefaultExplicitlyTagged<T: DERParseable & Equatable>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
defaultValue: T
|
||||
) throws -> T {
|
||||
return try Self.decodeDefaultExplicitlyTagged(
|
||||
&nodes, tagNumber: tagNumber, tagClass: tagClass, defaultValue: defaultValue
|
||||
&nodes,
|
||||
tagNumber: tagNumber,
|
||||
tagClass: tagClass,
|
||||
defaultValue: defaultValue
|
||||
) {
|
||||
try T(derEncoded: $0)
|
||||
}
|
||||
@@ -486,10 +563,18 @@ extension DER {
|
||||
///
|
||||
/// - returns: The result of `builder`.
|
||||
@inlinable
|
||||
public static func explicitlyTagged<T>(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
public static func explicitlyTagged<T>(
|
||||
_ nodes: inout ASN1NodeCollection.Iterator,
|
||||
tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
_ builder: (ASN1Node) throws -> T
|
||||
) throws -> T {
|
||||
guard let node = nodes.next() else {
|
||||
// Node not present, throw.
|
||||
throw ASN1Error.invalidASN1Object(reason: "Explicitly tagged node for \(T.self) with tag number \(tagNumber) and class \(tagClass) not present")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason:
|
||||
"Explicitly tagged node for \(T.self) with tag number \(tagNumber) and class \(tagClass) not present"
|
||||
)
|
||||
}
|
||||
|
||||
return try self.explicitlyTagged(node, tagNumber: tagNumber, tagClass: tagClass, builder)
|
||||
@@ -505,7 +590,12 @@ extension DER {
|
||||
///
|
||||
/// - returns: The result of `builder`.
|
||||
@inlinable
|
||||
public static func explicitlyTagged<T>(_ node: ASN1Node, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T {
|
||||
public static func explicitlyTagged<T>(
|
||||
_ node: ASN1Node,
|
||||
tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
_ builder: (ASN1Node) throws -> T
|
||||
) throws -> T {
|
||||
let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
guard node.identifier == expectedNodeID else {
|
||||
// Node is a mismatch, with the wrong tag.
|
||||
@@ -519,14 +609,15 @@ extension DER {
|
||||
|
||||
var nodeIterator = nodes.makeIterator()
|
||||
guard let child = nodeIterator.next(), nodeIterator.next() == nil else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid number of child nodes for explicit tag \(expectedNodeID) for \(T.self)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid number of child nodes for explicit tag \(expectedNodeID) for \(T.self)"
|
||||
)
|
||||
}
|
||||
|
||||
return try builder(child)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Parsing
|
||||
extension DER {
|
||||
/// A parsed representation of ASN.1.
|
||||
@@ -583,7 +674,9 @@ extension DER {
|
||||
|
||||
// We need a check here: this number needs to be greater than or equal to 0x1f, or it should have been encoded as short form.
|
||||
guard tagNumber >= 0x1f else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "ASN.1 tag incorrectly encoded in long form: \(tagNumber)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "ASN.1 tag incorrectly encoded in long form: \(tagNumber)"
|
||||
)
|
||||
}
|
||||
identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
} else {
|
||||
@@ -636,7 +729,7 @@ extension DER {
|
||||
}
|
||||
}
|
||||
|
||||
extension DER.ParseResult: Hashable { }
|
||||
extension DER.ParseResult: Hashable {}
|
||||
|
||||
extension DER {
|
||||
/// Parses an array of bytes as DER-encoded ASN.1 bytes.
|
||||
@@ -723,9 +816,9 @@ public struct ASN1NodeCollection {
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1NodeCollection: Hashable { }
|
||||
extension ASN1NodeCollection: Hashable {}
|
||||
|
||||
extension ASN1NodeCollection: Sendable { }
|
||||
extension ASN1NodeCollection: Sendable {}
|
||||
|
||||
extension ASN1NodeCollection: Sequence {
|
||||
/// An iterator of ASN.1 nodes that are children of a specific constructed node.
|
||||
@@ -751,16 +844,7 @@ extension ASN1NodeCollection: Sequence {
|
||||
}
|
||||
|
||||
assert(nextNode.depth == self._depth + 1)
|
||||
if nextNode.isConstructed {
|
||||
// We need to feed it the next set of nodes.
|
||||
let nodeCollection = self._nodes.prefix { $0.depth > nextNode.depth }
|
||||
self._nodes = self._nodes.dropFirst(nodeCollection.count)
|
||||
return ASN1Node(
|
||||
identifier: nextNode.identifier,
|
||||
content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)),
|
||||
encodedBytes: nextNode.encodedBytes
|
||||
)
|
||||
} else {
|
||||
guard nextNode.isConstructed else {
|
||||
// There must be data bytes here, even if they're empty.
|
||||
return ASN1Node(
|
||||
identifier: nextNode.identifier,
|
||||
@@ -768,6 +852,14 @@ extension ASN1NodeCollection: Sequence {
|
||||
encodedBytes: nextNode.encodedBytes
|
||||
)
|
||||
}
|
||||
// We need to feed it the next set of nodes.
|
||||
let nodeCollection = self._nodes.prefix { $0.depth > nextNode.depth }
|
||||
self._nodes = self._nodes.dropFirst(nodeCollection.count)
|
||||
return ASN1Node(
|
||||
identifier: nextNode.identifier,
|
||||
content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)),
|
||||
encodedBytes: nextNode.encodedBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -853,7 +945,10 @@ extension DER {
|
||||
/// - identifier: The tag for this ASN.1 node
|
||||
/// - contentWriter: A callback that will be invoked that allows users to write their bytes into the output stream.
|
||||
@inlinable
|
||||
public mutating func appendPrimitiveNode(identifier: ASN1Identifier, _ contentWriter: (inout [UInt8]) throws -> Void) rethrows {
|
||||
public mutating func appendPrimitiveNode(
|
||||
identifier: ASN1Identifier,
|
||||
_ contentWriter: (inout [UInt8]) throws -> Void
|
||||
) rethrows {
|
||||
try self._appendNode(identifier: identifier, constructed: false) { try contentWriter(&$0._serializedBytes) }
|
||||
}
|
||||
|
||||
@@ -866,7 +961,10 @@ extension DER {
|
||||
/// - identifier: The tag for this ASN.1 node
|
||||
/// - contentWriter: A callback that will be invoked that allows users to write the objects contained within this constructed node.
|
||||
@inlinable
|
||||
public mutating func appendConstructedNode(identifier: ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
|
||||
public mutating func appendConstructedNode(
|
||||
identifier: ASN1Identifier,
|
||||
_ contentWriter: (inout Serializer) throws -> Void
|
||||
) rethrows {
|
||||
try self._appendNode(identifier: identifier, constructed: true, contentWriter)
|
||||
}
|
||||
|
||||
@@ -889,7 +987,11 @@ extension DER {
|
||||
/// tagNumber: The number of the explicit tag.
|
||||
/// tagClass: The number of the explicit tag.
|
||||
@inlinable
|
||||
public mutating func serialize<T: DERSerializable>(_ node: T, explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1Identifier.TagClass) throws {
|
||||
public mutating func serialize<T: DERSerializable>(
|
||||
_ node: T,
|
||||
explicitlyTaggedWithTagNumber tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass
|
||||
) throws {
|
||||
let identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
return try self.serialize(node, explicitlyTaggedWithIdentifier: identifier)
|
||||
}
|
||||
@@ -900,7 +1002,10 @@ extension DER {
|
||||
/// node: The node to be serialized.
|
||||
/// identifier: The explicit ASN.1 tag to apply.
|
||||
@inlinable
|
||||
public mutating func serialize<T: DERSerializable>(_ node: T, explicitlyTaggedWithIdentifier identifier: ASN1Identifier) throws {
|
||||
public mutating func serialize<T: DERSerializable>(
|
||||
_ node: T,
|
||||
explicitlyTaggedWithIdentifier identifier: ASN1Identifier
|
||||
) throws {
|
||||
try self.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(node)
|
||||
}
|
||||
@@ -929,7 +1034,10 @@ extension DER {
|
||||
/// node: The node to be serialized.
|
||||
/// identifier: The implicit ASN.1 tag to apply.
|
||||
@inlinable
|
||||
public mutating func serializeOptionalImplicitlyTagged<T: DERImplicitlyTaggable>(_ node: T?, withIdentifier identifier: ASN1Identifier) throws {
|
||||
public mutating func serializeOptionalImplicitlyTagged<T: DERImplicitlyTaggable>(
|
||||
_ node: T?,
|
||||
withIdentifier identifier: ASN1Identifier
|
||||
) throws {
|
||||
if let node = node {
|
||||
try node.serialize(into: &self, withIdentifier: identifier)
|
||||
}
|
||||
@@ -945,7 +1053,11 @@ extension DER {
|
||||
/// tagClass: The number of the explicit tag.
|
||||
/// block: The block that will be invoked to encode the contents of the explicit tag.
|
||||
@inlinable
|
||||
public mutating func serialize(explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ block: (inout Serializer) throws -> Void) rethrows {
|
||||
public mutating func serialize(
|
||||
explicitlyTaggedWithTagNumber tagNumber: UInt,
|
||||
tagClass: ASN1Identifier.TagClass,
|
||||
_ block: (inout Serializer) throws -> Void
|
||||
) rethrows {
|
||||
let identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass)
|
||||
try self.appendConstructedNode(identifier: identifier) { coder in
|
||||
try block(&coder)
|
||||
@@ -958,21 +1070,27 @@ extension DER {
|
||||
/// - elements: The members of the ASN.1 SEQUENCE OF.
|
||||
/// - identifier: The identifier to use for the SEQUENCE OF node. Defaults to ``ASN1Identifier/sequence``.
|
||||
@inlinable
|
||||
public mutating func serializeSequenceOf<Elements: Sequence>(_ elements: Elements, identifier: ASN1Identifier = .sequence) throws where Elements.Element: DERSerializable {
|
||||
public mutating func serializeSequenceOf<Elements: Sequence>(
|
||||
_ elements: Elements,
|
||||
identifier: ASN1Identifier = .sequence
|
||||
) throws where Elements.Element: DERSerializable {
|
||||
try self.appendConstructedNode(identifier: identifier) { coder in
|
||||
for element in elements {
|
||||
try coder.serialize(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Serializes a SET OF ASN.1 nodes.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - elements: The members of the ASN.1 SET OF.
|
||||
/// - identifier: The identifier to use for the SET OF node. Defaults to ``ASN1Identifier/set``.
|
||||
@inlinable
|
||||
public mutating func serializeSetOf<Elements: Sequence>(_ elements: Elements, identifier: ASN1Identifier = .set) throws where Elements.Element: DERSerializable {
|
||||
public mutating func serializeSetOf<Elements: Sequence>(
|
||||
_ elements: Elements,
|
||||
identifier: ASN1Identifier = .set
|
||||
) throws where Elements.Element: DERSerializable {
|
||||
// We first serialize all elements into one intermediate Serializer and
|
||||
// create ArraySlices of their binary DER representation.
|
||||
var intermediateSerializer = DER.Serializer()
|
||||
@@ -986,7 +1104,7 @@ extension DER {
|
||||
// get `ArraySlice`s during the sort and write operations on demand.
|
||||
return startIndex..<endIndex
|
||||
}
|
||||
|
||||
|
||||
let serializedBytes = intermediateSerializer.serializedBytes
|
||||
// Afterwards we sort the binary representation of each element lexicographically
|
||||
let sortedRanges = serializedRanges.sorted { lhs, rhs in
|
||||
@@ -1050,7 +1168,11 @@ extension DER {
|
||||
// This is the base logical function that all other append methods are built on. This one has most of the logic, and doesn't
|
||||
// police what we expect to happen in the content writer.
|
||||
@inlinable
|
||||
mutating func _appendNode(identifier: ASN1Identifier, constructed: Bool, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
|
||||
mutating func _appendNode(
|
||||
identifier: ASN1Identifier,
|
||||
constructed: Bool,
|
||||
_ contentWriter: (inout Serializer) throws -> Void
|
||||
) rethrows {
|
||||
// This is a tricky game to play. We want to write the identifier and the length, but we don't know what the
|
||||
// length is here. To get around that, we _assume_ the length will be one byte, and let the writer write their content.
|
||||
// If it turns out to have been longer, we recalculate how many bytes we need and shuffle them in the buffer,
|
||||
@@ -1066,7 +1188,10 @@ extension DER {
|
||||
|
||||
try contentWriter(&self)
|
||||
|
||||
let contentLength = self._serializedBytes.distance(from: originalEndIndex, to: self._serializedBytes.endIndex)
|
||||
let contentLength = self._serializedBytes.distance(
|
||||
from: originalEndIndex,
|
||||
to: self._serializedBytes.endIndex
|
||||
)
|
||||
let lengthBytesNeeded = contentLength._bytesNeededToEncode
|
||||
if lengthBytesNeeded == 1 {
|
||||
// We can just set this at the top, and we're done!
|
||||
@@ -1077,7 +1202,10 @@ extension DER {
|
||||
|
||||
// Whoops, we need more than one byte to represent the length. That's annoying!
|
||||
// To sort this out we want to "move" the memory to the right.
|
||||
self._serializedBytes._moveRange(offset: lengthBytesNeeded - 1, range: originalEndIndex..<self._serializedBytes.endIndex)
|
||||
self._serializedBytes._moveRange(
|
||||
offset: lengthBytesNeeded - 1,
|
||||
range: originalEndIndex..<self._serializedBytes.endIndex
|
||||
)
|
||||
|
||||
// Now we can write the length bytes back. We first write the number of length bytes
|
||||
// we needed, setting the high bit. Then we write the bytes of the length.
|
||||
@@ -1206,8 +1334,10 @@ extension DERImplicitlyTaggable {
|
||||
/// will be used to construct this object.
|
||||
/// - identifier: The ASN.1 identifier that `derEncoded` is expected to have.
|
||||
@inlinable
|
||||
public init(derEncoded sequenceNodeIterator: inout ASN1NodeCollection.Iterator,
|
||||
withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier) throws {
|
||||
public init(
|
||||
derEncoded sequenceNodeIterator: inout ASN1NodeCollection.Iterator,
|
||||
withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier
|
||||
) throws {
|
||||
guard let node = sequenceNodeIterator.next() else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to decode \(Self.self), no ASN.1 nodes to decode")
|
||||
}
|
||||
@@ -1231,7 +1361,10 @@ extension DERImplicitlyTaggable {
|
||||
/// - derEncoded: The DER-encoded bytes representing this object.
|
||||
/// - identifier: The ASN.1 identifier that `derEncoded` is expected to have.
|
||||
@inlinable
|
||||
public init(derEncoded: ArraySlice<UInt8>, withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier) throws {
|
||||
public init(
|
||||
derEncoded: ArraySlice<UInt8>,
|
||||
withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier
|
||||
) throws {
|
||||
self = try .init(derEncoded: DER.parse(derEncoded), withIdentifier: identifier)
|
||||
}
|
||||
|
||||
@@ -1275,7 +1408,9 @@ extension ArraySlice where Element == UInt8 {
|
||||
switch requiredBits {
|
||||
case 0...7:
|
||||
// For 0 to 7 bits, the long form is unacceptable and we require the short.
|
||||
throw ASN1Error.unsupportedFieldLength(reason: "Field length encoded in long form, but DER requires \(length) to be encoded in short form")
|
||||
throw ASN1Error.unsupportedFieldLength(
|
||||
reason: "Field length encoded in long form, but DER requires \(length) to be encoded in short form"
|
||||
)
|
||||
case 8...:
|
||||
// For 8 or more bits, fieldLength should be the minimum required.
|
||||
let requiredBytes = (requiredBits + 7) / 8
|
||||
@@ -1284,7 +1419,9 @@ extension ArraySlice where Element == UInt8 {
|
||||
}
|
||||
default:
|
||||
// This is not reachable, but we'll error anyway.
|
||||
throw ASN1Error.unsupportedFieldLength(reason: "Correctness error: computed required bits as \(requiredBits)")
|
||||
throw ASN1Error.unsupportedFieldLength(
|
||||
reason: "Correctness error: computed required bits as \(requiredBits)"
|
||||
)
|
||||
}
|
||||
|
||||
return length
|
||||
@@ -1346,15 +1483,14 @@ extension Int {
|
||||
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
|
||||
// that requires only one byte. Otherwise, we need multiple bytes: work out how many,
|
||||
// plus one for the length of the length bytes.
|
||||
if self <= 0x7F {
|
||||
return 1
|
||||
} else {
|
||||
guard self <= 0x7F else {
|
||||
// We need to work out how many bytes we need. There are many fancy bit-twiddling
|
||||
// ways of doing this, but honestly we don't do this enough to need them, so we'll
|
||||
// do it the easy way. This math is done on UInt because it makes the shift semantics clean.
|
||||
// We save a branch here because we can never overflow this addition.
|
||||
return UInt(self).neededBytes &+ 1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1374,7 +1510,7 @@ extension ASN1NodeCollection {
|
||||
guard let first = iterator.next() else {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
var previousElement = first
|
||||
while let nextElement = iterator.next() {
|
||||
guard asn1SetElementLessThanOrEqual(previousElement.encodedBytes, nextElement.encodedBytes) else {
|
||||
@@ -1382,7 +1518,7 @@ extension ASN1NodeCollection {
|
||||
}
|
||||
previousElement = nextElement
|
||||
}
|
||||
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1398,7 +1534,7 @@ func asn1SetElementLessThan(_ lhs: ArraySlice<UInt8>, _ rhs: ArraySlice<UInt8>)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// We got to the end of the shorter element, so all current elements are equal.
|
||||
// If lhs is shorter, it comes earlier, _unless_ all of rhs's trailing elements are zero.
|
||||
let trailing = rhs.dropFirst(lhs.count)
|
||||
@@ -1414,5 +1550,3 @@ func asn1SetElementLessThanOrEqual(_ lhs: ArraySlice<UInt8>, _ rhs: ArraySlice<U
|
||||
// https://github.com/apple/swift/blob/43c5824be892967993f4d0111206764eceeffb67/stdlib/public/core/Comparable.swift#L202
|
||||
!asn1SetElementLessThan(rhs, lhs)
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,9 @@ public struct ASN1BitString: DERImplicitlyTaggable {
|
||||
|
||||
// The initial octet explains how many of the bits in the _final_ octet are not part of the bitstring.
|
||||
guard let paddingBits = content.first, (0..<8).contains(paddingBits) else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to determine a valid number of padding bits for ASN1BitString")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Unable to determine a valid number of padding bits for ASN1BitString"
|
||||
)
|
||||
}
|
||||
|
||||
self.paddingBits = Int(paddingBits)
|
||||
@@ -95,7 +97,9 @@ public struct ASN1BitString: DERImplicitlyTaggable {
|
||||
guard let finalByte = self.bytes.last else {
|
||||
if self.paddingBits != 0 {
|
||||
// If there are no bytes, there must be no padding bits.
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid number of padding bits for ASN1BitString: \(self.paddingBits)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid number of padding bits for ASN1BitString: \(self.paddingBits)"
|
||||
)
|
||||
}
|
||||
|
||||
return
|
||||
@@ -106,14 +110,16 @@ public struct ASN1BitString: DERImplicitlyTaggable {
|
||||
// All joking aside, this sets the bottom `self.paddingBits` to 1.
|
||||
let mask = ~(UInt8.max << self.paddingBits)
|
||||
if (finalByte & mask) != 0 {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid padding bits in ASN1BitString: \(self.paddingBits) of padding, \(finalByte) final byte")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid padding bits in ASN1BitString: \(self.paddingBits) of padding, \(finalByte) final byte"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1BitString: Hashable { }
|
||||
extension ASN1BitString: Hashable {}
|
||||
|
||||
extension ASN1BitString: Sendable { }
|
||||
extension ASN1BitString: Sendable {}
|
||||
|
||||
extension ASN1BitString {
|
||||
@inlinable
|
||||
|
||||
@@ -160,9 +160,9 @@ extension ASN1Identifier {
|
||||
public static let utcTime = ASN1Identifier(shortIdentifier: 0x17)
|
||||
}
|
||||
|
||||
extension ASN1Identifier: Hashable { }
|
||||
extension ASN1Identifier: Hashable {}
|
||||
|
||||
extension ASN1Identifier: Sendable { }
|
||||
extension ASN1Identifier: Sendable {}
|
||||
|
||||
extension ASN1Identifier: CustomStringConvertible {
|
||||
@inlinable
|
||||
|
||||
@@ -64,8 +64,7 @@ extension ASN1IntegerRepresentable {
|
||||
//
|
||||
// NOTE – These rules ensure that an integer value is always encoded in the smallest possible number of octets.
|
||||
if let first = dataBytes.first, let second = dataBytes.dropFirst().first {
|
||||
if (first == 0xFF) && second._topBitSet ||
|
||||
(first == 0x00) && !second._topBitSet {
|
||||
if (first == 0xFF) && second._topBitSet || (first == 0x00) && !second._topBitSet {
|
||||
throw ASN1Error.invalidASN1IntegerEncoding(reason: "INTEGER not encoded in fewest number of octets")
|
||||
}
|
||||
}
|
||||
@@ -124,7 +123,9 @@ extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytesCollection<Self>) throws -> ReturnType) rethrows -> ReturnType {
|
||||
public func withBigEndianIntegerBytes<ReturnType>(
|
||||
_ body: (IntegerBytesCollection<Self>) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
return try body(IntegerBytesCollection(self))
|
||||
}
|
||||
}
|
||||
@@ -140,7 +141,7 @@ public struct IntegerBytesCollection<Integer: FixedWidthInteger> {
|
||||
}
|
||||
}
|
||||
|
||||
extension IntegerBytesCollection: Hashable { }
|
||||
extension IntegerBytesCollection: Hashable {}
|
||||
|
||||
extension IntegerBytesCollection: Sendable where Integer: Sendable {}
|
||||
|
||||
@@ -185,29 +186,29 @@ extension IntegerBytesCollection: RandomAccessCollection {
|
||||
}
|
||||
}
|
||||
|
||||
extension IntegerBytesCollection.Index: Hashable { }
|
||||
extension IntegerBytesCollection.Index: Hashable {}
|
||||
|
||||
extension IntegerBytesCollection.Index: Sendable { }
|
||||
extension IntegerBytesCollection.Index: Sendable {}
|
||||
|
||||
extension IntegerBytesCollection.Index: Comparable {
|
||||
// Comparable here is backwards to the original ordering.
|
||||
@inlinable
|
||||
public static func <(lhs: Self, rhs: Self) -> Bool {
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
return lhs._byteNumber > rhs._byteNumber
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func >(lhs: Self, rhs: Self) -> Bool {
|
||||
public static func > (lhs: Self, rhs: Self) -> Bool {
|
||||
return lhs._byteNumber < rhs._byteNumber
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func <=(lhs: Self, rhs: Self) -> Bool {
|
||||
public static func <= (lhs: Self, rhs: Self) -> Bool {
|
||||
return lhs._byteNumber >= rhs._byteNumber
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func >=(lhs: Self, rhs: Self) -> Bool {
|
||||
public static func >= (lhs: Self, rhs: Self) -> Bool {
|
||||
return lhs._byteNumber <= rhs._byteNumber
|
||||
}
|
||||
}
|
||||
@@ -225,25 +226,25 @@ extension IntegerBytesCollection.Index: Strideable {
|
||||
}
|
||||
}
|
||||
|
||||
extension Int8: ASN1IntegerRepresentable { }
|
||||
extension Int8: ASN1IntegerRepresentable {}
|
||||
|
||||
extension UInt8: ASN1IntegerRepresentable { }
|
||||
extension UInt8: ASN1IntegerRepresentable {}
|
||||
|
||||
extension Int16: ASN1IntegerRepresentable { }
|
||||
extension Int16: ASN1IntegerRepresentable {}
|
||||
|
||||
extension UInt16: ASN1IntegerRepresentable { }
|
||||
extension UInt16: ASN1IntegerRepresentable {}
|
||||
|
||||
extension Int32: ASN1IntegerRepresentable { }
|
||||
extension Int32: ASN1IntegerRepresentable {}
|
||||
|
||||
extension UInt32: ASN1IntegerRepresentable { }
|
||||
extension UInt32: ASN1IntegerRepresentable {}
|
||||
|
||||
extension Int64: ASN1IntegerRepresentable { }
|
||||
extension Int64: ASN1IntegerRepresentable {}
|
||||
|
||||
extension UInt64: ASN1IntegerRepresentable { }
|
||||
extension UInt64: ASN1IntegerRepresentable {}
|
||||
|
||||
extension Int: ASN1IntegerRepresentable { }
|
||||
extension Int: ASN1IntegerRepresentable {}
|
||||
|
||||
extension UInt: ASN1IntegerRepresentable { }
|
||||
extension UInt: ASN1IntegerRepresentable {}
|
||||
|
||||
extension RandomAccessCollection where Element == UInt8 {
|
||||
@inlinable
|
||||
|
||||
@@ -21,7 +21,7 @@ public struct ASN1Null: DERImplicitlyTaggable, Hashable, Sendable {
|
||||
|
||||
/// Construct a new ASN.1 null.
|
||||
@inlinable
|
||||
public init() { }
|
||||
public init() {}
|
||||
|
||||
@inlinable
|
||||
public init(derEncoded node: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
|
||||
|
||||
@@ -52,9 +52,9 @@ public struct ASN1OctetString: DERImplicitlyTaggable {
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1OctetString: Hashable { }
|
||||
extension ASN1OctetString: Hashable {}
|
||||
|
||||
extension ASN1OctetString: Sendable { }
|
||||
extension ASN1OctetString: Sendable {}
|
||||
|
||||
extension ASN1OctetString {
|
||||
@inlinable
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
|
||||
extension ArraySlice: DERSerializable where Element == UInt8 { }
|
||||
extension ArraySlice: DERSerializable where Element == UInt8 {}
|
||||
|
||||
extension ArraySlice: DERParseable where Element == UInt8 { }
|
||||
extension ArraySlice: DERParseable where Element == UInt8 {}
|
||||
|
||||
extension ArraySlice: DERImplicitlyTaggable where Element == UInt8 { }
|
||||
extension ArraySlice: DERImplicitlyTaggable where Element == UInt8 {}
|
||||
|
||||
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
||||
// We only use unsigned "bigint"s
|
||||
@@ -32,7 +32,9 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func withBigEndianIntegerBytes<ReturnType>(_ body: (ArraySlice<UInt8>) throws -> ReturnType) rethrows -> ReturnType {
|
||||
public func withBigEndianIntegerBytes<ReturnType>(
|
||||
_ body: (ArraySlice<UInt8>) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
return try body(self)
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,15 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable {
|
||||
/// - seconds: The numerical seconds
|
||||
/// - fractionalSeconds: The numerical fractional seconds.
|
||||
@inlinable
|
||||
public init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int, fractionalSeconds: Double) throws {
|
||||
public init(
|
||||
year: Int,
|
||||
month: Int,
|
||||
day: Int,
|
||||
hours: Int,
|
||||
minutes: Int,
|
||||
seconds: Int,
|
||||
fractionalSeconds: Double
|
||||
) throws {
|
||||
self._year = year
|
||||
self._month = month
|
||||
self._day = day
|
||||
@@ -167,11 +175,15 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable {
|
||||
|
||||
// This also validates the month.
|
||||
guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid month \(self._month) of year \(self.year) for GeneralizedTime")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid month \(self._month) of year \(self.year) for GeneralizedTime"
|
||||
)
|
||||
}
|
||||
|
||||
guard self._day >= 1 && self._day <= daysInMonth else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid day \(self._day) of month \(self._month) for GeneralizedTime")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid day \(self._day) of month \(self._month) for GeneralizedTime"
|
||||
)
|
||||
}
|
||||
|
||||
guard self._hours >= 0 && self._hours < 24 else {
|
||||
@@ -192,14 +204,16 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable {
|
||||
|
||||
// Fractional seconds may not be negative and may not be 1 or more.
|
||||
guard self._fractionalSeconds >= 0 && self._fractionalSeconds < 1 else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid fractional seconds for GeneralizedTime \(self._fractionalSeconds)")
|
||||
throw ASN1Error.invalidASN1Object(
|
||||
reason: "Invalid fractional seconds for GeneralizedTime \(self._fractionalSeconds)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension GeneralizedTime: Comparable {
|
||||
@inlinable
|
||||
public static func <(lhs: GeneralizedTime, rhs: GeneralizedTime) -> Bool {
|
||||
public static func < (lhs: GeneralizedTime, rhs: GeneralizedTime) -> Bool {
|
||||
if lhs.year < rhs.year { return true } else if lhs.year > rhs.year { return false }
|
||||
if lhs.month < rhs.month { return true } else if lhs.month > rhs.month { return false }
|
||||
if lhs.day < rhs.day { return true } else if lhs.day > rhs.day { return false }
|
||||
|
||||
@@ -115,7 +115,7 @@ public struct ASN1ObjectIdentifier: DERImplicitlyTaggable {
|
||||
|
||||
extension ASN1ObjectIdentifier: Hashable {}
|
||||
|
||||
extension ASN1ObjectIdentifier: Sendable { }
|
||||
extension ASN1ObjectIdentifier: Sendable {}
|
||||
|
||||
extension ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
|
||||
@inlinable
|
||||
@@ -256,7 +256,7 @@ extension ASN1ObjectIdentifier {
|
||||
|
||||
/// The 'dc' ('domainComponent' in RFC 1274) attribute type is a string
|
||||
/// holding one component, a label, of a DNS domain name naming a host.
|
||||
public static let domainComponent: ASN1ObjectIdentifier = [0, 9, 2342, 19200300, 100, 1, 25]
|
||||
public static let domainComponent: ASN1ObjectIdentifier = [0, 9, 2342, 19_200_300, 100, 1, 25]
|
||||
|
||||
/// The emailAddress attribute type specifies the electronic-mail address
|
||||
/// or addresses of a subject as an unstructured ASCII string.
|
||||
@@ -281,7 +281,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Invalid encoding for OID subidentifier")
|
||||
}
|
||||
|
||||
let oidSlice = self[self.startIndex ... subidentifierEndIndex]
|
||||
let oidSlice = self[self.startIndex...subidentifierEndIndex]
|
||||
|
||||
guard let firstByte = oidSlice.first, firstByte != 0x80 else {
|
||||
// If the first byte is 0x80 then we have a leading 0 byte. All numbers encoded this way
|
||||
|
||||
@@ -30,7 +30,7 @@ public protocol PEMSerializable: DERSerializable {
|
||||
/// -----END defaultPEMDiscriminator-----
|
||||
/// ```
|
||||
static var defaultPEMDiscriminator: String { get }
|
||||
|
||||
|
||||
func serializeAsPEM(discriminator: String) throws -> PEMDocument
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ public protocol PEMParseable: DERParseable {
|
||||
/// -----END defaultPEMDiscriminator-----
|
||||
/// ```
|
||||
static var defaultPEMDiscriminator: String { get }
|
||||
|
||||
|
||||
init(pemDocument: PEMDocument) throws
|
||||
}
|
||||
|
||||
@@ -63,9 +63,9 @@ public protocol PEMParseable: DERParseable {
|
||||
public typealias PEMRepresentable = PEMSerializable & PEMParseable
|
||||
|
||||
extension PEMParseable {
|
||||
|
||||
|
||||
/// Initialize this object from a serialized PEM representation.
|
||||
///
|
||||
///
|
||||
/// This will check that the discriminator matches ``PEMParseable/defaultPEMDiscriminator``, decode the base64 encoded string and
|
||||
/// then decode the DER encoded bytes using ``DERParseable/init(derEncoded:)-i2rf``.
|
||||
///
|
||||
@@ -75,7 +75,7 @@ extension PEMParseable {
|
||||
public init(pemEncoded pemString: String) throws {
|
||||
try self.init(pemDocument: try PEMDocument(pemString: pemString))
|
||||
}
|
||||
|
||||
|
||||
/// Initialize this object from a serialized PEM representation.
|
||||
/// This will check that the ``PEMParseable/pemDiscriminator`` matches and
|
||||
/// forward the DER encoded bytes to ``DERParseable/init(derEncoded:)-i2rf``.
|
||||
@@ -85,9 +85,12 @@ extension PEMParseable {
|
||||
@inlinable
|
||||
public init(pemDocument: PEMDocument) throws {
|
||||
guard pemDocument.discriminator == Self.defaultPEMDiscriminator else {
|
||||
throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.defaultPEMDiscriminator) instead")
|
||||
throw ASN1Error.invalidPEMDocument(
|
||||
reason:
|
||||
"PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.defaultPEMDiscriminator) instead"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
try self.init(derEncoded: pemDocument.derBytes)
|
||||
}
|
||||
}
|
||||
@@ -100,10 +103,10 @@ extension PEMSerializable {
|
||||
public func serializeAsPEM(discriminator: String) throws -> PEMDocument {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.serialize(self)
|
||||
|
||||
|
||||
return PEMDocument(type: discriminator, derBytes: serializer.serializedBytes)
|
||||
}
|
||||
|
||||
|
||||
/// Serializes `self` as a PEM document with the ``defaultPEMDiscriminator``.
|
||||
@inlinable
|
||||
public func serializeAsPEM() throws -> PEMDocument {
|
||||
@@ -115,13 +118,12 @@ extension PEMSerializable {
|
||||
public struct PEMDocument: Hashable, Sendable {
|
||||
fileprivate static let lineLength = 64
|
||||
|
||||
|
||||
@available(*, deprecated, renamed: "discriminator")
|
||||
public var type: String {
|
||||
get { discriminator }
|
||||
set { discriminator = newValue }
|
||||
}
|
||||
|
||||
|
||||
/// The PEM discriminator is in the first line of a PEM string after `BEGIN` and at the end of the string after `END` e.g.
|
||||
/// ```
|
||||
/// -----BEGIN discriminator-----
|
||||
@@ -129,7 +131,7 @@ public struct PEMDocument: Hashable, Sendable {
|
||||
/// -----END discriminator-----
|
||||
/// ```
|
||||
public var discriminator: String
|
||||
|
||||
|
||||
public var derBytes: [UInt8]
|
||||
|
||||
public init(pemString: String) throws {
|
||||
@@ -155,7 +157,8 @@ public struct PEMDocument: Hashable, Sendable {
|
||||
lines = lines.dropFirst().dropLast()
|
||||
guard lines.count > 0,
|
||||
lines.dropLast().allSatisfy({ $0.utf8.count == PEMDocument.lineLength }),
|
||||
lines.last!.utf8.count <= PEMDocument.lineLength else {
|
||||
lines.last!.utf8.count <= PEMDocument.lineLength
|
||||
else {
|
||||
throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect line lengths")
|
||||
}
|
||||
|
||||
@@ -189,7 +192,9 @@ public struct PEMDocument: Hashable, Sendable {
|
||||
pemLines.append("-----BEGIN \(self.discriminator)-----")
|
||||
|
||||
while encoded.count > 0 {
|
||||
let prefixIndex = encoded.index(encoded.startIndex, offsetBy: Self.lineLength, limitedBy: encoded.endIndex) ?? encoded.endIndex
|
||||
let prefixIndex =
|
||||
encoded.index(encoded.startIndex, offsetBy: Self.lineLength, limitedBy: encoded.endIndex)
|
||||
?? encoded.endIndex
|
||||
pemLines.append(encoded[..<prefixIndex])
|
||||
encoded = encoded[prefixIndex...]
|
||||
}
|
||||
|
||||
@@ -21,8 +21,9 @@ enum TimeUtilities {
|
||||
// First, there must always be a calendar date. No separators, 4
|
||||
// digits for the year, 2 digits for the month, 2 digits for the day.
|
||||
guard let rawYear = bytes._readFourDigitDecimalInteger(),
|
||||
let rawMonth = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawDay = bytes._readTwoDigitDecimalInteger() else {
|
||||
let rawMonth = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawDay = bytes._readTwoDigitDecimalInteger()
|
||||
else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to load year, month, and day for GeneralizedTime")
|
||||
}
|
||||
|
||||
@@ -30,8 +31,9 @@ enum TimeUtilities {
|
||||
// to at least seconds, there are no separators, there is no time-zone (but there must be a 'Z'),
|
||||
// and there may be fractional seconds but they must not have trailing zeros.
|
||||
guard let rawHour = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawMinutes = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawSeconds = bytes._readTwoDigitDecimalInteger() else {
|
||||
let rawMinutes = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawSeconds = bytes._readTwoDigitDecimalInteger()
|
||||
else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to load hour, minutes, and seconds for GeneralizedTime")
|
||||
}
|
||||
|
||||
@@ -51,13 +53,15 @@ enum TimeUtilities {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Trailing bytes in GeneralizedTime")
|
||||
}
|
||||
|
||||
return try GeneralizedTime(year: rawYear,
|
||||
month: rawMonth,
|
||||
day: rawDay,
|
||||
hours: rawHour,
|
||||
minutes: rawMinutes,
|
||||
seconds: rawSeconds,
|
||||
fractionalSeconds: fractionalSeconds)
|
||||
return try GeneralizedTime(
|
||||
year: rawYear,
|
||||
month: rawMonth,
|
||||
day: rawDay,
|
||||
hours: rawHour,
|
||||
minutes: rawMinutes,
|
||||
seconds: rawSeconds,
|
||||
fractionalSeconds: fractionalSeconds
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -67,16 +71,18 @@ enum TimeUtilities {
|
||||
// First, there must always be a calendar date. No separators, 2
|
||||
// digits for the year, 2 digits for the month, 2 digits for the day.
|
||||
guard let rawYear = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawMonth = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawDay = bytes._readTwoDigitDecimalInteger() else {
|
||||
let rawMonth = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawDay = bytes._readTwoDigitDecimalInteger()
|
||||
else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to load year, month, and day for UTCTime")
|
||||
}
|
||||
|
||||
// Next there must be a _time_. Per DER rules, this time must always go
|
||||
// to at least seconds, there are no separators, there is no time-zone (but there must be a 'Z').
|
||||
guard let rawHour = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawMinutes = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawSeconds = bytes._readTwoDigitDecimalInteger() else {
|
||||
let rawMinutes = bytes._readTwoDigitDecimalInteger(),
|
||||
let rawSeconds = bytes._readTwoDigitDecimalInteger()
|
||||
else {
|
||||
throw ASN1Error.invalidASN1Object(reason: "Unable to load hour, minutes, and seconds for UTCTime")
|
||||
}
|
||||
|
||||
@@ -92,12 +98,14 @@ enum TimeUtilities {
|
||||
|
||||
let actualYear = rawYear < 50 ? rawYear &+ 2000 : rawYear &+ 1900
|
||||
|
||||
return try UTCTime(year: actualYear,
|
||||
month: rawMonth,
|
||||
day: rawDay,
|
||||
hours: rawHour,
|
||||
minutes: rawMinutes,
|
||||
seconds: rawSeconds)
|
||||
return try UTCTime(
|
||||
year: actualYear,
|
||||
month: rawMonth,
|
||||
day: rawDay,
|
||||
hours: rawHour,
|
||||
minutes: rawMinutes,
|
||||
seconds: rawSeconds
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -141,7 +149,8 @@ extension ArraySlice where Element == UInt8 {
|
||||
@inlinable
|
||||
mutating func _readFourDigitDecimalInteger() -> Int? {
|
||||
guard let first = self._readTwoDigitDecimalInteger(),
|
||||
let second = self._readTwoDigitDecimalInteger() else {
|
||||
let second = self._readTwoDigitDecimalInteger()
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -153,12 +162,14 @@ extension ArraySlice where Element == UInt8 {
|
||||
@inlinable
|
||||
mutating func _readTwoDigitDecimalInteger() -> Int? {
|
||||
guard let firstASCII = self.popFirst(),
|
||||
let secondASCII = self.popFirst() else {
|
||||
let secondASCII = self.popFirst()
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let first = Int(fromDecimalASCII: firstASCII),
|
||||
let second = Int(fromDecimalASCII: secondASCII) else {
|
||||
let second = Int(fromDecimalASCII: secondASCII)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -175,7 +186,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
var numerator = 0
|
||||
var denominator = 1
|
||||
|
||||
while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) {
|
||||
while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) {
|
||||
self = self.dropFirst()
|
||||
|
||||
let (newNumerator, multiplyOverflow) = numerator.multipliedReportingOverflow(by: 10)
|
||||
|
||||
@@ -183,7 +183,7 @@ public struct UTCTime: DERImplicitlyTaggable, Hashable, Sendable {
|
||||
|
||||
extension UTCTime: Comparable {
|
||||
@inlinable
|
||||
public static func <(lhs: UTCTime, rhs: UTCTime) -> Bool {
|
||||
public static func < (lhs: UTCTime, rhs: UTCTime) -> Bool {
|
||||
if lhs.year < rhs.year { return true } else if lhs.year > rhs.year { return false }
|
||||
if lhs.month < rhs.month { return true } else if lhs.month > rhs.month { return false }
|
||||
if lhs.day < rhs.day { return true } else if lhs.day > rhs.day { return false }
|
||||
|
||||
@@ -49,11 +49,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// The ASN.1 tag for the parsed field does not match the tag expected for the field.
|
||||
@inline(never)
|
||||
public static func unexpectedFieldType(
|
||||
_ identifier: ASN1Identifier, file: String = #fileID, line: UInt = #line
|
||||
_ identifier: ASN1Identifier,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .unexpectedFieldType, reason: "\(identifier)", file: file, line: line
|
||||
code: .unexpectedFieldType,
|
||||
reason: "\(identifier)",
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -62,11 +67,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// being decoded.
|
||||
@inline(never)
|
||||
public static func invalidASN1Object(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
reason: String,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .invalidASN1Object, reason: reason, file: file, line: line
|
||||
code: .invalidASN1Object,
|
||||
reason: reason,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -74,11 +84,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding.
|
||||
@inline(never)
|
||||
public static func invalidASN1IntegerEncoding(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
reason: String,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .invalidASN1IntegerEncoding, reason: reason, file: file, line: line
|
||||
code: .invalidASN1IntegerEncoding,
|
||||
reason: reason,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -86,11 +101,15 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// An ASN.1 field was truncated and could not be decoded.
|
||||
@inline(never)
|
||||
public static func truncatedASN1Field(
|
||||
file: String = #fileID, line: UInt = #line
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .truncatedASN1Field, reason: "", file: file, line: line
|
||||
code: .truncatedASN1Field,
|
||||
reason: "",
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -98,11 +117,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// The encoding used for the field length is not supported.
|
||||
@inline(never)
|
||||
public static func unsupportedFieldLength(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
reason: String,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .unsupportedFieldLength, reason: reason, file: file, line: line
|
||||
code: .unsupportedFieldLength,
|
||||
reason: reason,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -110,11 +134,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// It was not possible to parse a string as a PEM document.
|
||||
@inline(never)
|
||||
public static func invalidPEMDocument(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
reason: String,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .invalidPEMDocument, reason: reason, file: file, line: line
|
||||
code: .invalidPEMDocument,
|
||||
reason: reason,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -122,11 +151,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible {
|
||||
/// A string was invalid.
|
||||
@inline(never)
|
||||
public static func invalidStringRepresentation(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
reason: String,
|
||||
file: String = #fileID,
|
||||
line: UInt = #line
|
||||
) -> ASN1Error {
|
||||
return ASN1Error(
|
||||
backing: .init(
|
||||
code: .invalidStringRepresentation, reason: reason, file: file, line: line
|
||||
code: .invalidStringRepresentation,
|
||||
reason: reason,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -206,7 +240,7 @@ extension ASN1Error {
|
||||
}
|
||||
|
||||
// Only the error code matters for equality.
|
||||
static func ==(lhs: Backing, rhs: Backing) -> Bool {
|
||||
static func == (lhs: Backing, rhs: Backing) -> Bool {
|
||||
return lhs.code == rhs.code
|
||||
}
|
||||
|
||||
@@ -215,4 +249,3 @@ extension ASN1Error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,12 @@ import XCTest
|
||||
class ASN1Tests: XCTestCase {
|
||||
func testSimpleASN1P256SPKI() throws {
|
||||
// Given a static SPKI structure, verifies the parse.
|
||||
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
|
||||
let encodedSPKI =
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
|
||||
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
|
||||
|
||||
let encodedExpectedKeyBytes = "BNmnTK3Ru2lH2R+e2nihRTNNXT55MQtfEnEW+GeqaDAYCbWJVbXfZcut1Eb+e2VtDXLNS4mQe1gE297L7vtXOx0="
|
||||
let encodedExpectedKeyBytes =
|
||||
"BNmnTK3Ru2lH2R+e2nihRTNNXT55MQtfEnEW+GeqaDAYCbWJVbXfZcut1Eb+e2VtDXLNS4mQe1gE297L7vtXOx0="
|
||||
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedSPKI)
|
||||
@@ -40,10 +42,12 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testSimpleASN1P384SPKI() throws {
|
||||
let encodedSPKI = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEcBr0TNmgagf1ysckEA/3XLGx2amgzeHjDBZREqhCIVBrLhIiIR4zrJ8dqad/Y+zI2Hu8TIUbrzS/diFpFoE0YYKBTfYMCAUtaWuMb1oaBdFzWsLfYSSzF+ON1yeJCtro"
|
||||
let encodedSPKI =
|
||||
"MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEcBr0TNmgagf1ysckEA/3XLGx2amgzeHjDBZREqhCIVBrLhIiIR4zrJ8dqad/Y+zI2Hu8TIUbrzS/diFpFoE0YYKBTfYMCAUtaWuMb1oaBdFzWsLfYSSzF+ON1yeJCtro"
|
||||
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
|
||||
|
||||
let encodedExpectedKeyBytes = "BHAa9EzZoGoH9crHJBAP91yxsdmpoM3h4wwWURKoQiFQay4SIiEeM6yfHamnf2PsyNh7vEyFG680v3YhaRaBNGGCgU32DAgFLWlrjG9aGgXRc1rC32EksxfjjdcniQra6A=="
|
||||
let encodedExpectedKeyBytes =
|
||||
"BHAa9EzZoGoH9crHJBAP91yxsdmpoM3h4wwWURKoQiFQay4SIiEeM6yfHamnf2PsyNh7vEyFG680v3YhaRaBNGGCgU32DAgFLWlrjG9aGgXRc1rC32EksxfjjdcniQra6A=="
|
||||
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedSPKI)
|
||||
@@ -59,10 +63,12 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testSimpleASN1P521SPKI() throws {
|
||||
let encodedSPKI = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBTxMJZTRr9NcKmD7iTeX7ofcgz77JPTIDXOHFfS1tZHd9P0uAeK/ARwwDdsQpIKCvmtaO4O52oHqmczdrRwGtrHIBUTqaOw2Fqdiqt0fRQju9wH1Xi4h8u0h80MymUM0sbAQ70jHCeV0S0mGcJS8t3nfP+qLes30h297dPfV3SLsLg8M="
|
||||
let encodedSPKI =
|
||||
"MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBTxMJZTRr9NcKmD7iTeX7ofcgz77JPTIDXOHFfS1tZHd9P0uAeK/ARwwDdsQpIKCvmtaO4O52oHqmczdrRwGtrHIBUTqaOw2Fqdiqt0fRQju9wH1Xi4h8u0h80MymUM0sbAQ70jHCeV0S0mGcJS8t3nfP+qLes30h297dPfV3SLsLg8M="
|
||||
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
|
||||
|
||||
let encodedExpectedKeyBytes = "BAFPEwllNGv01wqYPuJN5fuh9yDPvsk9MgNc4cV9LW1kd30/S4B4r8BHDAN2xCkgoK+a1o7g7nageqZzN2tHAa2scgFROpo7DYWp2Kq3R9FCO73AfVeLiHy7SHzQzKZQzSxsBDvSMcJ5XRLSYZwlLy3ed8/6ot6zfSHb3t099XdIuwuDww=="
|
||||
let encodedExpectedKeyBytes =
|
||||
"BAFPEwllNGv01wqYPuJN5fuh9yDPvsk9MgNc4cV9LW1kd30/S4B4r8BHDAN2xCkgoK+a1o7g7nageqZzN2tHAa2scgFROpo7DYWp2Kq3R9FCO73AfVeLiHy7SHzQzKZQzSxsBDvSMcJ5XRLSYZwlLy3ed8/6ot6zfSHb3t099XdIuwuDww=="
|
||||
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedSPKI)
|
||||
@@ -78,13 +84,15 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1SEC1PrivateKeyP256() throws {
|
||||
let encodedPrivateKey = "MHcCAQEEIFAV2+taX2/ht9HEcLQPtfyuRktTkn4S3RaCQwDmDnrloAoGCCqGSM49AwEHoUQDQgAE3Oed98X0hHmzHmmmgtf5rAVEv0jIeH61K61P5UyiCozn+fz+mlmBywvluiVvERiT9WZCd3tkPPWwbIr+a0dnwA=="
|
||||
let encodedPrivateKey =
|
||||
"MHcCAQEEIFAV2+taX2/ht9HEcLQPtfyuRktTkn4S3RaCQwDmDnrloAoGCCqGSM49AwEHoUQDQgAE3Oed98X0hHmzHmmmgtf5rAVEv0jIeH61K61P5UyiCozn+fz+mlmBywvluiVvERiT9WZCd3tkPPWwbIr+a0dnwA=="
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "UBXb61pfb+G30cRwtA+1/K5GS1OSfhLdFoJDAOYOeuU="
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BNznnffF9IR5sx5ppoLX+awFRL9IyHh+tSutT+VMogqM5/n8/ppZgcsL5bolbxEYk/VmQnd7ZDz1sGyK/mtHZ8A="
|
||||
let encodedPublicKeyBytes =
|
||||
"BNznnffF9IR5sx5ppoLX+awFRL9IyHh+tSutT+VMogqM5/n8/ppZgcsL5bolbxEYk/VmQnd7ZDz1sGyK/mtHZ8A="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -101,13 +109,15 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1SEC1PrivateKeyP384() throws {
|
||||
let encodedPrivateKey = "MIGkAgEBBDAWv9iH6ZivZKtk5ihjvjlZCYc9JHyykqvmJ7JVQ50ZZWTkCPtIe7RSKzm+l7NJltqgBwYFK4EEACKhZANiAAQz0BBmMxeOj5XwTL1G4fqTYO2UAiYrUMixiRFlFKVY5I6jAgiEWdNbmte8o6dByo0No5YoyDHdG637xvuzGaWd+IT5LoBAVVv3AgL3ao3dA4aVhm6Yz6G6/2o3X7AH99c="
|
||||
let encodedPrivateKey =
|
||||
"MIGkAgEBBDAWv9iH6ZivZKtk5ihjvjlZCYc9JHyykqvmJ7JVQ50ZZWTkCPtIe7RSKzm+l7NJltqgBwYFK4EEACKhZANiAAQz0BBmMxeOj5XwTL1G4fqTYO2UAiYrUMixiRFlFKVY5I6jAgiEWdNbmte8o6dByo0No5YoyDHdG637xvuzGaWd+IT5LoBAVVv3AgL3ao3dA4aVhm6Yz6G6/2o3X7AH99c="
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "Fr/Yh+mYr2SrZOYoY745WQmHPSR8spKr5ieyVUOdGWVk5Aj7SHu0Uis5vpezSZba"
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BDPQEGYzF46PlfBMvUbh+pNg7ZQCJitQyLGJEWUUpVjkjqMCCIRZ01ua17yjp0HKjQ2jlijIMd0brfvG+7MZpZ34hPkugEBVW/cCAvdqjd0DhpWGbpjPobr/ajdfsAf31w=="
|
||||
let encodedPublicKeyBytes =
|
||||
"BDPQEGYzF46PlfBMvUbh+pNg7ZQCJitQyLGJEWUUpVjkjqMCCIRZ01ua17yjp0HKjQ2jlijIMd0brfvG+7MZpZ34hPkugEBVW/cCAvdqjd0DhpWGbpjPobr/ajdfsAf31w=="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -124,13 +134,16 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1SEC1PrivateKeyP521() throws {
|
||||
let encodedPrivateKey = "MIHcAgEBBEIBONszidL11f7D8LEbVGKG4A7768X16w35/m6OSPO7MGQcYhWHpgSV4NZ6AFKcksavZSCa59lYdAN+MA3sUjO7R/mgBwYFK4EEACOhgYkDgYYABAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
|
||||
let encodedPrivateKey =
|
||||
"MIHcAgEBBEIBONszidL11f7D8LEbVGKG4A7768X16w35/m6OSPO7MGQcYhWHpgSV4NZ6AFKcksavZSCa59lYdAN+MA3sUjO7R/mgBwYFK4EEACOhgYkDgYYABAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "ATjbM4nS9dX+w/CxG1RihuAO++vF9esN+f5ujkjzuzBkHGIVh6YEleDWegBSnJLGr2UgmufZWHQDfjAN7FIzu0f5"
|
||||
let encodedPrivateKeyBytes =
|
||||
"ATjbM4nS9dX+w/CxG1RihuAO++vF9esN+f5ujkjzuzBkHGIVh6YEleDWegBSnJLGr2UgmufZWHQDfjAN7FIzu0f5"
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
|
||||
let encodedPublicKeyBytes =
|
||||
"BAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -147,13 +160,15 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1PKCS8PrivateKeyP256() throws {
|
||||
let encodedPrivateKey = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bahRANCAATDXEj3jviAtzgx4bnMa/081v+FXbp7O5D1KtKVdje+ckejGVLYuYKE4Lpf5jonefi6wtoCc/sWHlbLiNV5PEB9"
|
||||
let encodedPrivateKey =
|
||||
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bahRANCAATDXEj3jviAtzgx4bnMa/081v+FXbp7O5D1KtKVdje+ckejGVLYuYKE4Lpf5jonefi6wtoCc/sWHlbLiNV5PEB9"
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "CRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bY="
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BMNcSPeO+IC3ODHhucxr/TzW/4Vduns7kPUq0pV2N75yR6MZUti5goTgul/mOid5+LrC2gJz+xYeVsuI1Xk8QH0="
|
||||
let encodedPublicKeyBytes =
|
||||
"BMNcSPeO+IC3ODHhucxr/TzW/4Vduns7kPUq0pV2N75yR6MZUti5goTgul/mOid5+LrC2gJz+xYeVsuI1Xk8QH0="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -171,13 +186,15 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1PKCS8PrivateKeyP384() throws {
|
||||
let encodedPrivateKey = "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCKfeRAkTtGQG7bGao6Ca5MDDcmxttyr6HNmNoaSkmuYvBtLGLLBWm1+VHT602xOIihZANiAAS56RzXiLO5YvFI0qh/+T9DhOXfkm3K/jJSUAqV/hP0FUlIUR824cFVdMMQA1S100mETsxdT0QDqUGAinMTUBSyk9y+jR33Fw/A068ZQRlqTCa0ThS0vwxKhM/M4vhYeDE="
|
||||
let encodedPrivateKey =
|
||||
"MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCKfeRAkTtGQG7bGao6Ca5MDDcmxttyr6HNmNoaSkmuYvBtLGLLBWm1+VHT602xOIihZANiAAS56RzXiLO5YvFI0qh/+T9DhOXfkm3K/jJSUAqV/hP0FUlIUR824cFVdMMQA1S100mETsxdT0QDqUGAinMTUBSyk9y+jR33Fw/A068ZQRlqTCa0ThS0vwxKhM/M4vhYeDE="
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "in3kQJE7RkBu2xmqOgmuTAw3Jsbbcq+hzZjaGkpJrmLwbSxiywVptflR0+tNsTiI"
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BLnpHNeIs7li8UjSqH/5P0OE5d+Sbcr+MlJQCpX+E/QVSUhRHzbhwVV0wxADVLXTSYROzF1PRAOpQYCKcxNQFLKT3L6NHfcXD8DTrxlBGWpMJrROFLS/DEqEz8zi+Fh4MQ=="
|
||||
let encodedPublicKeyBytes =
|
||||
"BLnpHNeIs7li8UjSqH/5P0OE5d+Sbcr+MlJQCpX+E/QVSUhRHzbhwVV0wxADVLXTSYROzF1PRAOpQYCKcxNQFLKT3L6NHfcXD8DTrxlBGWpMJrROFLS/DEqEz8zi+Fh4MQ=="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -195,13 +212,16 @@ class ASN1Tests: XCTestCase {
|
||||
}
|
||||
|
||||
func testASN1PKCS8PrivateKeyP521() throws {
|
||||
let encodedPrivateKey = "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIB/rwbfr3a+rdHQvKToS6Fw1WxsVFy3Wq2ylWC+EyQv//nGiT5TQYIAV2WDmmud3WnczITapXAAe6eS66jHa+OxyGhgYkDgYYABADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ=="
|
||||
let encodedPrivateKey =
|
||||
"MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIB/rwbfr3a+rdHQvKToS6Fw1WxsVFy3Wq2ylWC+EyQv//nGiT5TQYIAV2WDmmud3WnczITapXAAe6eS66jHa+OxyGhgYkDgYYABADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ=="
|
||||
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
|
||||
|
||||
let encodedPrivateKeyBytes = "Af68G3692vq3R0Lyk6EuhcNVsbFRct1qtspVgvhMkL//5xok+U0GCAFdlg5prnd1p3MyE2qVwAHunkuuox2vjsch"
|
||||
let encodedPrivateKeyBytes =
|
||||
"Af68G3692vq3R0Lyk6EuhcNVsbFRct1qtspVgvhMkL//5xok+U0GCAFdlg5prnd1p3MyE2qVwAHunkuuox2vjsch"
|
||||
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
|
||||
|
||||
let encodedPublicKeyBytes = "BADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ=="
|
||||
let encodedPublicKeyBytes =
|
||||
"BADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ=="
|
||||
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
|
||||
|
||||
let result = try DER.parse(decodedPrivateKey)
|
||||
@@ -220,7 +240,8 @@ class ASN1Tests: XCTestCase {
|
||||
|
||||
func testRejectDripFedASN1SPKIP256() throws {
|
||||
// This test drip-feeds an ASN.1 P256 SPKI block. It should never parse correctly until we feed the entire block.
|
||||
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
|
||||
let encodedSPKI =
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
|
||||
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
|
||||
|
||||
for index in decodedSPKI.indices {
|
||||
@@ -416,12 +437,12 @@ class ASN1Tests: XCTestCase {
|
||||
|
||||
func testStraightforwardPEMDocumentParsing() throws {
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
let document = try PEMDocument(pemString: simplePEM)
|
||||
XCTAssertEqual(document.discriminator, "EC PRIVATE KEY")
|
||||
XCTAssertEqual(document.derBytes.count, 121)
|
||||
@@ -437,15 +458,15 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
let reserialized2 = PEMDocument(type: "EC PRIVATE KEY", derBytes: serializer.serializedBytes)
|
||||
XCTAssertEqual(reserialized2.pemString, simplePEM)
|
||||
}
|
||||
|
||||
|
||||
func testStraightforwardPEMParsing() throws {
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
let pkey = try SEC1PrivateKey(pemEncoded: simplePEM)
|
||||
|
||||
let reserialized = try pkey.serializeAsPEM().pemString
|
||||
@@ -460,12 +481,12 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
func testTruncatedPEMDocumentsAreRejected() throws {
|
||||
// We drip feed the PEM one extra character at a time. It never parses successfully.
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
for index in simplePEM.indices.dropLast() {
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: String(simplePEM[..<index]))) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
@@ -474,7 +495,7 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
XCTAssertNoThrow(try PEMDocument(pemString: simplePEM))
|
||||
XCTAssertNoThrow(try SEC1PrivateKey(pemEncoded: simplePEM))
|
||||
}
|
||||
@@ -482,16 +503,16 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
func testMismatchedDiscriminatorsAreRejected() throws {
|
||||
// Different discriminators is not allowed.
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PUBLIC KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PUBLIC KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertThrowsError(try SEC1PrivateKey(pemEncoded: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
@@ -500,16 +521,16 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
func testOverlongLinesAreForbidden() throws {
|
||||
// This is arguably an excessive restriction, but we should try to be fairly strict here.
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzGO
|
||||
9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzGO
|
||||
9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertThrowsError(try SEC1PrivateKey(pemEncoded: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
@@ -518,16 +539,16 @@ AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzGO
|
||||
func testEarlyShortLinesAreForbidden() throws {
|
||||
// This is arguably an excessive restriction, but we should try to be fairly strict here.
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJz
|
||||
GO9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJz
|
||||
GO9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertThrowsError(try SEC1PrivateKey(pemEncoded: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
@@ -535,13 +556,13 @@ GO9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
|
||||
func testEmptyPEMDocument() throws {
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertThrowsError(try SEC1PrivateKey(pemEncoded: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
@@ -549,16 +570,16 @@ GO9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
|
||||
|
||||
func testInvalidBase64IsForbidden() throws {
|
||||
let simplePEM = """
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
|
||||
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
|
||||
O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
-----END EC PRIVATE KEY-----
|
||||
"""
|
||||
XCTAssertThrowsError(try PEMDocument(pemString: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
|
||||
|
||||
XCTAssertThrowsError(try SEC1PrivateKey(pemEncoded: simplePEM)) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidPEMDocument)
|
||||
}
|
||||
@@ -601,7 +622,6 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testBitstringWithNoContent() throws {
|
||||
// We don't allow bitstrings with no content.
|
||||
let weirdBitString: [UInt8] = [0x03, 0x00]
|
||||
@@ -658,15 +678,17 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
func testNotConsumingTaggedObject() throws {
|
||||
// We should error if there are two nodes inside an explicitly tagged object.
|
||||
let weirdASN1: [UInt8] = [
|
||||
0x30, 0x08, // Sequence, containing...
|
||||
0xA2, 0x06, // Context specific tag 2, 3 byte body, containing...
|
||||
0x02, 0x01, 0x00, // Integer 0 and
|
||||
0x02, 0x01, 0x01 // Integer 1
|
||||
0x30, 0x08, // Sequence, containing...
|
||||
0xA2, 0x06, // Context specific tag 2, 3 byte body, containing...
|
||||
0x02, 0x01, 0x00, // Integer 0 and
|
||||
0x02, 0x01, 0x01, // Integer 1
|
||||
|
||||
]
|
||||
let parsed = try DER.parse(weirdASN1)
|
||||
try DER.sequence(parsed, identifier: .sequence) { nodes in
|
||||
XCTAssertThrowsError(try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific, { _ in })) { error in
|
||||
XCTAssertThrowsError(
|
||||
try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific, { _ in })
|
||||
) { error in
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object)
|
||||
}
|
||||
}
|
||||
@@ -674,7 +696,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
|
||||
func testSPKIWithUnexpectedKeyTypeOID() throws {
|
||||
// This is an SPKI object for RSA instead of EC. This is a 1024-bit RSA key, so hopefully no-one will think to use it.
|
||||
let rsaSPKI = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQEcP8qgwq5JhGgl1mKMeOWbb0WFKkJKj4Tvm4RFWGKDYg/p+Fm8vHwPSICqU9HJ+dHF2Ty0M6WVwVlf6RJdJGsrp1s9cbxfc/74PdQUssIhUjhlBO2RFlQECbgNpw5UleRB9FLnEDp33qMgdr7nwXiYCTjd04QSkdU3mXJYrFfwIDAQAB"
|
||||
let rsaSPKI =
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQEcP8qgwq5JhGgl1mKMeOWbb0WFKkJKj4Tvm4RFWGKDYg/p+Fm8vHwPSICqU9HJ+dHF2Ty0M6WVwVlf6RJdJGsrp1s9cbxfc/74PdQUssIhUjhlBO2RFlQECbgNpw5UleRB9FLnEDp33qMgdr7nwXiYCTjd04QSkdU3mXJYrFfwIDAQAB"
|
||||
let decodedSPKI = Array(Data(base64Encoded: rsaSPKI)!)
|
||||
|
||||
var serializer = DER.Serializer()
|
||||
@@ -695,17 +718,18 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
78, 249, 184, 68, 85, 134, 40, 54, 32, 254, 159, 133, 155, 203, 199, 192,
|
||||
244, 136, 10, 165, 61, 28, 159, 157, 28, 93, 147, 203, 67, 58, 89, 92,
|
||||
21, 149, 254, 145, 37, 210, 70, 178, 186, 117, 179, 215, 27, 197, 247,
|
||||
63, 239, 131, 221, 65, 75, 44, 34, 21, 35, 134, 80, 78, 217, 17, 101, 64
|
||||
, 64, 155, 128, 218, 112, 229, 73, 94, 68, 31, 69, 46, 113, 3, 167, 125,
|
||||
63, 239, 131, 221, 65, 75, 44, 34, 21, 35, 134, 80, 78, 217, 17, 101, 64, 64, 155, 128, 218, 112, 229, 73,
|
||||
94, 68, 31, 69, 46, 113, 3, 167, 125,
|
||||
234, 50, 7, 107, 238, 124, 23, 137, 128, 147, 141, 221, 56, 65, 41, 29,
|
||||
83, 121, 151, 37, 138, 197, 127, 2, 3, 1, 0, 1
|
||||
83, 121, 151, 37, 138, 197, 127, 2, 3, 1, 0, 1,
|
||||
]
|
||||
XCTAssertEqual(spki.key.bytes, expectedKey)
|
||||
}
|
||||
|
||||
func testSPKIWithUnsupportedCurve() throws {
|
||||
// This is an EC SPKI object with an unsupported named curve.
|
||||
let b64SPKI = "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEzN09Sbb+mhMIlUbOdoIoND8lNcoQPd/yZDjQi1IDyDQEvVvz1yhi5J0FPLAlM3hE2o/a+rASUz2UP4fX5Cpnxw=="
|
||||
let b64SPKI =
|
||||
"MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEzN09Sbb+mhMIlUbOdoIoND8lNcoQPd/yZDjQi1IDyDQEvVvz1yhi5J0FPLAlM3hE2o/a+rASUz2UP4fX5Cpnxw=="
|
||||
let decodedSPKI = Array(Data(base64Encoded: b64SPKI)!)
|
||||
|
||||
let parsed = try DER.parse(decodedSPKI)
|
||||
@@ -718,7 +742,7 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
52, 63, 37, 53, 202, 16, 61, 223, 242, 100, 56, 208, 139, 82, 3, 200,
|
||||
52, 4, 189, 91, 243, 215, 40, 98, 228, 157, 5, 60, 176, 37, 51, 120, 68,
|
||||
218, 143, 218, 250, 176, 18, 83, 61, 148, 63, 135, 215, 228, 42, 103,
|
||||
199
|
||||
199,
|
||||
]
|
||||
XCTAssertEqual(spki.key.bytes, expectedKey)
|
||||
}
|
||||
@@ -735,7 +759,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
|
||||
func testSEC1PrivateKeyUnsupportedKeyType() throws {
|
||||
// This is an EC SPKI object with an unsupported named curve.
|
||||
let b64SEC1 = "MHQCAQEEINIuVmNF7g1wNCJWXDpgL+09jATtaS1n0SxqqQneHi+woAcGBSuBBAAKoUQDQgAEB7v/p7gvuV0aDx02EF6a+pr563p+FzRJXI+COWHdr+XRcjg6vEi4n3Jj7ksmEg4t1x6E1xFyTvF3eV/B/XVXbw=="
|
||||
let b64SEC1 =
|
||||
"MHQCAQEEINIuVmNF7g1wNCJWXDpgL+09jATtaS1n0SxqqQneHi+woAcGBSuBBAAKoUQDQgAEB7v/p7gvuV0aDx02EF6a+pr563p+FzRJXI+COWHdr+XRcjg6vEi4n3Jj7ksmEg4t1x6E1xFyTvF3eV/B/XVXbw=="
|
||||
let decodedSEC1 = Array(Data(base64Encoded: b64SEC1)!)
|
||||
|
||||
let parsed = try DER.parse(decodedSEC1)
|
||||
@@ -752,7 +777,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
try coder.serialize(RFC5480AlgorithmIdentifier.ecdsaP256)
|
||||
|
||||
var subCoder = DER.Serializer()
|
||||
try subCoder.serialize(SEC1PrivateKey(privateKey: [], algorithm: .ecdsaP384, publicKey: [])) // We won't notice these are empty either, but we will notice the algo mismatch.
|
||||
// We won't notice these are empty either, but we will notice the algo mismatch.
|
||||
try subCoder.serialize(SEC1PrivateKey(privateKey: [], algorithm: .ecdsaP384, publicKey: []))
|
||||
let serializedKey = ASN1OctetString(contentBytes: subCoder.serializedBytes[...])
|
||||
|
||||
try coder.serialize(serializedKey)
|
||||
@@ -766,7 +792,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
|
||||
func testNodeSlices() throws {
|
||||
// This is an SPKI object for RSA instead of EC. This is a 1024-bit RSA key, so hopefully no-one will think to use it.
|
||||
let rsaSPKI = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQEcP8qgwq5JhGgl1mKMeOWbb0WFKkJKj4Tvm4RFWGKDYg/p+Fm8vHwPSICqU9HJ+dHF2Ty0M6WVwVlf6RJdJGsrp1s9cbxfc/74PdQUssIhUjhlBO2RFlQECbgNpw5UleRB9FLnEDp33qMgdr7nwXiYCTjd04QSkdU3mXJYrFfwIDAQAB"
|
||||
let rsaSPKI =
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQEcP8qgwq5JhGgl1mKMeOWbb0WFKkJKj4Tvm4RFWGKDYg/p+Fm8vHwPSICqU9HJ+dHF2Ty0M6WVwVlf6RJdJGsrp1s9cbxfc/74PdQUssIhUjhlBO2RFlQECbgNpw5UleRB9FLnEDp33qMgdr7nwXiYCTjd04QSkdU3mXJYrFfwIDAQAB"
|
||||
let decodedSPKI = Array(Data(base64Encoded: rsaSPKI)!)
|
||||
|
||||
let parsed = try DER.parse(decodedSPKI)
|
||||
@@ -814,7 +841,10 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
func testOptionalImplicitlyTaggedWithCustomTag() throws {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.appendConstructedNode(identifier: .sequence) { serializer in
|
||||
try serializer.serializeOptionalImplicitlyTagged(1, withIdentifier: ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific))
|
||||
try serializer.serializeOptionalImplicitlyTagged(
|
||||
1,
|
||||
withIdentifier: ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific)
|
||||
)
|
||||
}
|
||||
let bytes = serializer.serializedBytes
|
||||
|
||||
@@ -826,11 +856,14 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
}
|
||||
XCTAssertEqual(int, 1)
|
||||
}
|
||||
|
||||
|
||||
func testOptionalImplicitlyTaggedWithBuilder() throws {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.appendConstructedNode(identifier: .sequence) { serializer in
|
||||
try serializer.serializeOptionalImplicitlyTagged(1, withIdentifier: ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific))
|
||||
try serializer.serializeOptionalImplicitlyTagged(
|
||||
1,
|
||||
withIdentifier: ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific)
|
||||
)
|
||||
}
|
||||
let bytes = serializer.serializedBytes
|
||||
|
||||
@@ -856,19 +889,26 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
let s = String(describing: any)
|
||||
XCTAssertEqual(s, "ASN1Any([5, 0])")
|
||||
}
|
||||
|
||||
|
||||
func testSetOfSingleElement() throws {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.serializeSetOf([
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [1])
|
||||
])
|
||||
XCTAssertEqual(serializer.serializedBytes, [49, 4, 3, 2, 0, 1])
|
||||
let bitStrings = try DER.set(of: ASN1BitString.self, identifier: .set, rootNode: try DER.parse(serializer.serializedBytes))
|
||||
XCTAssertEqual(bitStrings, [
|
||||
ASN1BitString(bytes: [1]),
|
||||
])
|
||||
let bitStrings = try DER.set(
|
||||
of: ASN1BitString.self,
|
||||
identifier: .set,
|
||||
rootNode: try DER.parse(serializer.serializedBytes)
|
||||
)
|
||||
XCTAssertEqual(
|
||||
bitStrings,
|
||||
[
|
||||
ASN1BitString(bytes: [1])
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
func testSetOfTwoElementsInOrder() throws {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.serializeSetOf([
|
||||
@@ -876,14 +916,21 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
ASN1BitString(bytes: [2]),
|
||||
])
|
||||
XCTAssertEqual(serializer.serializedBytes, [49, 8, 3, 2, 0, 1, 3, 2, 0, 2])
|
||||
|
||||
let bitStrings = try DER.set(of: ASN1BitString.self, identifier: .set, rootNode: try DER.parse(serializer.serializedBytes))
|
||||
XCTAssertEqual(bitStrings, [
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [2]),
|
||||
])
|
||||
|
||||
let bitStrings = try DER.set(
|
||||
of: ASN1BitString.self,
|
||||
identifier: .set,
|
||||
rootNode: try DER.parse(serializer.serializedBytes)
|
||||
)
|
||||
XCTAssertEqual(
|
||||
bitStrings,
|
||||
[
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [2]),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
func testSetOfTwoElementNotInOrder() throws {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.serializeSetOf([
|
||||
@@ -891,12 +938,19 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
ASN1BitString(bytes: [1]),
|
||||
])
|
||||
XCTAssertEqual(serializer.serializedBytes, [49, 8, 3, 2, 0, 1, 3, 2, 0, 2])
|
||||
|
||||
let bitStrings = try DER.set(of: ASN1BitString.self, identifier: .set, rootNode: try DER.parse(serializer.serializedBytes))
|
||||
XCTAssertEqual(bitStrings, [
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [2]),
|
||||
])
|
||||
|
||||
let bitStrings = try DER.set(
|
||||
of: ASN1BitString.self,
|
||||
identifier: .set,
|
||||
rootNode: try DER.parse(serializer.serializedBytes)
|
||||
)
|
||||
XCTAssertEqual(
|
||||
bitStrings,
|
||||
[
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [2]),
|
||||
]
|
||||
)
|
||||
}
|
||||
func testSetOfTwoEqualElements() throws {
|
||||
var serializer = DER.Serializer()
|
||||
@@ -905,12 +959,19 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
ASN1BitString(bytes: [1]),
|
||||
])
|
||||
XCTAssertEqual(serializer.serializedBytes, [49, 8, 3, 2, 0, 1, 3, 2, 0, 1])
|
||||
|
||||
let bitStrings = try DER.set(of: ASN1BitString.self, identifier: .set, rootNode: try DER.parse(serializer.serializedBytes))
|
||||
XCTAssertEqual(bitStrings, [
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [1]),
|
||||
])
|
||||
|
||||
let bitStrings = try DER.set(
|
||||
of: ASN1BitString.self,
|
||||
identifier: .set,
|
||||
rootNode: try DER.parse(serializer.serializedBytes)
|
||||
)
|
||||
XCTAssertEqual(
|
||||
bitStrings,
|
||||
[
|
||||
ASN1BitString(bytes: [1]),
|
||||
ASN1BitString(bytes: [1]),
|
||||
]
|
||||
)
|
||||
}
|
||||
func testSetOfTwoElementsOrderedIncorrectly() throws {
|
||||
let rootNode = try DER.parse([49, 8, 3, 2, 0, 2, 3, 2, 0, 1])
|
||||
@@ -918,7 +979,7 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testASN1SetOfOrder() {
|
||||
func assertSetOfLessThanOrEqual(
|
||||
_ lhs: ArraySlice<UInt8>,
|
||||
@@ -929,7 +990,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
|
||||
XCTAssert(
|
||||
asn1SetElementLessThanOrEqual(lhs, rhs),
|
||||
"\(lhs) is not less than or equal to \(rhs)",
|
||||
file: file, line: line
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
assertSetOfLessThanOrEqual([1], [1])
|
||||
|
||||
@@ -28,26 +28,86 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
// We store the byte payload here as a string.
|
||||
let vectors: [(String, GeneralizedTime?)] = [
|
||||
// Valid representations
|
||||
("19920521000000Z", try .init(year: 1992, month: 5, day: 21, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)),
|
||||
("19920622123421Z", try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0)),
|
||||
("19920722132100.3Z", try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3)),
|
||||
("19851106210627.3Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3)),
|
||||
("19851106210627.14159Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159)),
|
||||
("20210131000000Z", try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in January
|
||||
("20210228000000Z", try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2021
|
||||
("20200229000000Z", try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2020
|
||||
("21000228000000Z", try .init(year: 2100, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2100
|
||||
("20000229000000Z", try .init(year: 2000, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2000
|
||||
("20210331000000Z", try .init(year: 2021, month: 3, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in March
|
||||
("20210430000000Z", try .init(year: 2021, month: 4, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in April
|
||||
("20210531000000Z", try .init(year: 2021, month: 5, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in May
|
||||
("20210630000000Z", try .init(year: 2021, month: 6, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in June
|
||||
("20210731000000Z", try .init(year: 2021, month: 7, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in July
|
||||
("20210831000000Z", try .init(year: 2021, month: 8, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in August
|
||||
("20210930000000Z", try .init(year: 2021, month: 9, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in September
|
||||
("20211031000000Z", try .init(year: 2021, month: 10, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in October
|
||||
("20211130000000Z", try .init(year: 2021, month: 11, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in November
|
||||
("20211231000000Z", try .init(year: 2021, month: 12, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in December
|
||||
(
|
||||
"19920521000000Z",
|
||||
try .init(year: 1992, month: 5, day: 21, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
),
|
||||
(
|
||||
"19920622123421Z",
|
||||
try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0)
|
||||
),
|
||||
(
|
||||
"19920722132100.3Z",
|
||||
try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3)
|
||||
),
|
||||
(
|
||||
"19851106210627.3Z",
|
||||
try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3)
|
||||
),
|
||||
(
|
||||
"19851106210627.14159Z",
|
||||
try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159)
|
||||
),
|
||||
(
|
||||
"20210131000000Z",
|
||||
try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in January
|
||||
(
|
||||
"20210228000000Z",
|
||||
try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 28 days in February 2021
|
||||
(
|
||||
"20200229000000Z",
|
||||
try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 29 days in February 2020
|
||||
(
|
||||
"21000228000000Z",
|
||||
try .init(year: 2100, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 28 days in February 2100
|
||||
(
|
||||
"20000229000000Z",
|
||||
try .init(year: 2000, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 29 days in February 2000
|
||||
(
|
||||
"20210331000000Z",
|
||||
try .init(year: 2021, month: 3, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in March
|
||||
(
|
||||
"20210430000000Z",
|
||||
try .init(year: 2021, month: 4, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 30 days in April
|
||||
(
|
||||
"20210531000000Z",
|
||||
try .init(year: 2021, month: 5, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in May
|
||||
(
|
||||
"20210630000000Z",
|
||||
try .init(year: 2021, month: 6, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 30 days in June
|
||||
(
|
||||
"20210731000000Z",
|
||||
try .init(year: 2021, month: 7, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in July
|
||||
(
|
||||
"20210831000000Z",
|
||||
try .init(year: 2021, month: 8, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in August
|
||||
(
|
||||
"20210930000000Z",
|
||||
try .init(year: 2021, month: 9, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 30 days in September
|
||||
(
|
||||
"20211031000000Z",
|
||||
try .init(year: 2021, month: 10, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in October
|
||||
(
|
||||
"20211130000000Z",
|
||||
try .init(year: 2021, month: 11, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 30 days in November
|
||||
(
|
||||
"20211231000000Z",
|
||||
try .init(year: 2021, month: 12, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)
|
||||
), // only 31 days in December
|
||||
|
||||
// Invalid representations
|
||||
("19920520240000Z", nil), // midnight may not be 2400000
|
||||
@@ -79,11 +139,11 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
("20211131000000Z", nil), // only 30 days in November
|
||||
("20211232000000Z", nil), // only 31 days in December
|
||||
("20200101000000.9223372036854775808Z", nil), // Fractional part will overflow a 64-bit integer by adding
|
||||
("20200101000000.92233720368547758071Z", nil), // Fractional part will overflow a 64-bit integer by multiplication
|
||||
|
||||
]
|
||||
|
||||
for (stringRepresentation, expectedResult) in vectors {
|
||||
var serialized = Array<UInt8>()
|
||||
var serialized = [UInt8]()
|
||||
serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false)
|
||||
serialized.append(UInt8(stringRepresentation.utf8.count))
|
||||
serialized.append(contentsOf: stringRepresentation.utf8)
|
||||
@@ -102,40 +162,69 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
XCTAssertThrowsError(try code())
|
||||
}
|
||||
|
||||
mustFail(try .init(year: -1, month: 1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid year, negative
|
||||
mustFail(try .init(year: 2000, month: 0, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, zero.
|
||||
mustFail(try .init(year: 2000, month: -1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, negative.
|
||||
mustFail(try .init(year: 2000, month: 13, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, too large.
|
||||
mustFail(try .init(year: 2000, month: 1, day: 0, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, zero.
|
||||
mustFail(try .init(year: 2000, month: 1, day: -1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, negative.
|
||||
mustFail(try .init(year: 2000, month: 1, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in January
|
||||
mustFail(try .init(year: 2021, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2021
|
||||
mustFail(try .init(year: 2020, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2020
|
||||
mustFail(try .init(year: 2100, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2100
|
||||
mustFail(try .init(year: 2000, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2000
|
||||
mustFail(try .init(year: 2000, month: 3, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in March
|
||||
mustFail(try .init(year: 2000, month: 4, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in April
|
||||
mustFail(try .init(year: 2000, month: 5, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in May
|
||||
mustFail(try .init(year: 2000, month: 6, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in June
|
||||
mustFail(try .init(year: 2000, month: 7, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in July
|
||||
mustFail(try .init(year: 2000, month: 8, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in August
|
||||
mustFail(try .init(year: 2000, month: 9, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in September
|
||||
mustFail(try .init(year: 2000, month: 10, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in October
|
||||
mustFail(try .init(year: 2000, month: 11, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in November
|
||||
mustFail(try .init(year: 2000, month: 11, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in December
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: -1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid hour, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 24, minutes: 0, seconds: 0, fractionalSeconds: 0)) // Invalid hour, 24
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: -1, seconds: 1, fractionalSeconds: 0)) // Invalid minute, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 60, seconds: 0, fractionalSeconds: 0)) // Invalid minute, 60
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: -1, fractionalSeconds: 0)) // Invalid second, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 62, fractionalSeconds: 0)) // Invalid second, 62 (we allow some leap seconds)
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: -0.5)) // Invalid fractional seconds, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 1.1)) // Invalid fractional seconds, greater than one
|
||||
// Invalid year, negative
|
||||
mustFail(try .init(year: -1, month: 1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid month, zero.
|
||||
mustFail(try .init(year: 2000, month: 0, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid month, negative.
|
||||
mustFail(try .init(year: 2000, month: -1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid month, too large.
|
||||
mustFail(try .init(year: 2000, month: 13, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid day, zero.
|
||||
mustFail(try .init(year: 2000, month: 1, day: 0, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid day, negative.
|
||||
mustFail(try .init(year: 2000, month: 1, day: -1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in January
|
||||
mustFail(try .init(year: 2000, month: 1, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 28 days in February 2021
|
||||
mustFail(try .init(year: 2021, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 29 days in February 2020
|
||||
mustFail(try .init(year: 2020, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 28 days in February 2100
|
||||
mustFail(try .init(year: 2100, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 29 days in February 2000
|
||||
mustFail(try .init(year: 2000, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in March
|
||||
mustFail(try .init(year: 2000, month: 3, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 30 days in April
|
||||
mustFail(try .init(year: 2000, month: 4, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in May
|
||||
mustFail(try .init(year: 2000, month: 5, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 30 days in June
|
||||
mustFail(try .init(year: 2000, month: 6, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in July
|
||||
mustFail(try .init(year: 2000, month: 7, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in August
|
||||
mustFail(try .init(year: 2000, month: 8, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 30 days in September
|
||||
mustFail(try .init(year: 2000, month: 9, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in October
|
||||
mustFail(try .init(year: 2000, month: 10, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 30 days in November
|
||||
mustFail(try .init(year: 2000, month: 11, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// only 31 days in December
|
||||
mustFail(try .init(year: 2000, month: 11, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid hour, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: -1, minutes: 1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid hour, 24
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 24, minutes: 0, seconds: 0, fractionalSeconds: 0))
|
||||
// Invalid minute, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: -1, seconds: 1, fractionalSeconds: 0))
|
||||
// Invalid minute, 60
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 60, seconds: 0, fractionalSeconds: 0))
|
||||
// Invalid second, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: -1, fractionalSeconds: 0))
|
||||
// Invalid second, 62 (we allow some leap seconds)
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 62, fractionalSeconds: 0))
|
||||
// Invalid fractional seconds, negative
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: -0.5))
|
||||
// Invalid fractional seconds, greater than one
|
||||
mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 1.1))
|
||||
}
|
||||
|
||||
func testTruncatedRepresentationsRejected() throws {
|
||||
func mustNotDeserialize(_ stringRepresentation: Substring) {
|
||||
var serialized = Array<UInt8>()
|
||||
var serialized = [UInt8]()
|
||||
serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false)
|
||||
serialized.append(UInt8(stringRepresentation.utf8.count))
|
||||
serialized.append(contentsOf: stringRepresentation.utf8)
|
||||
@@ -144,7 +233,7 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
}
|
||||
|
||||
func deserializes(_ stringRepresentation: Substring) {
|
||||
var serialized = Array<UInt8>()
|
||||
var serialized = [UInt8]()
|
||||
serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false)
|
||||
serialized.append(UInt8(stringRepresentation.utf8.count))
|
||||
serialized.append(contentsOf: stringRepresentation.utf8)
|
||||
@@ -170,7 +259,7 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
|
||||
func testRequiresAppropriateTag() throws {
|
||||
let rawValue = "19920521000000Z".utf8
|
||||
var invalidBytes = Array<UInt8>()
|
||||
var invalidBytes = [UInt8]()
|
||||
invalidBytes.writeIdentifier(ASN1Identifier.integer, constructed: false) // generalizedTime isn't an integer
|
||||
invalidBytes.append(UInt8(rawValue.count))
|
||||
invalidBytes.append(contentsOf: rawValue)
|
||||
@@ -185,16 +274,28 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
case greaterThan
|
||||
}
|
||||
|
||||
let original = try GeneralizedTime(year: 2020, month: 03, day: 03, hours: 03, minutes: 03, seconds: 03, fractionalSeconds: 0.105)
|
||||
let original = try GeneralizedTime(
|
||||
year: 2020,
|
||||
month: 03,
|
||||
day: 03,
|
||||
hours: 03,
|
||||
minutes: 03,
|
||||
seconds: 03,
|
||||
fractionalSeconds: 0.105
|
||||
)
|
||||
|
||||
func modify<Modifiable: AdditiveArithmetic>(_ field: WritableKeyPath<GeneralizedTime, Modifiable>, of time: GeneralizedTime, by modifier: Modifiable) -> GeneralizedTime {
|
||||
func modify<Modifiable: AdditiveArithmetic>(
|
||||
_ field: WritableKeyPath<GeneralizedTime, Modifiable>,
|
||||
of time: GeneralizedTime,
|
||||
by modifier: Modifiable
|
||||
) -> GeneralizedTime {
|
||||
var copy = time
|
||||
copy[keyPath: field] += modifier
|
||||
return copy
|
||||
}
|
||||
|
||||
let integerTransformable: [WritableKeyPath<GeneralizedTime, Int>] = [
|
||||
\.year, \.month, \.day, \.hours, \.minutes, \.seconds
|
||||
\.year, \.month, \.day, \.hours, \.minutes, \.seconds,
|
||||
]
|
||||
|
||||
var transformationsAndResults: [(GeneralizedTime, ExpectedComparisonResult)] = []
|
||||
@@ -208,10 +309,20 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
transformationsAndResults.append((modify(\.fractionalSeconds, of: original, by: 0.1), .greaterThan))
|
||||
transformationsAndResults.append((modify(\.fractionalSeconds, of: original, by: -0.1), .lessThan))
|
||||
|
||||
transformationsAndResults.append((
|
||||
try GeneralizedTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08, fractionalSeconds: 0.205),
|
||||
.lessThan
|
||||
))
|
||||
transformationsAndResults.append(
|
||||
(
|
||||
try GeneralizedTime(
|
||||
year: 2019,
|
||||
month: 08,
|
||||
day: 08,
|
||||
hours: 08,
|
||||
minutes: 08,
|
||||
seconds: 08,
|
||||
fractionalSeconds: 0.205
|
||||
),
|
||||
.lessThan
|
||||
)
|
||||
)
|
||||
|
||||
for (newValue, expectedResult) in transformationsAndResults {
|
||||
switch expectedResult {
|
||||
|
||||
@@ -23,7 +23,7 @@ import SwiftASN1
|
||||
// }
|
||||
struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable {
|
||||
static let defaultPEMDiscriminator: String = "EC PRIVATE KEY"
|
||||
|
||||
|
||||
static var defaultIdentifier: ASN1Identifier {
|
||||
return .sequence
|
||||
}
|
||||
@@ -42,7 +42,8 @@ struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable {
|
||||
}
|
||||
|
||||
let privateKey = try ASN1OctetString(derEncoded: &nodes)
|
||||
let parameters = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
|
||||
let parameters = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
|
||||
node in
|
||||
return try ASN1ObjectIdentifier(derEncoded: node)
|
||||
}
|
||||
let publicKey = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
|
||||
|
||||
@@ -103,15 +103,20 @@ struct RFC5480AlgorithmIdentifier: DERImplicitlyTaggable, Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Algorithm Identifier Statics
|
||||
extension RFC5480AlgorithmIdentifier {
|
||||
static let ecdsaP256 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1))
|
||||
static let ecdsaP256 = RFC5480AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1)
|
||||
)
|
||||
|
||||
static let ecdsaP384 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1))
|
||||
static let ecdsaP384 = RFC5480AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1)
|
||||
)
|
||||
|
||||
static let ecdsaP521 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1))
|
||||
static let ecdsaP521 = RFC5480AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1)
|
||||
)
|
||||
}
|
||||
@@ -32,7 +32,7 @@ final class UTCTimeTests: XCTestCase {
|
||||
}
|
||||
|
||||
let integerTransformable: [WritableKeyPath<UTCTime, Int>] = [
|
||||
\.year, \.month, \.day, \.hours, \.minutes, \.seconds
|
||||
\.year, \.month, \.day, \.hours, \.minutes, \.seconds,
|
||||
]
|
||||
|
||||
var transformationsAndResults: [(UTCTime, ExpectedComparisonResult)] = []
|
||||
@@ -43,10 +43,12 @@ final class UTCTimeTests: XCTestCase {
|
||||
transformationsAndResults.append((modify(transform, of: original, by: -1), .lessThan))
|
||||
}
|
||||
|
||||
transformationsAndResults.append((
|
||||
try UTCTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08),
|
||||
.lessThan
|
||||
))
|
||||
transformationsAndResults.append(
|
||||
(
|
||||
try UTCTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08),
|
||||
.lessThan
|
||||
)
|
||||
)
|
||||
|
||||
for (newValue, expectedResult) in transformationsAndResults {
|
||||
switch expectedResult {
|
||||
|
||||
@@ -15,3 +15,9 @@ ENV LANGUAGE en_US.UTF-8
|
||||
# tools
|
||||
RUN mkdir -p $HOME/.tools
|
||||
RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile
|
||||
|
||||
# swift-format
|
||||
ARG swiftformat_version=508.0.1
|
||||
RUN git clone --branch $swiftformat_version --depth 1 https://github.com/apple/swift-format $HOME/.tools/swift-format-source
|
||||
RUN cd $HOME/.tools/swift-format-source && swift build -c release
|
||||
RUN ln -s $HOME/.tools/swift-format-source/.build/release/swift-format $HOME/.tools/swift-format
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/bin/bash
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftASN1 open source project
|
||||
##
|
||||
## Copyright (c) 2022-2023 Apple Inc. and the SwiftASN1 project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftASN1 project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftOpenAPIGenerator open source project
|
||||
##
|
||||
## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
set -euo pipefail
|
||||
|
||||
function log() { printf -- "** %s\n" "$*" >&2; }
|
||||
function error() { printf -- "** ERROR: %s\n" "$*" >&2; }
|
||||
function fatal() { error "$*"; exit 1; }
|
||||
|
||||
current_script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
repo_root="$(git -C "${current_script_dir}" rev-parse --show-toplevel)"
|
||||
|
||||
swiftformat_bin=${swiftformat_bin:-$(command -v swift-format)} || fatal "❌ swiftformat_bin unset and no swift-format on PATH"
|
||||
|
||||
"${swiftformat_bin}" lint \
|
||||
--parallel --recursive --strict \
|
||||
"${repo_root}/Sources" "${repo_root}/Tests" \
|
||||
&& swift_format_rc=$? || swift_format_rc=$?
|
||||
|
||||
if [[ "${swift_format_rc}" -ne 0 ]]; then
|
||||
fatal "❌ Running swift-format produced errors.
|
||||
|
||||
To fix, run the following command:
|
||||
|
||||
% swift-format format --parallel --recursive --in-place Sources Tests
|
||||
"
|
||||
exit "${swift_format_rc}"
|
||||
fi
|
||||
|
||||
log "✅ Ran swift-format with no errors."
|
||||
@@ -53,6 +53,12 @@ if git grep --color=never -i "${unacceptable_terms[@]}" -- . ":(exclude)CODE_OF_
|
||||
fi
|
||||
printf "\033[0;32mokay.\033[0m\n"
|
||||
|
||||
# swift-format
|
||||
swift_format_script="${here}/run-swift-format.sh"
|
||||
if ! bash "${swift_format_script}"; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf "=> Detecting changes in source files for CMake build\n"
|
||||
FIRST_OUT="$(git status --porcelain)"
|
||||
out=$($here/update_cmakelists.sh 2>&1)
|
||||
|
||||
Reference in new issue
Block a user