Initial commit

This commit is contained in:
Cory Benfield authored and David Nadoba committed 2022-11-15 10:31:11 +01:00
commit 81b7d4dc72
29 files changed
+5836

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
Package.pins
*.pem
/docs/1.*
/docs/2.*
Package.resolved
.podspecs
DerivedData
.swiftpm
**/gyb.pyc
.*.sw[nop]
+203
View File
@@ -0,0 +1,203 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+30
View File
@@ -0,0 +1,30 @@
// swift-tools-version:5.6
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2022 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-asn1",
products: [
.library(name: "SwiftASN1", targets: ["SwiftASN1"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
],
targets: [
.target(name: "SwiftASN1"),
.testTarget(name: "SwiftASN1Tests", dependencies: ["SwiftASN1"]),
]
)
+32
View File
@@ -0,0 +1,32 @@
# SwiftASN1
An implementation of ASN.1 types and DER serialization.
## Overview
ASN.1, and the DER encoding scheme, is a commonly used object serialization format. The most common use-cases for ASN.1 in
general computing are in the cryptographic space, but there are a number of use-cases in a wide range of fields. This module
provides an implementation of a number of ASN.1 types, as well as the DER serialization format for ASN.1.
ASN.1 can be used abstractly to describe essentially any kind of object. ASN.1 objects are made up of either primitive or
composite (called "constructed") types. Individual scalar objects can be combined into aggregate types, and composed essentially
arbitrarily to form abstract object formats.
Importantly, the ASN.1 object description does not define a specific encoding for these objects. Instead there are a wide range
of possible ways to serialize or deserialize an ASN.1 object. Some of the most prominent are BER (the Basic Encoding Rules),
CER (the Canonical Encoding Rules), DER (the Distinguished Encoding Rules), and XER (the XML Encoding Rules). For the cryptographic
use-case DER is the standard choice, as a given ASN.1 object can be encoded in only one way under DER. This makes signing and verifying
vastly easier, as it is at least in principle possible to perfectly reconstruct the serialization of a parsed object.
This module provides several moving pieces:
1. A high-level representation of an ASN.1 object, in the form of a tree of object nodes (`ASN1Node`).
2. A DER parser that can construct the ASN.1 tree from serialized bytes (`ASN1.parse(_:)`).
3. A DER serializer that can construct serialized bytes from the ASN.1 tree (`ASN1.Serializer`).
4. A number of built-in ASN.1 types, representing common constructs.
These moving pieces combine to provide support for the DER representation of ASN.1 suitable for a wide range of cryptographic uses.
## Getting Started
Consult the documentation for examples of how to use the code. A number of examples are also present in the repository itself.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,95 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An ASN1 ANY represents...well, anything.
///
/// In this case we store the ASN.1 ANY as a serialized representation. This is a bit limiting,
/// but it's the only safe way to manage this data, as we cannot arbitrarily parse it.
///
/// The only things users can do with ASN.1 ANYs is to try to decode them as something else,
/// to create them from something else, or to serialize them.
public struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable, Sendable {
@usableFromInline
var _serializedBytes: ArraySlice<UInt8>
/// Create an ``ASN1/ASN1Any`` from a serializable ASN1 type.
///
/// - parameters:
/// erasing: The type to be represented as an ASN1 ANY.
@inlinable
public init<ASN1Type: ASN1Serializable>(erasing: ASN1Type) throws {
var serializer = ASN1.Serializer()
try erasing.serialize(into: &serializer)
self._serializedBytes = ArraySlice(serializer._serializedBytes)
}
/// Create an ``ASN1/ASN1Any`` from a serializable implicitly taggable ASN1 type.
///
/// - parameters:
/// erasing: The type to be represented as an ASN1 ANY.
/// identifier: The tag to use with this node.
@inlinable
public init<ASN1Type: ASN1ImplicitlyTaggable>(erasing: ASN1Type, withIdentifier identifier: ASN1.ASN1Identifier) throws {
var serializer = ASN1.Serializer()
try erasing.serialize(into: &serializer, withIdentifier: identifier)
self._serializedBytes = ArraySlice(serializer._serializedBytes)
}
@inlinable
public init(asn1Encoded rootNode: ASN1.ASN1Node) {
// This is a bit sad: we just re-serialize this data. In an ideal world
// we'd update the parse representation so that all nodes can point at their
// complete backing storage, but for now this is better.
var serializer = ASN1.Serializer()
serializer.serialize(rootNode)
self._serializedBytes = ArraySlice(serializer._serializedBytes)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer) throws {
// Dangerous to just reach in there like this, but it's the right way to serialize this.
coder._serializedBytes.append(contentsOf: self._serializedBytes)
}
}
}
extension ASN1Parseable {
/// Construct this node from an ASN.1 ANY object.
///
/// This operation works by asking the type to decode itself from the serialized representation
/// of this ASN.1 ANY node.
///
/// - parameters:
/// asn1Any: The ASN.1 ANY object to reinterpret.
@inlinable
public init(asn1Any: ASN1.ASN1Any) throws {
try self.init(asn1Encoded: asn1Any._serializedBytes)
}
}
extension ASN1ImplicitlyTaggable {
/// Construct this node from an ASN.1 ANY object.
///
/// This operation works by asking the type to decode itself from the serialized representation
/// of this ASN.1 ANY node.
///
/// - parameters:
/// asn1Any: The ASN.1 ANY object to reinterpret.
/// identifier: The tag to use with this node.
@inlinable
public init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try self.init(asn1Encoded: asn1Any._serializedBytes, withIdentifier: identifier)
}
}
@@ -0,0 +1,125 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// A bitstring is a representation of a sequence of bits.
///
/// In ASN.1, bitstrings serve two different use-cases. The first is as arbitrary-length sequences of bits.
/// These are typically used to encode cryptographic keys, such as RSA keys. The second is as a form of bitset.
///
/// In the case of a bitset, DER has additonal requirements as to how to represent the object. This type does not
/// enforce those additional rules: users are expected to implement that validation themselves.
public struct ASN1BitString: ASN1ImplicitlyTaggable {
/// The default identifier for this type.
///
/// Evaluates to ``ASN1/ASN1Identifier/primitiveBitString``.
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveBitString
}
/// The raw bytes that make up this bitstring.
///
/// The last ``paddingBits`` number of bits in the final octet of this byte sequence must be zero.
public var bytes: ArraySlice<UInt8> {
didSet {
try! self._validate()
}
}
/// The number of bits in the last octet of ``bytes`` that are not part of this bitstring.
///
/// The excluded bits are the least significant bits.
///
/// If ``bytes`` is empty then this value must be 0.
public var paddingBits: Int {
didSet {
precondition((0..<8).contains(self.paddingBits))
try! self._validate()
}
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// 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
}
self.paddingBits = Int(paddingBits)
self.bytes = content.dropFirst()
try self._validate()
}
/// Construct an ``ASN1/ASN1BitString`` from raw components.
///
/// - parameters:
/// - bytes: The bytes to represent this bitstring
/// - paddingBits: The number of bits in the trailing byte that are not actually part of this bitstring.
@inlinable
public init(bytes: ArraySlice<UInt8>, paddingBits: Int = 0) {
self.bytes = bytes
self.paddingBits = paddingBits
try! self._validate()
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
bytes.append(UInt8(truncatingIfNeeded: self.paddingBits))
bytes.append(contentsOf: self.bytes)
}
}
@inlinable
internal func _validate() throws {
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
}
return
}
// Oooh, bit twiddling.
//
// All joking aside, this sets the bottom `self.paddingBits` to 1.
let mask = ~(UInt8.max << self.paddingBits)
if (finalByte & mask) != 0 {
throw ASN1Error.invalidASN1Object
}
}
}
}
extension ASN1.ASN1BitString: Hashable { }
extension ASN1.ASN1BitString: Sendable { }
extension ASN1.ASN1BitString {
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension Bool: ASN1ImplicitlyTaggable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.boolean
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.invalidASN1Object
}
guard case .primitive(let bytes) = node.content, bytes.count == 1 else {
throw ASN1Error.invalidASN1Object
}
switch bytes[bytes.startIndex] {
case 0:
// Boolean false
self = false
case 0xff:
// Boolean true in DER
self = true
default:
// If we come to support BER then these values are all "true" as well.
throw ASN1Error.invalidASN1Object
}
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
if self {
bytes.append(0xff)
} else {
bytes.append(0)
}
}
}
}
@@ -0,0 +1,231 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An ``ASN1/ASN1Identifier`` is a representation of the abstract notion of an ASN.1 identifier.
public struct ASN1Identifier {
/// The base tag.
public var tagNumber: UInt
/// The class of the tag.
public var tagClass: TagClass
/// Whether this tag represents a primitive object.
public var primitive: Bool
/// Whether this tag represents a constructed object.
@inlinable
public var constructed: Bool {
get {
return !self.primitive
}
set {
self.primitive = !newValue
}
}
@inlinable
var _shortForm: UInt8? {
// An ASN.1 identifier can be encoded in short form iff the tag number is strictly
// less than 0x1f.
guard self.tagNumber < 0x1f else { return nil }
var baseNumber = UInt8(truncatingIfNeeded: self.tagNumber)
if self.constructed {
baseNumber |= 0x20
}
baseNumber |= self.tagClass._topByteFlags
return baseNumber
}
/// The class of an ASN.1 tag.
public enum TagClass: Hashable, Sendable {
case universal
case application
case contextSpecific
case `private`
@inlinable
init(topByteInWireFormat topByte: UInt8) {
switch topByte >> 6 {
case 0x00:
self = .universal
case 0x01:
self = .application
case 0x02:
self = .contextSpecific
case 0x03:
self = .private
default:
fatalError("Unreachable")
}
}
@inlinable
var _topByteFlags: UInt8 {
switch self {
case .universal:
return 0x00
case .application:
return 0x01 << 6
case .contextSpecific:
return 0x02 << 6
case .private:
return 0x03 << 6
}
}
}
@inlinable
init(shortIdentifier: UInt8) {
precondition(shortIdentifier & 0x1F != 0x1F)
self.tagClass = TagClass(topByteInWireFormat: shortIdentifier)
self.primitive = (shortIdentifier & 0x20 == 0)
self.tagNumber = UInt(shortIdentifier & 0x1f)
}
/// Produces a tag suitable for use as an explicit tag from components.
///
/// This is equivalent to ``init(tagWithNumber:tagClass:constructed:)``, but sets
/// `constructed` to `true` in all cases.
///
/// - parameters:
/// - number: The tag number.
/// - tagClass: The class of the ASN.1 tag.
@inlinable
public init(explicitTagWithNumber number: UInt, tagClass: TagClass) {
self.tagClass = tagClass
self.tagNumber = number
// Explicit tags are always constructed
self.primitive = false
}
/// Produces a tag from components.
///
/// This is equivalent to ``init(tagWithNumber:tagClass:constructed:)``, but sets
/// `constructed` to `true` in all cases.
///
/// - parameters:
/// - number: The tag number.
/// - tagClass: The class of the ASN.1 tag.
/// - constructed: Whether this is a constructed tag.
@inlinable
public init(tagWithNumber number: UInt, tagClass: TagClass, constructed: Bool) {
self.tagNumber = number
self.tagClass = tagClass
self.primitive = !constructed
}
}
}
extension ASN1.ASN1Identifier {
/// This tag represents an OBJECT IDENTIFIER.
public static let objectIdentifier = ASN1.ASN1Identifier(shortIdentifier: 0x06)
/// This tag represents a BITSTRING.
public static let primitiveBitString = ASN1.ASN1Identifier(shortIdentifier: 0x03)
/// This tag represents an OCTET STRING.
public static let primitiveOctetString = ASN1.ASN1Identifier(shortIdentifier: 0x04)
/// This tag represents an INTEGER.
public static let integer = ASN1.ASN1Identifier(shortIdentifier: 0x02)
/// This tag represents a SEQUENCE or SEQUENCE OF.
public static let sequence = ASN1.ASN1Identifier(shortIdentifier: 0x30)
/// This tag represents a SET or SET OF.
public static let set = ASN1.ASN1Identifier(shortIdentifier: 0x31)
/// This tag represents an ASN.1 NULL.
public static let null = ASN1.ASN1Identifier(shortIdentifier: 0x05)
/// This tag represents a BOOLEAN.
public static let boolean = ASN1.ASN1Identifier(shortIdentifier: 0x01)
/// This tag represents an ENUMERATED.
public static let enumerated = ASN1.ASN1Identifier(shortIdentifier: 0x0a)
/// This tag represents a UTF8STRING.
public static let primitiveUTF8String = ASN1.ASN1Identifier(shortIdentifier: 0x0c)
/// This tag represents a NUMERICSTRING.
public static let primitiveNumericString = ASN1.ASN1Identifier(shortIdentifier: 0x12)
/// This tag represents a PRINTABLESTRING.
public static let primitivePrintableString = ASN1.ASN1Identifier(shortIdentifier: 0x13)
/// This tag represents a TELETEXSTRING.
public static let primitiveTeletexString = ASN1.ASN1Identifier(shortIdentifier: 0x14)
/// This tag represents a VIDEOTEXSTRING.
public static let primitiveVideotexString = ASN1.ASN1Identifier(shortIdentifier: 0x15)
/// This tag represents an IA5STRING.
public static let primitiveIA5String = ASN1.ASN1Identifier(shortIdentifier: 0x16)
/// This tag represents a GRAPHICSTRING.
public static let primitiveGraphicString = ASN1.ASN1Identifier(shortIdentifier: 0x19)
/// This tag represents a VISIBLESTRING.
public static let primitiveVisibleString = ASN1.ASN1Identifier(shortIdentifier: 0x1a)
/// This tag represents a GENERALSTRING.
public static let primitiveGeneralString = ASN1.ASN1Identifier(shortIdentifier: 0x1b)
/// This tag represents a UNIVERSALSTRING.
public static let primitiveUniversalString = ASN1.ASN1Identifier(shortIdentifier: 0x1c)
/// This tag represents a BMPSTRING.
public static let primitiveBMPString = ASN1.ASN1Identifier(shortIdentifier: 0x1e)
/// This tag represents a GENERALIZEDTIME.
public static let generalizedTime = ASN1.ASN1Identifier(shortIdentifier: 0x18)
/// This tag represents a UTCTIME.
public static let utcTime = ASN1.ASN1Identifier(shortIdentifier: 0x17)
}
extension ASN1.ASN1Identifier: Hashable { }
extension ASN1.ASN1Identifier: Sendable { }
extension ASN1.ASN1Identifier: CustomStringConvertible {
@inlinable
public var description: String {
return "ASN1Identifier(tagNumber: \(self.tagNumber), tagClass: \(self.tagClass), primitive: \(self.primitive))"
}
}
extension Array where Element == UInt8 {
@inlinable
mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
if let shortForm = identifier._shortForm {
self.append(shortForm)
} else {
// Long-form encoded. The top byte is 0x1f plus the various flags.
var topByte = UInt8(0x1f)
if identifier.constructed {
topByte |= 0x20
}
topByte |= identifier.tagClass._topByteFlags
self.append(topByte)
// Then we encode this in base128, just like an OID subidentifier.
// TODO: Adjust the ASN1Identifier to use UInt for its storage.
self.writeUsing7BitBytesASN1Discipline(unsignedInteger: UInt(identifier.tagNumber))
}
}
}
@@ -0,0 +1,301 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
/// a INTEGER.
///
/// This protocol exists to allow users to handle the possibility of decoding integers that cannot fit into
/// UInt64 or Int64. While both of those types conform by default, users can conform their preferred
/// arbitrary-width integer type as well, or use `ArraySlice<UInt8>` to store the raw bytes of the
/// integer directly.
public protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable {
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
/// Whether this type can represent signed integers.
///
/// If this is set to false, the serializer and parser will automatically handle padding
/// with leading zero bytes as needed.
static var isSigned: Bool { get }
/// Construct the integer value from the integer bytes. These will be big-endian, and encoded
/// according to DER requirements.
init(asn1IntegerBytes: ArraySlice<UInt8>) throws
/// Provide the big-endian bytes corresponding to this integer.
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws -> ReturnType) rethrows -> ReturnType
}
extension ASN1IntegerRepresentable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.integer
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(var dataBytes) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// Zero bytes of integer is not an acceptable encoding.
guard dataBytes.count > 0 else {
throw ASN1Error.invalidASN1IntegerEncoding
}
// 8.3.2 If the contents octets of an integer value encoding consist of more than one octet, then the bits of the first octet and bit 8 of the second octet:
//
// a) shall not all be ones; and
// b) shall not all be zero.
//
// 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 {
throw ASN1Error.invalidASN1IntegerEncoding
}
}
// If the type we're trying to decode is unsigned, and the top byte is zero, we should strip it.
// If the top bit is set, however, this is an invalid conversion: the number needs to be positive!
if !Self.isSigned, let first = dataBytes.first {
if first == 0x00 {
dataBytes = dataBytes.dropFirst()
} else if first & 0x80 == 0x80 {
throw ASN1Error.invalidASN1IntegerEncoding
}
}
self = try Self(asn1IntegerBytes: dataBytes)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
self.withBigEndianIntegerBytes { integerBytes in
// If the number of bytes is 0, we're encoding a zero. That actually _does_ require one byte.
if integerBytes.count == 0 {
bytes.append(0)
return
}
// If self is unsigned and the first byte has the top bit set, we need to prepend a 0 byte.
if !Self.isSigned, let topByte = integerBytes.first, topByte._topBitSet {
bytes.append(0)
bytes.append(contentsOf: integerBytes)
} else {
// Either self is signed, or the top bit isn't set. Either way, trim to make sure the representation is minimal.
bytes.append(contentsOf: integerBytes._trimLeadingExcessBytes())
}
}
}
}
}
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
@inlinable
public init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws {
// Defer to the FixedWidthInteger constructor.
// There's a wrinkle here: if this is a signed integer, and the top bit of the data bytes was set,
// then we need to 1-extend the bytes. This is because ASN.1 tries to delete redundant bytes that
// are all 1.
self = try Self(bigEndianBytes: bytes)
if Self.isSigned, let first = bytes.first, first._topBitSet {
for shift in stride(from: self.bitWidth - self.leadingZeroBitCount, to: self.bitWidth, by: 8) {
self |= 0xFF << shift
}
}
}
@inlinable
public func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytesCollection<Self>) throws -> ReturnType) rethrows -> ReturnType {
return try body(IntegerBytesCollection(self))
}
}
/// A big-endian `Collection` of bytes representing a fixed width integer.
public struct IntegerBytesCollection<Integer: FixedWidthInteger & Sendable> {
@usableFromInline var integer: Integer
/// Construct an ``IntegerBytesCollection`` representing the bytes of this integer.
@inlinable
public init(_ integer: Integer) {
self.integer = integer
}
}
extension IntegerBytesCollection: Hashable { }
extension IntegerBytesCollection: Sendable { }
extension IntegerBytesCollection: RandomAccessCollection {
public struct Index {
@usableFromInline
var _byteNumber: Int
@inlinable
init(byteNumber: Int) {
self._byteNumber = byteNumber
}
@inlinable
var _shift: Integer {
// As byte number 0 is the end index, the byte number is one byte too large for the shift.
return Integer((self._byteNumber - 1) * 8)
}
}
@inlinable
public var startIndex: Index {
return Index(byteNumber: Int(self.integer.neededBytes))
}
@inlinable
public var endIndex: Index {
return Index(byteNumber: 0)
}
@inlinable
public var count: Int {
return Int(self.integer.neededBytes)
}
@inlinable
public subscript(index: Index) -> UInt8 {
// We perform the bitwise operations in magnitude space.
let shifted = Integer.Magnitude(truncatingIfNeeded: self.integer) >> index._shift
let masked = shifted & 0xFF
return UInt8(masked)
}
}
extension IntegerBytesCollection.Index: Hashable { }
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 {
return lhs._byteNumber > rhs._byteNumber
}
@inlinable
public static func >(lhs: Self, rhs: Self) -> Bool {
return lhs._byteNumber < rhs._byteNumber
}
@inlinable
public static func <=(lhs: Self, rhs: Self) -> Bool {
return lhs._byteNumber >= rhs._byteNumber
}
@inlinable
public static func >=(lhs: Self, rhs: Self) -> Bool {
return lhs._byteNumber <= rhs._byteNumber
}
}
extension IntegerBytesCollection.Index: Strideable {
@inlinable
public func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
return IntegerBytesCollection.Index(byteNumber: self._byteNumber - n)
}
@inlinable
public func distance(to other: IntegerBytesCollection<Integer>.Index) -> Int {
// Remember that early indices have high byte numbers and later indices have low ones.
return self._byteNumber - other._byteNumber
}
}
extension Int8: ASN1IntegerRepresentable { }
extension UInt8: ASN1IntegerRepresentable { }
extension Int16: ASN1IntegerRepresentable { }
extension UInt16: ASN1IntegerRepresentable { }
extension Int32: ASN1IntegerRepresentable { }
extension UInt32: ASN1IntegerRepresentable { }
extension Int64: ASN1IntegerRepresentable { }
extension UInt64: ASN1IntegerRepresentable { }
extension Int: ASN1IntegerRepresentable { }
extension UInt: ASN1IntegerRepresentable { }
extension RandomAccessCollection where Element == UInt8 {
@inlinable
func _trimLeadingExcessBytes() -> SubSequence {
var slice = self[...]
guard let first = slice.first else {
// Easy case, empty.
return slice
}
let wholeByte: UInt8
switch first {
case 0:
wholeByte = 0
case 0xFF:
wholeByte = 0xFF
default:
// We're already fine, this is maximally compact. We need the whole thing.
return slice
}
// We never trim this to less than one byte, as that's always the smallest representation.
while slice.count > 1 {
// If the first byte is equal to our original first byte, and the top bit
// of the next byte is also equal to that, then we need to drop the byte and
// go again.
if slice.first != wholeByte {
break
}
guard let second = slice.dropFirst().first else {
preconditionFailure("Loop condition violated: must be at least two bytes left")
}
if second & 0x80 != wholeByte & 0x80 {
// Different top bit, we need the leading byte.
break
}
// Both the first byte and the top bit of the next are all zero or all 1, drop the leading
// byte.
slice = slice.dropFirst()
}
return slice
}
}
extension UInt8 {
@inlinable
var _topBitSet: Bool {
return (self & 0x80) != 0
}
}
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An ASN1 NULL represents nothing.
public struct ASN1Null: ASN1ImplicitlyTaggable, Hashable, Sendable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.null
}
/// Construct a new ASN.1 null.
@inlinable
public init() { }
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier, case .primitive(let content) = node.content else {
throw ASN1Error.unexpectedFieldType
}
guard content.count == 0 else {
throw ASN1Error.invalidASN1Object
}
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) {
coder.appendPrimitiveNode(identifier: identifier, { _ in })
}
}
}
@@ -0,0 +1,66 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An OCTET STRING is a representation of a string of octets.
public struct ASN1OctetString: ASN1ImplicitlyTaggable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveOctetString
}
/// The octets that make up this OCTET STRING.
public var bytes: ArraySlice<UInt8>
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
self.bytes = content
}
/// Construct an OCTET STRING from a sequence of bytes.
///
/// - parameters:
/// - contentBytes: The bytes that make up this OCTET STRING.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
bytes.append(contentsOf: self.bytes)
}
}
}
}
extension ASN1.ASN1OctetString: Hashable { }
extension ASN1.ASN1OctetString: Sendable { }
extension ASN1.ASN1OctetString {
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
@@ -0,0 +1,351 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// A UTF8String represents a string made up of UTF-8 bytes.
public struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveUTF8String
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8>
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
}
/// Construct a UTF8STRING from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
}
/// Construct a UTF8STRING from a String.
@inlinable
public init(_ string: String) {
self.bytes = ArraySlice(string.utf8)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
/// TeletexString is an uncommon ASN.1 string type.
///
/// This module represents a TeletexString as an opaque sequence of bytes.
public struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveTeletexString
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8>
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
}
/// Construct a TeletexString from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
/// PrintableString represents a String made up of bytes that can reliably be printed in a terminal.
///
/// This string will be validated when it is constructed, and will reject characters outside of this
/// space.
///
/// PrintableString is deprecated for most use-cases and generally ``ASN1/ASN1UTF8String`` should be
/// preferred.
public struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitivePrintableString
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8> {
didSet {
precondition(Self._isValid(self.bytes))
}
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
/// Construct a PrintableString from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) throws {
self.bytes = contentBytes
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
precondition(Self._isValid(self.bytes))
}
/// Construct a PrintableString from a String.
@inlinable
public init(_ string: String) throws {
self.bytes = ArraySlice(string.utf8)
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
@inlinable
static func _isValid(_ bytes: ArraySlice<UInt8>) -> Bool {
bytes.allSatisfy {
switch $0 {
case UInt8(ascii: "a")...UInt8(ascii: "z"),
UInt8(ascii: "A")...UInt8(ascii: "Z"),
UInt8(ascii: "0")...UInt8(ascii: "9"),
UInt8(ascii: "'"), UInt8(ascii: "("),
UInt8(ascii: ")"), UInt8(ascii: "+"),
UInt8(ascii: "-"), UInt8(ascii: "?"),
UInt8(ascii: ":"), UInt8(ascii: "/"),
UInt8(ascii: "="), UInt8(ascii: " "),
UInt8(ascii: ","), UInt8(ascii: "."):
return true
default:
return false
}
}
}
}
/// UniversalString is an uncommon ASN.1 string type.
///
/// This module represents a UniversalString as an opaque sequence of bytes.
public struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveUniversalString
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8>
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
}
/// Construct a UniversalString from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
/// BMPString is an uncommon ASN.1 string type.
///
/// This module represents a BMPString as an opaque sequence of bytes.
public struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveBMPString
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8>
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
}
/// Construct a BMPString from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
/// IA5String represents a String made up of ASCII characters.
///
/// This string will be validated when it is constructed, and will reject characters outside of this
/// space.
///
/// IA5String is deprecated for most use-cases and generally ``ASN1/ASN1UTF8String`` should be
/// preferred.
public struct ASN1IA5String: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.primitiveIA5String
}
/// The raw bytes that make up this string.
public var bytes: ArraySlice<UInt8> {
didSet {
precondition(Self._isValid(self.bytes))
}
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
/// Construct an IA5String from raw bytes.
@inlinable
public init(contentBytes: ArraySlice<UInt8>) throws {
self.bytes = contentBytes
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
precondition(Self._isValid(self.bytes))
}
/// Construct an IA5String from a String.
@inlinable
public init(_ string: String) throws {
self.bytes = ArraySlice(string.utf8)
guard Self._isValid(self.bytes) else {
throw ASN1Error.invalidStringRepresentation
}
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
let octet = ASN1OctetString(contentBytes: self.bytes)
try octet.serialize(into: &coder, withIdentifier: identifier)
}
@inlinable
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
@inlinable
static func _isValid(_ bytes: ArraySlice<UInt8>) -> Bool {
// Valid IA5Strings are ASCII characters.
bytes.allSatisfy { $0 < 128 }
}
}
}
extension String {
/// Construct a `String` from an ``ASN1/ASN1UTF8String``.
public init(_ utf8String: ASN1.ASN1UTF8String) {
self = String(decoding: utf8String.bytes, as: UTF8.self)
}
/// Construct a `String` from an ``ASN1/ASN1PrintableString``.
public init(_ printableString: ASN1.ASN1PrintableString) {
self = String(decoding: printableString.bytes, as: UTF8.self)
}
/// Construct a `String` from an ``ASN1/ASN1IA5String``.
public init(_ ia5String: ASN1.ASN1IA5String) {
self = String(decoding: ia5String.bytes, as: UTF8.self)
}
}
@@ -0,0 +1,38 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
extension ArraySlice: ASN1Parseable where Element == UInt8 { }
extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { }
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
// We only use unsigned "bigint"s
@inlinable
public static var isSigned: Bool {
return false
}
@inlinable
public init(asn1IntegerBytes: ArraySlice<UInt8>) throws {
self = asn1IntegerBytes
}
@inlinable
public func withBigEndianIntegerBytes<ReturnType>(_ body: (ArraySlice<UInt8>) throws -> ReturnType) rethrows -> ReturnType {
return try body(self)
}
}
@@ -0,0 +1,200 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// GeneralizedTime represents a date and time.
///
/// In DER format, this is always in the form of `YYYYMMDDHHMMSSZ`. The type in
/// general is capable of expressing fractional seconds. The time is always in the
/// UTC time zone.
public struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable, Sendable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.generalizedTime
}
/// The numerical year.
@inlinable
public var year: Int {
get {
return self._year
}
set {
self._year = newValue
try! self._validate()
}
}
/// The numerical month.
@inlinable
public var month: Int {
get {
return self._month
}
set {
self._month = newValue
try! self._validate()
}
}
/// The numerical day.
@inlinable
public var day: Int {
get {
return self._day
}
set {
self._day = newValue
try! self._validate()
}
}
/// The numerical hours.
@inlinable
public var hours: Int {
get {
return self._hours
}
set {
self._hours = newValue
try! self._validate()
}
}
/// The numerical minutes.
@inlinable
public var minutes: Int {
get {
return self._minutes
}
set {
self._minutes = newValue
try! self._validate()
}
}
/// The numerical seconds.
@inlinable
public var seconds: Int {
get {
return self._seconds
}
set {
self._seconds = newValue
try! self._validate()
}
}
/// The fractional seconds.
@inlinable
public var fractionalSeconds: Double {
get {
return self._fractionalSeconds
}
set {
self._fractionalSeconds = newValue
try! self._validate()
}
}
@usableFromInline var _year: Int
@usableFromInline var _month: Int
@usableFromInline var _day: Int
@usableFromInline var _hours: Int
@usableFromInline var _minutes: Int
@usableFromInline var _seconds: Int
@usableFromInline var _fractionalSeconds: Double
/// Construct a new ``ASN1/GeneralizedTime`` from individual components.
///
/// - parameters:
/// - year: The numerical year
/// - month: The numerical month
/// - day: The numerical day
/// - hours: The numerical hours
/// - minutes: The numerical minutes
/// - 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 {
self._year = year
self._month = month
self._day = day
self._hours = hours
self._minutes = minutes
self._seconds = seconds
self._fractionalSeconds = fractionalSeconds
try self._validate()
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
self = try TimeUtilities.generalizedTimeFromBytes(content)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
bytes.append(self)
}
}
@inlinable
func _validate() throws {
// Validate that the structure is well-formed.
guard self._year >= 0 && self._year <= 9999 else {
throw ASN1Error.invalidASN1Object
}
// This also validates the month.
guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else {
throw ASN1Error.invalidASN1Object
}
guard self._day >= 1 && self._day <= daysInMonth else {
throw ASN1Error.invalidASN1Object
}
guard self._hours >= 0 && self._hours < 24 else {
throw ASN1Error.invalidASN1Object
}
guard self._minutes >= 0 && self._minutes < 60 else {
throw ASN1Error.invalidASN1Object
}
// We allow leap seconds here, but don't validate it.
// This exposes us to potential confusion if we naively implement
// comparison here. We should consider whether this needs to be transformable
// to `Date` or similar.
guard self._seconds >= 0 && self._seconds <= 61 else {
throw ASN1Error.invalidASN1Object
}
// Fractional seconds may not be negative and may not be 1 or more.
guard self._fractionalSeconds >= 0 && self._fractionalSeconds < 1 else {
throw ASN1Error.invalidASN1Object
}
}
}
}
@@ -0,0 +1,345 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An Object Identifier is a representation of some kind of object.
///
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers. Object identifiers
/// form a nested tree of namespaces.
///
/// The most common way to construct an OID is to create one using an array literal. For example, the OID 2.5.4.41 can be created
/// as:
///
/// ```swift
/// let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
/// ```
///
/// This object also has a number of pre-existing values defined in namespaces. Users are encouraged to create their own namespaces to
/// make it easier to use OIDs in their own serialization code.
public struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.objectIdentifier
}
@usableFromInline
var _oidComponents: [UInt]
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(var content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// We have to parse the content. From the spec:
//
// > Each subidentifier is represented as a series of (one or more) octets. Bit 8 of each octet indicates whether it
// > is the last in the series: bit 8 of the last octet is zero, bit 8 of each preceding octet is one. Bits 7 to 1 of
// > the octets in the series collectively encode the subidentifier. Conceptually, these groups of bits are concatenated
// > to form an unsigned binary number whose most significant bit is bit 7 of the first octet and whose least significant
// > bit is bit 1 of the last octet. The subidentifier shall be encoded in the fewest possible octets[...].
// >
// > The number of subidentifiers (N) shall be one less than the number of object identifier components in the object identifier
// > value being encoded.
// >
// > The numerical value of the first subidentifier is derived from the values of the first _two_ object identifier components
// > in the object identifier value being encoded, using the formula:
// >
// > (X*40) + Y
// >
// > where X is the value of the first object identifier component and Y is the value of the second object identifier component.
//
// Yeah, this is a bit bananas, but basically there are only 3 first OID components (0, 1, 2) and there are no more than 39 children
// of nodes 0 or 1. In my view this is too clever by half, but the ITU.T didn't ask for my opinion when they were coming up with this
// scheme, likely because I was in middle school at the time.
var subcomponents = [UInt]()
while content.count > 0 {
subcomponents.append(try content.readUIntUsing8BitBytesASN1Discipline())
}
guard subcomponents.count >= 2 else {
throw ASN1Error.invalidObjectIdentifier
}
// Now we need to expand the subcomponents out. This means we need to undo the step above. The first component will be in the range 0..<40
// when the first oidComponent is 0, 40..<80 when the first oidComponent is 1, and 80+ when the first oidComponent is 2.
var oidComponents = [UInt]()
oidComponents.reserveCapacity(subcomponents.count + 1)
switch subcomponents.first! {
case ..<40:
oidComponents.append(0)
oidComponents.append(subcomponents.first!)
case 40 ..< 80:
oidComponents.append(1)
oidComponents.append(subcomponents.first! - 40)
default:
oidComponents.append(2)
oidComponents.append(subcomponents.first! - 80)
}
oidComponents.append(contentsOf: subcomponents.dropFirst())
self._oidComponents = oidComponents
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
var components = self._oidComponents[...]
guard let firstComponent = components.popFirst(), let secondComponent = components.popFirst() else {
preconditionFailure("Invalid number of OID components: must be at least two!")
}
let serializedFirstComponent = (firstComponent * 40) + secondComponent
ASN1ObjectIdentifier._writeOIDSubidentifier(serializedFirstComponent, into: &bytes)
while let component = components.popFirst() {
ASN1ObjectIdentifier._writeOIDSubidentifier(component, into: &bytes)
}
}
}
@inlinable
static func _writeOIDSubidentifier(_ identifier: UInt, into array: inout [UInt8]) {
array.writeUsing7BitBytesASN1Discipline(unsignedInteger: identifier)
}
}
}
extension ASN1.ASN1ObjectIdentifier: Hashable {}
extension ASN1.ASN1ObjectIdentifier: Sendable { }
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
@inlinable
public init(arrayLiteral elements: UInt...) {
self._oidComponents = elements
}
}
extension ASN1.ASN1ObjectIdentifier {
/// Represents a namespace for OIDs that identify named Elliptic Curves.
///
/// These OIDs are defined in RFC 5480.
public enum NamedCurves {
/// Represents the NIST P256 curve. Also called `prime256v1`.
public static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
/// Represents the NIST P384 curve.
public static let secp384r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 34]
/// Represents the NIST P521 curve.
public static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
}
/// Represents a namespace for OIDs that identify an algorithm within an
/// `AlgorithmIdentifier` object.
public enum AlgorithmIdentifier {
/// Identifies an elliptic curve public key.
///
/// This identifier is defined in RFC 5480. `AlgorithmIdentifier` objects with this key have a parameters
/// value defined in that RFC.
public static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
/// Identifies a PKCS#1v1.5 RSA signature using SHA256 as the hash algorithm.
///
/// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL.
public static let sha256WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 11]
/// Identifies a PKCS#1v1.5 RSA signature using SHA384 as the hash algorithm.
///
/// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL.
public static let sha384WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 12]
/// Identifies a PKCS#1v1.5 RSA signature using SHA512 as the hash algorithm.
///
/// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL.
public static let sha512WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 13]
/// Identifies an RSA PSS signature.
///
/// This identifier is defined in RFC 4055. When used, the parameters will be `RSASSA-PSS-params` as
/// defined in that RFC.
public static let rsaPSS: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 10]
/// Identifies an RSA public key.
///
/// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL.
public static let rsaEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 1]
}
/// Represents a namespace for OIDs that identify Relative Distinguished Name components.
///
/// An enormous number of these identifiers exist. A non-exhaustive list of them is available in
/// RFC 4519.
public enum NameAttributes {
/// The 'name' attribute type is the attribute supertype from which user
/// attribute types with the name syntax inherit. Such attribute types
/// are typically used for naming. The attribute type is multi-valued.
public static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41]
/// The 'sn' ('surname' in X.500) attribute type contains name strings
/// for the family names of a person.
public static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4]
/// The 'givenName' attribute type contains name strings that are the
/// part of a person's name that is not their surname.
public static let givenName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 42]
/// The 'initials' attribute type contains strings of initials of some or
/// all of an individual's names, except the surname(s).
public static let initials: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 43]
/// The 'generationQualifier' attribute type contains name strings that
/// are typically the suffix part of a person's name.
public static let generationQualifier: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 44]
/// The 'cn' ('commonName' in X.500) attribute type contains names of an
/// object. If the object corresponds to a person, it is typically the person's full
/// name.
///
/// In modern usage, the common name typically represents a general identifier of an actor.
public static let commonName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 3]
/// The 'l' ('localityName' in X.500) attribute type contains names of a
/// locality or place, such as a city, county, or other geographic
/// region.
public static let localityName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 7]
/// The 'st' ('stateOrProvinceName' in X.500) attribute type contains the
/// full names of states or provinces.
public static let stateOrProvinceName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 8]
/// The 'o' ('organizationName' in X.500) attribute type contains the
/// names of an organization.
public static let organizationName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 10]
/// The 'ou' ('organizationalUnitName' in X.500) attribute type contains
/// the names of an organizational unit.
public static let organizationalUnitName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 11]
/// The 'title' attribute type contains the title of a person in their
/// organizational context.
public static let title: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 12]
/// The 'dnQualifier' attribute type contains disambiguating information
/// strings to add to the relative distinguished name of an entry. The
/// information is intended for use when merging data from multiple
/// sources in order to prevent conflicts between entries that would
/// otherwise have the same name.
public static let dnQualifier: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 46]
/// The 'c' ('countryName' in X.500) attribute type contains a two-letter
/// ISO 3166 [ISO3166] country code.
public static let countryName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 6]
/// The 'serialNumber' attribute type contains the serial numbers of
/// devices.
public static let serialNumber: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 5]
/// The pseudonym attribute type contains a pseudonym of the subject.
public static let pseudonym: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 65]
/// 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: ASN1.ASN1ObjectIdentifier = [0, 9, 2342, 19200300, 100, 1, 25]
/// The emailAddress attribute type specifies the electronic-mail address
/// or addresses of a subject as an unstructured ASCII string.
public static let emailAddress: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 113549, 1, 9, 1]
}
/// Represents a namespace for OIDs corresponding to OCSP identifiers.
///
/// The meaning of these OIDs is defined in RFC 6960.
public enum OCSP {
/// Identifies a `BasicOCSPResponse`.
public static let basicResponse: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 1, 1]
}
}
extension ArraySlice where Element == UInt8 {
@inlinable
mutating func readUIntUsing8BitBytesASN1Discipline() throws -> UInt {
// In principle OID subidentifiers and long tags can be too large to fit into a UInt. We are choosing to not care about that
// because for us it shouldn't matter.
guard let subidentifierEndIndex = self.firstIndex(where: { $0 & 0x80 == 0x00 }) else {
throw ASN1Error.invalidASN1Object
}
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
// need to be encoded in the minimal number of bytes, so we need to reject this.
throw ASN1Error.invalidASN1Object
}
self = self[self.index(after: subidentifierEndIndex)...]
// We need to compact the bits. These are 7-bit integers, which is really awkward.
return try UInt(sevenBitBigEndianBytes: oidSlice)
}
}
extension UInt {
@inlinable
init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
// We need to know how many bytes we _need_ to store this "int". As a base optimization we refuse to parse
// anything larger than 9 bytes wide, even though conceptually we could fit a few more bits.
guard ((bytes.count * 7) + 7) / 8 <= MemoryLayout<UInt>.size else {
throw ASN1Error.invalidASN1Object
}
self = 0
let shiftSizes = stride(from: 0, to: bytes.count * 7, by: 7).reversed()
var index = bytes.startIndex
for shift in shiftSizes {
self |= UInt(bytes[index] & 0x7F) << shift
bytes.formIndex(after: &index)
}
}
}
extension Array where Element == UInt8 {
@inlinable
mutating func writeUsing7BitBytesASN1Discipline(unsignedInteger identifier: UInt) {
// An OID subidentifier or long-form tag is written as an integer over 7-bit bytes, where the last byte has the top bit unset.
// The first thing we need is to know how many bits we need to write
let bitsToWrite = UInt.bitWidth - identifier.leadingZeroBitCount
let bytesToWrite = (bitsToWrite + 6) / 7
guard bytesToWrite > 0 else {
// Just a zero.
self.append(0)
return
}
for byteNumber in (1..<bytesToWrite).reversed() {
let shift = byteNumber * 7
let byte = UInt8((identifier >> shift) & 0x7f) | 0x80
self.append(byte)
}
// Last byte to append here, we must unset the top bit.
let byte = UInt8((identifier & 0x7F))
self.append(byte)
}
}
@@ -0,0 +1,277 @@
@usableFromInline
enum TimeUtilities {
@inlinable
static func generalizedTimeFromBytes(_ bytes: ArraySlice<UInt8>) throws -> ASN1.GeneralizedTime {
var bytes = bytes
// 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 {
throw ASN1Error.invalidASN1Object
}
// 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'),
// 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 {
throw ASN1Error.invalidASN1Object
}
// There may be some fractional seconds.
var fractionalSeconds: Double = 0
if bytes.first == UInt8(ascii: ".") {
fractionalSeconds = try bytes._readFractionalSeconds()
}
// The next character _must_ be Z, or the encoding is invalid.
guard bytes.popFirst() == UInt8(ascii: "Z") else {
throw ASN1Error.invalidASN1Object
}
// Great! There better not be anything left.
guard bytes.count == 0 else {
throw ASN1Error.invalidASN1Object
}
return try ASN1.GeneralizedTime(year: rawYear,
month: rawMonth,
day: rawDay,
hours: rawHour,
minutes: rawMinutes,
seconds: rawSeconds,
fractionalSeconds: fractionalSeconds)
}
@inlinable
static func utcTimeFromBytes(_ bytes: ArraySlice<UInt8>) throws -> ASN1.UTCTime {
var bytes = bytes
// 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 {
throw ASN1Error.invalidASN1Object
}
// 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 {
throw ASN1Error.invalidASN1Object
}
// The next character _must_ be Z, or the encoding is invalid.
guard bytes.popFirst() == UInt8(ascii: "Z") else {
throw ASN1Error.invalidASN1Object
}
// Great! There better not be anything left.
guard bytes.count == 0 else {
throw ASN1Error.invalidASN1Object
}
let actualYear = rawYear < 50 ? rawYear &+ 2000 : rawYear &+ 1900
return try ASN1.UTCTime(year: actualYear,
month: rawMonth,
day: rawDay,
hours: rawHour,
minutes: rawMinutes,
seconds: rawSeconds)
}
@inlinable
static func daysInMonth(_ month: Int, ofYear year: Int) -> Int? {
switch month {
case 1:
return 31
case 2:
// This one has a dependency on the year!
// A leap year occurs in any year divisible by 4, except when that year is divisible by 100,
// unless the year is divisible by 400.
let isLeapYear = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))
return isLeapYear ? 29 : 28
case 3:
return 31
case 4:
return 30
case 5:
return 31
case 6:
return 30
case 7:
return 31
case 8:
return 31
case 9:
return 30
case 10:
return 31
case 11:
return 30
case 12:
return 31
default:
return nil
}
}
}
extension ArraySlice where Element == UInt8 {
@inlinable
mutating func _readFourDigitDecimalInteger() -> Int? {
guard let first = self._readTwoDigitDecimalInteger(),
let second = self._readTwoDigitDecimalInteger() else {
return nil
}
// Unchecked math is still safe here: we're in Int32 space, and this number cannot
// get any larger than 9999.
return (first &* 100) &+ second
}
@inlinable
mutating func _readTwoDigitDecimalInteger() -> Int? {
guard let firstASCII = self.popFirst(),
let secondASCII = self.popFirst() else {
return nil
}
guard let first = Int(fromDecimalASCII: firstASCII),
let second = Int(fromDecimalASCII: secondASCII) else {
return nil
}
// Unchecked math is safe here: we're in Int32 space at the very least, and this number cannot
// possibly be smaller than zero or larger than 99.
return (first &* 10) &+ (second)
}
/// This may only be called if there's a leading period: we precondition on this fact.
@inlinable
mutating func _readFractionalSeconds() throws -> Double {
precondition(self.popFirst() == UInt8(ascii: "."))
var numerator = 0
var denominator = 1
while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) {
self = self.dropFirst()
let (newNumerator, multiplyOverflow) = numerator.multipliedReportingOverflow(by: 10)
let (newDenominator, secondMultiplyOverflow) = denominator.multipliedReportingOverflow(by: 10)
let (newNumeratorWithAdded, addingOverflow) = newNumerator.addingReportingOverflow(next)
// If the new denominator overflows, we just cap to the old value.
if !secondMultiplyOverflow {
denominator = newDenominator
}
// If the numerator overflows, we don't support the result.
if multiplyOverflow || addingOverflow {
throw ASN1Error.invalidASN1Object
}
numerator = newNumeratorWithAdded
}
// Ok, we're either at the end or the next character is a Z. One final check: there may not have
// been any trailing zeros here. This means the number may not be 0 mod 10.
if numerator % 10 == 0 {
throw ASN1Error.invalidASN1Object
}
return Double(numerator) / Double(denominator)
}
}
extension Array where Element == UInt8 {
@inlinable
mutating func append(_ generalizedTime: ASN1.GeneralizedTime) {
self._appendFourDigitDecimal(generalizedTime.year)
self._appendTwoDigitDecimal(generalizedTime.month)
self._appendTwoDigitDecimal(generalizedTime.day)
self._appendTwoDigitDecimal(generalizedTime.hours)
self._appendTwoDigitDecimal(generalizedTime.minutes)
self._appendTwoDigitDecimal(generalizedTime.seconds)
// Ok, tricky moment here. Is the fractional part non-zero? If it is, we need to write it out as well.
if generalizedTime.fractionalSeconds != 0 {
let stringified = String(generalizedTime.fractionalSeconds)
assert(stringified.starts(with: "0."))
self.append(contentsOf: stringified.utf8.dropFirst(1))
// Remove any trailing zeros from self, they are forbidden.
while self.last == 0 {
self = self.dropLast()
}
}
self.append(UInt8(ascii: "Z"))
}
@inlinable
mutating func append(_ utcTime: ASN1.UTCTime) {
precondition((1950..<2050).contains(utcTime.year))
if utcTime.year >= 2000 {
self._appendTwoDigitDecimal(utcTime.year &- 2000)
} else {
self._appendTwoDigitDecimal(utcTime.year &- 1900)
}
self._appendTwoDigitDecimal(utcTime.month)
self._appendTwoDigitDecimal(utcTime.day)
self._appendTwoDigitDecimal(utcTime.hours)
self._appendTwoDigitDecimal(utcTime.minutes)
self._appendTwoDigitDecimal(utcTime.seconds)
self.append(UInt8(ascii: "Z"))
}
@inlinable
mutating func _appendFourDigitDecimal(_ number: Int) {
assert(number >= 0 && number <= 9999)
// Each digit can be isolated by dividing by the place and then taking the result modulo 10.
// This is annoyingly division heavy. There may be a better algorithm floating around.
// Unchecked math is fine, there cannot be an overflow here.
let asciiZero = UInt8(ascii: "0")
self.append(UInt8(truncatingIfNeeded: (number / 1000) % 10) &+ asciiZero)
self.append(UInt8(truncatingIfNeeded: (number / 100) % 10) &+ asciiZero)
self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero)
self.append(UInt8(truncatingIfNeeded: number % 10) &+ asciiZero)
}
@inlinable
mutating func _appendTwoDigitDecimal(_ number: Int) {
assert(number >= 0 && number <= 99)
// Each digit can be isolated by dividing by the place and then taking the result modulo 10.
// This is annoyingly division heavy. There may be a better algorithm floating around.
// Unchecked math is fine, there cannot be an overflow here.
let asciiZero = UInt8(ascii: "0")
self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero)
self.append(UInt8(truncatingIfNeeded: number % 10) &+ asciiZero)
}
}
extension Int {
@inlinable
init?(fromDecimalASCII ascii: UInt8) {
let asciiZero = UInt8(ascii: "0")
let zeroToNine = 0...9
// These are all coming from UInt8space, the subtraction cannot overflow.
let converted = Int(ascii) &- Int(asciiZero)
guard zeroToNine.contains(converted) else {
return nil
}
self = converted
}
}
@@ -0,0 +1,184 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// UTCTime represents a date and time.
///
/// In DER format, this is always in the form of `YYMMDDHHMMSSZ`, with no support for fractional seconds.
/// The time is always in the UTC time zone.
///
/// ``UTCTime`` differs from ``GeneralizedTime`` in that it only has support for a two-digit year. This
/// means that it can only encode dates between 1950 and 2049. For dates outside that range, prefer
/// ``GeneralizedTime``.
public struct UTCTime: ASN1ImplicitlyTaggable, Hashable, Sendable {
@inlinable
public static var defaultIdentifier: ASN1.ASN1Identifier {
.utcTime
}
/// The numerical year.
@inlinable
public var year: Int {
get {
return self._year
}
set {
self._year = newValue
try! self._validate()
}
}
/// The numerical month.
@inlinable
public var month: Int {
get {
return self._month
}
set {
self._month = newValue
try! self._validate()
}
}
/// The numerical day.
@inlinable
public var day: Int {
get {
return self._day
}
set {
self._day = newValue
try! self._validate()
}
}
/// The numerical hours.
@inlinable
public var hours: Int {
get {
return self._hours
}
set {
self._hours = newValue
try! self._validate()
}
}
/// The numerical minutes.
@inlinable
public var minutes: Int {
get {
return self._minutes
}
set {
self._minutes = newValue
try! self._validate()
}
}
/// The numerical seconds.
@inlinable
public var seconds: Int {
get {
return self._seconds
}
set {
self._seconds = newValue
try! self._validate()
}
}
@usableFromInline var _year: Int
@usableFromInline var _month: Int
@usableFromInline var _day: Int
@usableFromInline var _hours: Int
@usableFromInline var _minutes: Int
@usableFromInline var _seconds: Int
/// Construct a new ``ASN1/UTCTime`` from individual components.
///
/// - parameters:
/// - year: The numerical year. Must be in the range 1950 to 2049.
/// - month: The numerical month
/// - day: The numerical day
/// - hours: The numerical hours
/// - minutes: The numerical minutes
/// - seconds: The numerical seconds
@inlinable
public init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int) throws {
self._year = year
self._month = month
self._day = day
self._hours = hours
self._minutes = minutes
self._seconds = seconds
try self._validate()
}
@inlinable
public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
guard node.identifier == identifier else {
throw ASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
self = try TimeUtilities.utcTimeFromBytes(content)
}
@inlinable
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
coder.appendPrimitiveNode(identifier: identifier) { bytes in
bytes.append(self)
}
}
@inlinable
func _validate() throws {
// Validate that the structure is well-formed.
// UTCTime can only hold years between 1950 and 2049.
guard self._year >= 1950 && self._year < 2050 else {
throw ASN1Error.invalidASN1Object
}
// This also validates the month.
guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else {
throw ASN1Error.invalidASN1Object
}
guard self._day >= 1 && self._day <= daysInMonth else {
throw ASN1Error.invalidASN1Object
}
guard self._hours >= 0 && self._hours < 24 else {
throw ASN1Error.invalidASN1Object
}
guard self._minutes >= 0 && self._minutes < 60 else {
throw ASN1Error.invalidASN1Object
}
// We allow leap seconds here, but don't validate it.
// This exposes us to potential confusion if we naively implement
// comparison here. We should consider whether this needs to be transformable
// to `Date` or similar.
guard self._seconds >= 0 && self._seconds <= 61 else {
throw ASN1Error.invalidASN1Object
}
}
}
}
+304
View File
@@ -0,0 +1,304 @@
# Encoding and Decoding DER
Serialize and deserialize objects from DER format.
## Overview
When working with your own ASN.1 types, the biggest problem you'll have is writing the code to serialize and deserialize them from DER format.
This module does not provide an ASN.1 compiler which can automatically synthesise this code for you. Instead, you have to write it yourself.
This is some unfortunate boilerplate, but the good news is that it's straightforward enough that you'll get it done in no time.
By way of a worked example, we can build up a few types in increasing complexity.
## ECDSA Signature
Our starting point is the ECDSA signature type, defined like this:
```
ECDSASignature ::= SEQUENCE {
r INTEGER,
s INTEGER }
```
This defines `ECDSASignature` as a `SEQUENCE` of two `INTEGER` values.
In ASN.1, `SEQUENCE` is often used to define a record type. This is much like a Swift `struct`: an ordered series of named fields, often
of different types. That makes a `struct` the natural representation for our `ECDSASignature` type:
```swift
struct ECDSASignature {
}
```
### Storing Fields
Our next problem is to work out the fields we want to store in our type. A natural choice might be `Int`, but some more careful reading will
clue us in to the fact that an ASN.1 `INTEGER` type is of arbitrary size. In the case of ECDSA signatures, these can be very large: 32 bytes
large or more! These won't fit into `Int`.
To address this issue, ``SwiftASN1`` defines two helpers. The first is a protocol, ``ASN1IntegerRepresentable``. This allows users that have
access to a preferred arbitrary-precision integer type to decode directly to that type. The second is a conformance of `ArraySlice<UInt8>` to
``ASN1IntegerRepresentable``. This conformance allows us to just store the raw big-endian bytes of the INTEGER fields without needing to
define an arbitrary-precision integer ourselves. As we mostly care about these numbers as arbitrary byte sequences, we'll use this
escape hatch.
```swift
struct ECDSASignature {
var r: ArraySlice<UInt8>
var s: ArraySlice<UInt8>
init(r: ArraySlice<UInt8>, s: ArraySlice<UInt8>) {
self.r = r
self.s = s
}
}
```
### Decoding from DER
To decode from DER, we'll need to implement ``ASN1Parseable``. As this is a `SEQUENCE` type, however, we can safely implement
``ASN1ImplicitlyTaggable``. Most types can do so, especially anything that is a `SEQUENCE` type.
To conform we need to implement the protocol requirement ``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo``. This function
will pass us a pair of arguments. The first is the ``ASN1/ASN1Node`` representing the root of the ASN.1 object tree we've been asked to parse
the `ECDSASignature` from. The second is the ``ASN1/ASN1Identifier`` we expect to have this node to have. In many cases this will be
``ASN1/ASN1Identifier/sequence``, but we will happily use whatever we're told to.
The first trick is to unwrap the `SEQUENCE`. To do that, we can use ``ASN1/sequence(_:identifier:_:)``. This checks whether the ``ASN1/ASN1Node``
we pass to it has the right ``ASN1/ASN1Identifier`` and that it is a constructed node. Assuming all those checks pass, our builder function
will be invoked with an ``ASN1/ASN1NodeCollection/Iterator`` that contains the nodes within the `SEQUENCE`.
This initial scaffolding will look like this:
```swift
extension ECDSASignature: ASN1ImplicitlyTaggable {
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
// TODO
}
}
}
```
Next, we need to decode the constituent objects. This is where the recursive nature of ASN.1 works in our favour. These sub-objects
(in this case of ASN.1 type `INTEGER`) are themselves described as trees of ASN.1 nodes. For `INTEGER` specifically this tree will
only have a root node, but in general all ASN.1 objects can be parsed from a single root node.
Fortunately for us, this is exactly the interface that ``ASN1Parseable`` provides us. So we can safely recurse into the child objects using
the helper method ``ASN1Parseable/init(asn1Encoded:)-5tkco``. This handy method will even take care of consuming the node from the iterator for us.
The result is a method body that looks like this:
```swift
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let r = try ArraySlice<UInt8>(asn1Encoded: &nodes)
let s = try ArraySlice<UInt8>(asn1Encoded: &nodes)
return ECDSASignature(r: r, s: s)
}
}
```
Note that we don't need to confirm the exact length of the ``ASN1/ASN1NodeCollection/Iterator`` `nodes`. The helper method
``ASN1Parseable/init(asn1Encoded:)-5tkco`` will automatically throw an error if there is no node available to decode an object from, and
``ASN1/sequence(_:identifier:_:)`` will confirm that all the nodes were consumed from the child iterator.
This composition approach scales to more complex types. Any ASN.1 composite object can be implemented using ``ASN1/sequence(_:identifier:_:)``
and recursive initialization of ever-smaller ASN.1 objects.
### Encoding to DER
Next we need to implement the inverse method, ``ASN1ImplicitlyTaggable/serialize(into:withIdentifier:)``. This method is implemented in much the
same was as our parsing method, but in reverse.
Importantly, here we don't have a `sequence` helper. Instead we use the more general operation, ``ASN1/Serializer/appendConstructedNode(identifier:_:)``.
This doesn't have any semantic implications: it applies a general purpose ASN.1 constructed node with a given identifier.
```swift
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.r)
try coder.serialize(self.s)
}
}
```
Note that we have shadowed our `coder` in this block. This is important: we're passed our original ``ASN1/Serializer`` `coder` as an `inout`
variable, and ``ASN1/Serializer/appendConstructedNode(identifier:_:)`` is a `mutating` operation. The closure it takes will receive the same
serializer as an `inout` again, allowing us to subsequently serialize new objects.
We can then recurse down the tree. ``ASN1/Serializer/serialize(_:)-3281j`` is a handy wrapper that will ultimately invoke ``ASN1Serializable/serialize(into:)`` on
the node in question.
### Final Result
We're done! Ultimately we've ended up with the following type. Don't worry too much about our use of ``ASN1ImplicitlyTaggable/defaultIdentifier`` here: we'll cover it
in [Implicit Tagging](#Implicit-Tagging).
```swift
struct ECDSASignature: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
}
var r: ArraySlice<UInt8>
var s: ArraySlice<UInt8>
init(r: ArraySlice<UInt8>, s: ArraySlice<UInt8>) {
self.r = r
self.s = s
}
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let r = try ArraySlice<UInt8>(asn1Encoded: &nodes)
let s = try ArraySlice<UInt8>(asn1Encoded: &nodes)
return ECDSASignature(r: r, s: s)
}
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.r)
try coder.serialize(self.s)
}
}
}
```
## Alternative Tagging
ASN.1 supports overriding tags in two ways: implicit and explicit tagging. ``SwiftASN1`` supports both.
It's often difficult to work out from an isolated snippet of ASN.1 definition whether a custom tag is explicit
or implicit. For clarity, this document will attempt to express on each line whether a tag is explicit or
implicit.
### Implicit Tagging
Implicit tagging replaces the usual tag for an object with a new tag. This makes it impossible to know the type
of the object without having the ASN.1 definition. It can also limit some extensibility.
The principal advantage of implicit tagging is that there is no need to add the extra tag that explicit tagging requires.
This will save at least 2 bytes on each object, but may save more.
An object that can be implicitly tagged should conform to ``ASN1ImplicitlyTaggable``. This will make a number of extra
methods available to users of that type, as well as forcing users to implement
``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo`` and ``ASN1ImplicitlyTaggable/serialize(into:withIdentifier:)``.
These two methods allow the caller to tell the type what its implicit tag is. The implementer is required to use that tag
for the top-level object (usually a constructed node).
> Note: A few objects should not conform to ``ASN1ImplicitlyTaggable``. These objects are ones which, if they lost their tag,
> would not be able to correctly decode themselves.
>
> An example of such a type is a CHOICE type. For example:
>
> ```
> CannotBeImplicitlyTagged ::= CHOICE {
> integerVal INTEGER
> boolVal BOOLEAN
> stringVal UTF8String }
> ```
>
> As CHOICE types encode as whatever of the choice values is chosen, the tag is necessary to know which of these cases to decode.
> As a result, we cannot implicitly tag a CHOICE object: it'll be impossible to decode. This is true even if the various CHOICE
> fields are implicitly or explicitly tagged with custom tags: that tag will be obliterated if the CHOICE itself is implicitly
> tagged.
Users can then decode an implicitly tagged object using one of the helper methods. For example, consider
this simple ASN.1 type:
```
ContainsImplicitTag ::= SEQUENCE {
value [0] IMPLICIT INTEGER }
```
We can decode it like so:
```swift
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
self = try ASN1.sequence(rootNode, identifier: .sequence) { nodes in
let value = try Int64(asn1Encoded: &nodes, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false))
return ContainsImplicitTag(value: value)
}
}
```
We can also encode it similarly:
```swift
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try self.value.serialize(into: &coder, withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false))
}
}
```
Note that we need to construct the ``ASN1/ASN1Identifier`` directly in this case. This is common whenever we have an implicit
tag that needs to be passed to an an object that is unconditionally present. It's often a wise idea to store this tag in a `static let`
for ease of access.
There are a few helper functions for circumstances when an object has an implicit tag and is also either `OPTIONAL` or `DEFAULT`. For parsing,
those are:
- ``ASN1/optionalImplicitlyTagged(_:tag:)``
- ``ASN1/decodeDefault(_:identifier:defaultValue:)``
- ``ASN1/decodeDefault(_:identifier:defaultValue:_:)``
For serializing, those are:
- ``ASN1/Serializer/serializeOptionalImplicitlyTagged(_:)``
- ``ASN1/Serializer/serializeOptionalImplicitlyTagged(_:withIdentifier:)``
Note that in a few cases you will see an object that is `OPTIONAL` or `DEFAULT` without a note of a tag. In this case, the implicit tag is
identical to the normal tag for this object.
### Explicit Tagging
Explicit tagging wraps an object in a new constructed object whose tag is equal to the explicit tag defined in the ASN.1 definition. This allows
the explicitly tagged object to still retain its original tag, helping the encoding to remain self-describing. Additionally, unlike with implicit
tagging, all nodes can be explicitly tagged, as the underlying representation of that node is not affected.
As a worked example of explicit tagging, consider the following object:
```
ContainsExplicitTag ::= SEQUENCE {
value [0] EXPLICIT INTEGER }
```
We can decode it like so:
```swift
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
self = try ASN1.sequence(rootNode, identifier: .sequence) { nodes in
let value = try ASN1.explicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
try Int64(asn1Encoded: $0)
}
return ContainsExplicitTag(value: value)
}
}
```
We can also encode it similarly:
```swift
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(self.value, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
}
}
```
As with the implicitly tagged case, most explicit tags are used in cases where the object is also either `OPTIONAL` or `DEFAULT`. We have a number
helper methods for those. For parsing:
- ``ASN1/optionalExplicitlyTagged(_:tagNumber:tagClass:_:)``
- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:)``
- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:_:)``
For serializing, users are expected to implement the DEFAULT/OPTIONAL logic themselves.
+85
View File
@@ -0,0 +1,85 @@
# ``SwiftASN1``
An implementation of ASN.1 types and DER serialization.
## Overview
ASN.1, and the DER encoding scheme, is a commonly used object serialization format. The most common use-cases for ASN.1 in
general computing are in the cryptographic space, but there are a number of use-cases in a wide range of fields. This module
provides an implementation of a number of ASN.1 types, as well as the DER serialization format for ASN.1.
ASN.1 can be used abstractly to describe essentially any kind of object. ASN.1 objects are made up of either primitive or
composite (called "constructed") types. Individual scalar objects can be combined into aggregate types, and composed essentially
arbitrarily to form abstract object formats.
Importantly, the ASN.1 object description does not define a specific encoding for these objects. Instead there are a wide range
of possible ways to serialize or deserialize an ASN.1 object. Some of the most prominent are BER (the Basic Encoding Rules),
CER (the Canonical Encoding Rules), DER (the Distinguished Encoding Rules), and XER (the XML Encoding Rules). For the cryptographic
use-case DER is the standard choice, as a given ASN.1 object can be encoded in only one way under DER. This makes signing and verifying
vastly easier, as it is at least in principle possible to perfectly reconstruct the serialization of a parsed object.
This module provides several moving pieces:
1. A high-level representation of an ASN.1 object, in the form of a tree of object nodes (``ASN1/ASN1Node``).
2. A DER parser that can construct the ASN.1 tree from serialized bytes (``ASN1/parse(_:)-41gug``).
3. A DER serializer that can construct serialized bytes from the ASN.1 tree (``ASN1/Serializer``).
4. A number of built-in ASN.1 types, representing common constructs.
These moving pieces combine to provide support for the DER representation of ASN.1 suitable for a wide range of cryptographic uses.
## Topics
### Articles
- <doc:DecodingASN1>
### Parsing DER
- ``ASN1/parse(_:)-41gug``
- ``ASN1/parse(_:)-8ar01``
- ``ASN1Parseable``
- ``ASN1Serializable``
- ``ASN1ImplicitlyTaggable``
- ``ASN1/sequence(_:identifier:_:)``
- ``ASN1/sequence(of:identifier:rootNode:)``
- ``ASN1/sequence(of:identifier:nodes:)``
- ``ASN1/set(_:identifier:_:)``
- ``ASN1/decodeDefault(_:identifier:defaultValue:_:)``
- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:_:)``
- ``ASN1/decodeDefault(_:defaultValue:)``
- ``ASN1/decodeDefault(_:identifier:defaultValue:)``
- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:)``
- ``ASN1/optionalExplicitlyTagged(_:tagNumber:tagClass:_:)``
- ``ASN1/optionalImplicitlyTagged(_:tag:)``
- ``ASN1/explicitlyTagged(_:tagNumber:tagClass:_:)-6iqvq``
- ``ASN1/explicitlyTagged(_:tagNumber:tagClass:_:)-4ystp``
### Serializing DER
- ``ASN1/Serializer``
- ``ASN1Serializable``
- ``ASN1ImplicitlyTaggable``
### Representing ASN.1 types
- ``ASN1/ASN1Node``
- ``ASN1/ASN1NodeCollection``
- ``ASN1/ASN1Identifier``
### Built-in ASN.1 types
- ``ASN1IntegerRepresentable``
- ``IntegerBytesCollection``
- ``ASN1/GeneralizedTime``
- ``ASN1/ASN1BitString``
- ``ASN1/UTCTime``
- ``ASN1/ASN1OctetString``
- ``ASN1/ASN1Any``
- ``ASN1/ASN1Null``
- ``ASN1/ASN1ObjectIdentifier``
- ``ASN1/ASN1UTF8String``
- ``ASN1/ASN1PrintableString``
- ``ASN1/ASN1BMPString``
- ``ASN1/ASN1IA5String``
- ``ASN1/ASN1TeletexString``
- ``ASN1/ASN1UniversalString``
+53
View File
@@ -0,0 +1,53 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
/// An ECDSA signature is laid out as follows:
///
/// ECDSASignature ::= SEQUENCE {
/// r INTEGER,
/// s INTEGER
/// }
///
/// This type is generic because our different backends want to use different bignum representations.
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
}
var r: IntegerType
var s: IntegerType
init(r: IntegerType, s: IntegerType) {
self.r = r
self.s = s
}
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let r = try IntegerType(asn1Encoded: &nodes)
let s = try IntegerType(asn1Encoded: &nodes)
return ECDSASignature(r: r, s: s)
}
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.r)
try coder.serialize(self.s)
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Errors that may be thrown while encoding or decoding ASN.1 objects.
public enum ASN1Error : Error {
/// The ASN.1 tag for this field is invalid or unsupported.
case invalidFieldIdentifier
/// The ASN.1 tag for the parsed field does not match the required format.
case unexpectedFieldType
/// An invalid ASN.1 object identifier was encountered.
case invalidObjectIdentifier
/// The format of the parsed ASN.1 object does not match the format required for the data type
/// being decoded.
case invalidASN1Object
/// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding.
case invalidASN1IntegerEncoding
/// An ASN.1 field was truncated and could not be decoded.
case truncatedASN1Field
/// The encoding used for the field length is not supported.
case unsupportedFieldLength
/// It was not possible to parse a string as a PEM document.
case invalidPEMDocument
/// A string was invalid
case invalidStringRepresentation
}
+116
View File
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Foundation)
import Foundation
extension ASN1 {
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
struct PEMDocument {
private static let lineLength = 64
var type: String
var derBytes: Data
init(pemString: String) throws {
// A PEM document looks like this:
//
// -----BEGIN <SOME DISCRIMINATOR>-----
// <base64 encoded bytes, 64 characters per line>
// -----END <SOME DISCRIMINATOR>-----
//
// This function attempts to parse this string as a PEM document, and returns the discriminator type
// and the base64 decoded bytes.
var lines = pemString.split { $0.isNewline }[...]
guard let first = lines.first, let last = lines.last else {
throw ASN1Error.invalidPEMDocument
}
guard let discriminator = first.pemStartDiscriminator, discriminator == last.pemEndDiscriminator else {
throw ASN1Error.invalidPEMDocument
}
// All but the last line must be 64 bytes. The force unwrap is safe because we require the lines to be
// greater than zero.
lines = lines.dropFirst().dropLast()
guard lines.count > 0,
lines.dropLast().allSatisfy({ $0.utf8.count == PEMDocument.lineLength }),
lines.last!.utf8.count <= PEMDocument.lineLength else {
throw ASN1Error.invalidPEMDocument
}
guard let derBytes = Data(base64Encoded: lines.joined()) else {
throw ASN1Error.invalidPEMDocument
}
self.type = discriminator
self.derBytes = derBytes
}
init(type: String, derBytes: Data) {
self.type = type
self.derBytes = derBytes
}
var pemString: String {
var encoded = self.derBytes.base64EncodedString()[...]
let pemLineCount = (encoded.utf8.count + PEMDocument.lineLength) / PEMDocument.lineLength
var pemLines = [Substring]()
pemLines.reserveCapacity(pemLineCount + 2)
pemLines.append("-----BEGIN \(self.type)-----")
while encoded.count > 0 {
let prefixIndex = encoded.index(encoded.startIndex, offsetBy: PEMDocument.lineLength, limitedBy: encoded.endIndex) ?? encoded.endIndex
pemLines.append(encoded[..<prefixIndex])
encoded = encoded[prefixIndex...]
}
pemLines.append("-----END \(self.type)-----")
return pemLines.joined(separator: "\n")
}
}
}
extension Substring {
fileprivate var pemStartDiscriminator: String? {
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
}
fileprivate var pemEndDiscriminator: String? {
return self.pemDiscriminator(expectedPrefix: "-----END ", expectedSuffix: "-----")
}
private func pemDiscriminator(expectedPrefix: String, expectedSuffix: String) -> String? {
var utf8Bytes = self.utf8[...]
// We want to split this sequence into three parts: the prefix, the middle, and the end
let prefixSize = expectedPrefix.utf8.count
let suffixSize = expectedSuffix.utf8.count
let prefix = utf8Bytes.prefix(prefixSize)
utf8Bytes = utf8Bytes.dropFirst(prefixSize)
let suffix = utf8Bytes.suffix(suffixSize)
utf8Bytes = utf8Bytes.dropLast(suffixSize)
guard prefix.elementsEqual(expectedPrefix.utf8), suffix.elementsEqual(expectedSuffix.utf8) else {
return nil
}
return String(utf8Bytes)
}
}
#endif
+97
View File
@@ -0,0 +1,97 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
// A PKCS#8 private key is one of two formats, depending on the version:
//
// For PKCS#8 we need the following for the private key:
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
//
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
//
// PrivateKey ::= OCTET STRING
//
// Attributes ::= SET OF Attribute
//
// We disregard the attributes because we don't support them anyway.
//
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
// ASN.1 parser and go again.
struct PKCS8PrivateKey: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
return .sequence
}
var algorithm: RFC5480AlgorithmIdentifier
var privateKey: ASN1.SEC1PrivateKey
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let version = try Int(asn1Encoded: &nodes)
guard version == 0 else {
throw ASN1Error.invalidASN1Object
}
let algorithm = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
let privateKeyBytes = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
// We ignore the attributes
_ = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in }
let sec1PrivateKeyNode = try ASN1.parse(privateKeyBytes.bytes)
let sec1PrivateKey = try ASN1.SEC1PrivateKey(asn1Encoded: sec1PrivateKeyNode)
if let innerAlgorithm = sec1PrivateKey.algorithm, innerAlgorithm != algorithm {
throw ASN1Error.invalidASN1Object
}
return try .init(algorithm: algorithm, privateKey: sec1PrivateKey)
}
}
private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws {
self.privateKey = privateKey
self.algorithm = algorithm
}
init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: [UInt8], publicKey: [UInt8]) {
self.algorithm = algorithm
// We nil out the private key here. I don't really know why we do this, but OpenSSL does, and it seems
// safe enough to do: it certainly avoids the possibility of disagreeing on what it is!
self.privateKey = ASN1.SEC1PrivateKey(privateKey: privateKey, algorithm: nil, publicKey: publicKey)
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(0) // version
try coder.serialize(self.algorithm)
// Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string.
var subCoder = ASN1.Serializer()
try subCoder.serialize(self.privateKey)
let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...])
try coder.serialize(serializedKey)
}
}
}
}
+104
View File
@@ -0,0 +1,104 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
// For private keys, SEC 1 uses:
//
// ECPrivateKey ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
// privateKey OCTET STRING,
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
// }
struct SEC1PrivateKey: ASN1ImplicitlyTaggable {
static var defaultIdentifier: ASN1.ASN1Identifier {
return .sequence
}
var algorithm: ASN1.RFC5480AlgorithmIdentifier?
var privateKey: ASN1.ASN1OctetString
var publicKey: ASN1.ASN1BitString?
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let version = try Int(asn1Encoded: &nodes)
guard 1 == version else {
throw ASN1Error.invalidASN1Object
}
let privateKey = try ASN1OctetString(asn1Encoded: &nodes)
let parameters = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
return try ASN1.ASN1ObjectIdentifier(asn1Encoded: node)
}
let publicKey = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
return try ASN1.ASN1BitString(asn1Encoded: node)
}
return try .init(privateKey: privateKey, algorithm: parameters, publicKey: publicKey)
}
}
private init(privateKey: ASN1.ASN1OctetString, algorithm: ASN1.ASN1ObjectIdentifier?, publicKey: ASN1.ASN1BitString?) throws {
self.privateKey = privateKey
self.publicKey = publicKey
self.algorithm = try algorithm.map { algorithmOID in
switch algorithmOID {
case ASN1ObjectIdentifier.NamedCurves.secp256r1:
return .ecdsaP256
case ASN1ObjectIdentifier.NamedCurves.secp384r1:
return .ecdsaP384
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
return .ecdsaP521
default:
throw ASN1Error.invalidASN1Object
}
}
}
init(privateKey: [UInt8], algorithm: RFC5480AlgorithmIdentifier?, publicKey: [UInt8]) {
self.privateKey = ASN1OctetString(contentBytes: privateKey[...])
self.algorithm = algorithm
self.publicKey = ASN1BitString(bytes: publicKey[...])
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(1) // version
try coder.serialize(self.privateKey)
if let algorithm = self.algorithm {
let oid: ASN1.ASN1ObjectIdentifier
switch algorithm {
case .ecdsaP256:
oid = ASN1ObjectIdentifier.NamedCurves.secp256r1
case .ecdsaP384:
oid = ASN1ObjectIdentifier.NamedCurves.secp384r1
case .ecdsaP521:
oid = ASN1ObjectIdentifier.NamedCurves.secp521r1
default:
throw ASN1Error.invalidASN1Object
}
try coder.serialize(oid, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
}
if let publicKey = self.publicKey {
try coder.serialize(publicKey, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific)
}
}
}
}
}
@@ -0,0 +1,122 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension ASN1 {
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
}
var algorithmIdentifier: RFC5480AlgorithmIdentifier
var key: ASN1.ASN1BitString
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
// The SPKI block looks like this:
//
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING
// }
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let algorithmIdentifier = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
let key = try ASN1.ASN1BitString(asn1Encoded: &nodes)
return SubjectPublicKeyInfo(algorithmIdentifier: algorithmIdentifier, key: key)
}
}
private init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: ASN1.ASN1BitString) {
self.algorithmIdentifier = algorithmIdentifier
self.key = key
}
internal init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: [UInt8]) {
self.algorithmIdentifier = algorithmIdentifier
self.key = ASN1BitString(bytes: key[...])
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.algorithmIdentifier)
try coder.serialize(self.key)
}
}
}
struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1.ASN1Identifier {
.sequence
}
var algorithm: ASN1.ASN1ObjectIdentifier
var parameters: ASN1.ASN1Any?
// case ecdsaP256
// case ecdsaP384
// case ecdsaP521
init(algorithm: ASN1.ASN1ObjectIdentifier, parameters: ASN1.ASN1Any?) {
self.algorithm = algorithm
self.parameters = parameters
}
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
// The AlgorithmIdentifier block looks like this.
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL
// }
//
// ECParameters ::= CHOICE {
// namedCurve OBJECT IDENTIFIER
// -- implicitCurve NULL
// -- specifiedCurve SpecifiedECDomain
// }
//
// We don't bother with helpers: we just try to decode it directly.
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
let parameters = nodes.next().map { ASN1.ASN1Any(asn1Encoded: $0) }
return .init(algorithm: algorithmOID, parameters: parameters)
}
}
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.algorithm)
if let parameters = self.parameters {
try coder.serialize(parameters)
}
}
}
}
}
// MARK: Algorithm Identifier Statics
extension ASN1.RFC5480AlgorithmIdentifier {
static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
static let ecdsaP384 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp384r1))
static let ecdsaP521 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
}
+178
View File
@@ -0,0 +1,178 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import SwiftASN1
final class ASN1StringTests: XCTestCase {
private func assertRoundTrips<ASN1Object: ASN1Parseable & ASN1Serializable & Equatable>(_ value: ASN1Object) throws {
var serializer = ASN1.Serializer()
try serializer.serialize(value)
let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes)
XCTAssertEqual(parsed, value)
}
func testUTF8StringEncoding() throws {
var serializer = ASN1.Serializer()
let originalString = ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4])
try serializer.serialize(originalString)
XCTAssertEqual(serializer.serializedBytes, [12, 4, 1, 2, 3, 4])
}
func testUTF8StringRoundTrips() throws {
try self.assertRoundTrips(ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4]))
}
func testUTF8StringContiguousBytes() throws {
let string = ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4])
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) }
}
func testTeletexStringEncoding() throws {
var serializer = ASN1.Serializer()
let originalString = ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4])
try serializer.serialize(originalString)
XCTAssertEqual(serializer.serializedBytes, [20, 4, 1, 2, 3, 4])
}
func testTeletexStringRoundTrips() throws {
try self.assertRoundTrips(ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4]))
}
func testTeletexStringContiguousBytes() throws {
let string = ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4])
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) }
}
func testPrintableStringEncoding() throws {
var serializer = ASN1.Serializer()
let originalString = try ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74])
try serializer.serialize(originalString)
XCTAssertEqual(serializer.serializedBytes, [19, 4, 0x54, 0x65, 0x73, 0x74])
}
func testPrintableStringRoundTrips() throws {
try self.assertRoundTrips(ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74]))
}
func testPrintableStringContiguousBytes() throws {
let string = try ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74])
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([0x54, 0x65, 0x73, 0x74])) }
}
func testUniversalStringEncoding() throws {
var serializer = ASN1.Serializer()
let originalString = ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4])
try serializer.serialize(originalString)
XCTAssertEqual(serializer.serializedBytes, [28, 4, 1, 2, 3, 4])
}
func testUniversalStringRoundTrips() throws {
try self.assertRoundTrips(ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4]))
}
func testUniversalStringContiguousBytes() throws {
let string = ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4])
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) }
}
func testBMPStringEncoding() throws {
var serializer = ASN1.Serializer()
let originalString = ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4])
try serializer.serialize(originalString)
XCTAssertEqual(serializer.serializedBytes, [30, 4, 1, 2, 3, 4])
}
func testBMPStringRoundTrips() throws {
try self.assertRoundTrips(ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4]))
}
func testBMPStringContiguousBytes() throws {
let string = ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4])
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) }
}
func testUTF8StringCanCreateAString() throws {
let string = "hello, world!"
let utf8String = ASN1.ASN1UTF8String(string)
let newString = String(utf8String)
XCTAssertEqual(newString, string)
}
func testPrintableStringCanCreateAString() throws {
let string = "hello, world"
let utf8String = try ASN1.ASN1PrintableString(string)
let newString = String(utf8String)
XCTAssertEqual(newString, string)
}
func testIA5StringCanCreateAString() throws {
let string = "hello, world"
let ia5String = try ASN1.ASN1IA5String(string)
let newString = String(ia5String)
XCTAssertEqual(newString, string)
}
func testPrintableStringRejectsCharacters() throws {
let allBytes = (UInt8(0)...UInt8.max)
let invalidBytes = (UInt8(0)...UInt8(255)).filter {
switch $0 {
case UInt8(ascii: "a")...UInt8(ascii: "z"),
UInt8(ascii: "A")...UInt8(ascii: "Z"),
UInt8(ascii: "0")...UInt8(ascii: "9"),
UInt8(ascii: "'"), UInt8(ascii: "("),
UInt8(ascii: ")"), UInt8(ascii: "+"),
UInt8(ascii: "-"), UInt8(ascii: "?"),
UInt8(ascii: ":"), UInt8(ascii: "/"),
UInt8(ascii: "="), UInt8(ascii: " "),
UInt8(ascii: ","), UInt8(ascii: "."):
return false
default:
return true
}
}
let validBytes = allBytes.filter { !invalidBytes.contains($0) }
for byte in invalidBytes {
XCTAssertThrowsError(try ASN1.ASN1PrintableString(contentBytes: [byte]))
XCTAssertThrowsError(try ASN1.ASN1PrintableString(String(UnicodeScalar(byte))))
XCTAssertThrowsError(try ASN1.ASN1PrintableString(asn1Encoded: [0x13, 1, byte]))
}
for byte in validBytes {
XCTAssertNoThrow(try ASN1.ASN1PrintableString(contentBytes: [byte]))
XCTAssertNoThrow(try ASN1.ASN1PrintableString(String(UnicodeScalar(byte))))
XCTAssertNoThrow(try ASN1.ASN1PrintableString(asn1Encoded: [0x13, 1, byte]))
}
}
func testIA5StringRejectsCharacters() throws {
let invalidBytes = (UInt8(128)...(UInt8.max))
let validBytes = (UInt8(0)..<UInt8(128))
for byte in invalidBytes {
XCTAssertThrowsError(try ASN1.ASN1IA5String(contentBytes: [byte]))
XCTAssertThrowsError(try ASN1.ASN1IA5String(String(UnicodeScalar(byte))))
XCTAssertThrowsError(try ASN1.ASN1IA5String(asn1Encoded: [0x16, 1, byte]))
}
for byte in validBytes {
XCTAssertNoThrow(try ASN1.ASN1IA5String(contentBytes: [byte]))
XCTAssertNoThrow(try ASN1.ASN1IA5String(String(UnicodeScalar(byte))))
XCTAssertNoThrow(try ASN1.ASN1IA5String(asn1Encoded: [0x16, 1, byte]))
}
}
}
+788
View File
@@ -0,0 +1,788 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import SwiftASN1
class ASN1Tests: XCTestCase {
func testSimpleASN1P256SPKI() throws {
// Given a static SPKI structure, verifies the parse.
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
let encodedExpectedKeyBytes = "BNmnTK3Ru2lH2R+e2nihRTNNXT55MQtfEnEW+GeqaDAYCbWJVbXfZcut1Eb+e2VtDXLNS4mQe1gE297L7vtXOx0="
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
let result = try ASN1.parse(decodedSPKI)
let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: result)
XCTAssertEqual(spki.algorithmIdentifier, .ecdsaP256)
spki.key.withUnsafeBytes { XCTAssertEqual(Array($0), expectedKeyBytes) }
// For SPKI we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(spki))
XCTAssertEqual(serializer.serializedBytes, decodedSPKI)
// The root node should contain all the bytes
XCTAssertEqual(result.encodedBytes, decodedSPKI[...])
}
func testSimpleASN1P384SPKI() throws {
let encodedSPKI = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEcBr0TNmgagf1ysckEA/3XLGx2amgzeHjDBZREqhCIVBrLhIiIR4zrJ8dqad/Y+zI2Hu8TIUbrzS/diFpFoE0YYKBTfYMCAUtaWuMb1oaBdFzWsLfYSSzF+ON1yeJCtro"
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
let encodedExpectedKeyBytes = "BHAa9EzZoGoH9crHJBAP91yxsdmpoM3h4wwWURKoQiFQay4SIiEeM6yfHamnf2PsyNh7vEyFG680v3YhaRaBNGGCgU32DAgFLWlrjG9aGgXRc1rC32EksxfjjdcniQra6A=="
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
let result = try ASN1.parse(decodedSPKI)
let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: result)
XCTAssertEqual(spki.algorithmIdentifier, .ecdsaP384)
spki.key.withUnsafeBytes { XCTAssertEqual(Array($0), expectedKeyBytes) }
// For SPKI we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(spki))
XCTAssertEqual(serializer.serializedBytes, decodedSPKI)
}
func testSimpleASN1P521SPKI() throws {
let encodedSPKI = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBTxMJZTRr9NcKmD7iTeX7ofcgz77JPTIDXOHFfS1tZHd9P0uAeK/ARwwDdsQpIKCvmtaO4O52oHqmczdrRwGtrHIBUTqaOw2Fqdiqt0fRQju9wH1Xi4h8u0h80MymUM0sbAQ70jHCeV0S0mGcJS8t3nfP+qLes30h297dPfV3SLsLg8M="
let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
let encodedExpectedKeyBytes = "BAFPEwllNGv01wqYPuJN5fuh9yDPvsk9MgNc4cV9LW1kd30/S4B4r8BHDAN2xCkgoK+a1o7g7nageqZzN2tHAa2scgFROpo7DYWp2Kq3R9FCO73AfVeLiHy7SHzQzKZQzSxsBDvSMcJ5XRLSYZwlLy3ed8/6ot6zfSHb3t099XdIuwuDww=="
let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!)
let result = try ASN1.parse(decodedSPKI)
let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: result)
XCTAssertEqual(spki.algorithmIdentifier, .ecdsaP521)
spki.key.withUnsafeBytes { XCTAssertEqual(Array($0), expectedKeyBytes) }
// For SPKI we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(spki))
XCTAssertEqual(serializer.serializedBytes, decodedSPKI)
}
func testASN1SEC1PrivateKeyP256() throws {
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 publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.SEC1PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP256)
pkey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For SEC1 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testASN1SEC1PrivateKeyP384() throws {
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 publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.SEC1PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP384)
pkey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For SEC1 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testASN1SEC1PrivateKeyP521() throws {
let encodedPrivateKey = "MIHcAgEBBEIBONszidL11f7D8LEbVGKG4A7768X16w35/m6OSPO7MGQcYhWHpgSV4NZ6AFKcksavZSCa59lYdAN+MA3sUjO7R/mgBwYFK4EEACOhgYkDgYYABAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!)
let encodedPrivateKeyBytes = "ATjbM4nS9dX+w/CxG1RihuAO++vF9esN+f5ujkjzuzBkHGIVh6YEleDWegBSnJLGr2UgmufZWHQDfjAN7FIzu0f5"
let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
let encodedPublicKeyBytes = "BAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ=="
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.SEC1PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP521)
pkey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For SEC1 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testASN1PKCS8PrivateKeyP256() throws {
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 publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.PKCS8PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP256)
XCTAssertNil(pkey.privateKey.algorithm) // OpenSSL nils this out for some reason
pkey.privateKey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.privateKey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For PKCS8 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testASN1PKCS8PrivateKeyP384() throws {
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 publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.PKCS8PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP384)
XCTAssertNil(pkey.privateKey.algorithm) // OpenSSL nils this out for some reason
pkey.privateKey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.privateKey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For PKCS8 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
func testASN1PKCS8PrivateKeyP521() throws {
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 privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!)
let encodedPublicKeyBytes = "BADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ=="
let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!)
let result = try ASN1.parse(decodedPrivateKey)
let pkey = try ASN1.PKCS8PrivateKey(asn1Encoded: result)
XCTAssertEqual(pkey.algorithm, .ecdsaP521)
XCTAssertNil(pkey.privateKey.algorithm) // OpenSSL nils this out for some reason
pkey.privateKey.privateKey.withUnsafeBytes { XCTAssertEqual(Array($0), privateKeyBytes) }
pkey.privateKey.publicKey!.withUnsafeBytes { XCTAssertEqual(Array($0), publicKeyBytes) }
// For PKCS8 we should be able to round-trip the serialization.
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
}
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 decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!)
for index in decodedSPKI.indices {
let expectSuccessfulParse = index == decodedSPKI.endIndex
do {
_ = try ASN1.parse(decodedSPKI[..<index])
if !expectSuccessfulParse {
XCTFail("Unexpected successful parse with: \(decodedSPKI[...])")
}
} catch let error as ASN1Error {
if expectSuccessfulParse {
XCTFail("Unexpected failure (error: \(error)) with \(decodedSPKI[...])")
}
}
}
}
func testASN1TypesRequireAppropriateTypeIdentifierToDecode() throws {
// This is an ASN.1 REAL, a type we don't support
let base64Node = "CQUDMUUtMQ=="
let decodedReal = Array(Data(base64Encoded: base64Node)!)
let parsed = try ASN1.parse(decodedReal)
XCTAssertThrowsError(try ASN1.ASN1ObjectIdentifier(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .unexpectedFieldType)
}
XCTAssertThrowsError(try ASN1.sequence(parsed, identifier: .sequence, { _ in })) { error in
XCTAssertEqual(error as? ASN1Error, .unexpectedFieldType)
}
XCTAssertThrowsError(try ASN1.ASN1OctetString(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .unexpectedFieldType)
}
XCTAssertThrowsError(try ASN1.ASN1BitString(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .unexpectedFieldType)
}
XCTAssertThrowsError(try Int(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .unexpectedFieldType)
}
}
func testMultipleRootNodesAreForbidden() throws {
// This is an ASN.1 REAL, a type we don't support, repeated
let base64Node = "CQUDMUUtMQkFAzFFLTE="
let decodedReal = Array(Data(base64Encoded: base64Node)!)
XCTAssertThrowsError(try ASN1.parse(decodedReal)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testTrailingBytesAreForbidden() throws {
// This is an ASN.1 INTEGER with trailing junk bytes
let base64Node = "AgEBAA=="
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
XCTAssertThrowsError(try ASN1.parse(decodedInteger)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testEmptyStringsDontDecode() throws {
XCTAssertThrowsError(try ASN1.parse([])) { error in
XCTAssertEqual(error as? ASN1Error, .truncatedASN1Field)
}
}
func testSupportMultibyteTags() throws {
// This is an ASN.1 object with a multibyte explicit tag, with the raw numerical value being 55.
let base64Node = "vzcDAgEB"
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
let result = try ASN1.parse(decodedInteger)
XCTAssertEqual(result.identifier, ASN1.ASN1Identifier(tagWithNumber: 55, tagClass: .contextSpecific, constructed: true))
}
func testSupportSmallestValidMultibyteTags() throws {
// This is an ASN.1 object with a multibyte explicit tag, with the raw numerical value being 31.
let base64Node = "vx8DAgEB"
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
let result = try ASN1.parse(decodedInteger)
XCTAssertEqual(result.identifier, ASN1.ASN1Identifier(tagWithNumber: 31, tagClass: .contextSpecific, constructed: true))
}
func testRejectExcessivelySmallMultibyteTags() throws {
// This is an ASN.1 object with a multibyte explicit tag but whose raw value is 30, which is required to be written in the short form.
let base64Node = "vx4DAgEB"
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
XCTAssertThrowsError(try ASN1.parse(decodedInteger)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testGracefullyTolerateExcessivelyLargeMultibyteTags() throws {
// This is an ASN.1 object with a multibyte explicit tag whose raw value is one larger than the max we tolerate, which is (1 << 63).
let base64Node = "v4GAgICAgICAgAADAgEB"
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
XCTAssertThrowsError(try ASN1.parse(decodedInteger)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testGracefullyTolerateLargeButRepresentableMultibyteTags() throws {
// This is an ASN.1 object with a multibyte explicit tag whose raw value is (1 << 63) - 1.
let base64Node = "v///////////fwMCAQE="
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
let result = try ASN1.parse(decodedInteger)
XCTAssertEqual(result.identifier, ASN1.ASN1Identifier(tagWithNumber: (1 << 63) - 1, tagClass: .contextSpecific, constructed: true))
}
func testRejectMultibyteTagWithLeadingZeroByte() throws {
// This is an ASN.1 object with a multibyte explicit tag whose raw value is 55 but padded with a leading byte of zeros.
let base64Node = "v4A3AwIBAQ=="
let decodedInteger = Array(Data(base64Encoded: base64Node)!)
XCTAssertThrowsError(try ASN1.parse(decodedInteger)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testSequenceMustConsumeAllNodes() throws {
// This is an ASN.1 SEQUENCE with two child nodes, both octet strings. We're going to consume only one.
let base64Sequence = "MAwEBEFCQ0QEBEVGR0g="
let decodedSequence = Array(Data(base64Encoded: base64Sequence)!)
let parsed = try ASN1.parse(decodedSequence)
do {
try ASN1.sequence(parsed, identifier: .sequence) { nodes in
// This is fine.
XCTAssertNoThrow(try ASN1.ASN1OctetString(asn1Encoded: &nodes))
}
} catch let error as ASN1Error {
XCTAssertEqual(error, .invalidASN1Object)
}
}
func testNodesErrorIfThereIsInsufficientData() throws {
struct Stub: ASN1Parseable {
init(asn1Encoded node: ASN1.ASN1Node) throws {
XCTFail("Must not be called")
}
}
// This is an ASN.1 SEQUENCE with two child nodes, both octet strings. We're going to consume both and then try
// to eat the (nonexistent) next node.
let base64Sequence = "MAwEBEFCQ0QEBEVGR0g="
let decodedSequence = Array(Data(base64Encoded: base64Sequence)!)
let parsed = try ASN1.parse(decodedSequence)
do {
try ASN1.sequence(parsed, identifier: .sequence) { nodes in
XCTAssertNoThrow(try ASN1.ASN1OctetString(asn1Encoded: &nodes))
XCTAssertNoThrow(try ASN1.ASN1OctetString(asn1Encoded: &nodes))
_ = try Stub(asn1Encoded: &nodes)
}
} catch let error as ASN1Error {
XCTAssertEqual(error, .invalidASN1Object)
}
}
func testRejectsIndefiniteLengthForm() throws {
// This the first octets of a constructed object of unknown tag type (private, number 7) whose length
// is indefinite. We reject this immediately, not even noticing that the rest of the data isn't here.
XCTAssertThrowsError(try ASN1.parse([0xe7, 0x80])) { error in
XCTAssertEqual(error as? ASN1Error, .unsupportedFieldLength)
}
}
func testRejectsUnterminatedASN1OIDSubidentifiers() throws {
// This data contains the ASN.1 OID 2.6.7, with the last subidentifier having been mangled to set the top bit.
// This makes it look like we're expecting more data in the OID, and we should flag it as truncated.
let badBase64 = "BgJWhw=="
let badNode = Array(Data(base64Encoded: badBase64)!)
let parsed = try ASN1.parse(badNode)
XCTAssertThrowsError(try ASN1.ASN1ObjectIdentifier(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testRejectsMassiveIntegers() throws {
// This is an ASN.1 integer containing UInt64.max * 2. This is too big for us to store, and we reject it.
// This test may need to be rewritten if we either support arbitrary integers or move to platforms where
// UInt is larger than 64 bits (seems unlikely).
let badBase64 = "AgkB//////////4="
let badNode = Array(Data(base64Encoded: badBase64)!)
let parsed = try ASN1.parse(badNode)
XCTAssertThrowsError(try Int(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testStraightforwardPEMParsing() throws {
let simplePEM = """
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA==
-----END EC PRIVATE KEY-----
"""
let document = try ASN1.PEMDocument(pemString: simplePEM)
XCTAssertEqual(document.type, "EC PRIVATE KEY")
XCTAssertEqual(document.derBytes.count, 121)
let parsed = try ASN1.parse(Array(document.derBytes))
let pkey = try ASN1.SEC1PrivateKey(asn1Encoded: parsed)
let reserialized = document.pemString
XCTAssertEqual(reserialized, simplePEM)
var serializer = ASN1.Serializer()
XCTAssertNoThrow(try serializer.serialize(pkey))
let reserialized2 = ASN1.PEMDocument(type: "EC PRIVATE KEY", derBytes: Data(serializer.serializedBytes))
XCTAssertEqual(reserialized2.pemString, simplePEM)
}
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-----
"""
for index in simplePEM.indices.dropLast() {
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: String(simplePEM[..<index]))) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
XCTAssertNoThrow(try ASN1.PEMDocument(pemString: simplePEM))
}
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-----
"""
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: simplePEM)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
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-----
"""
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: simplePEM)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
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-----
"""
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: simplePEM)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
func testEmptyPEMDocument() throws {
let simplePEM = """
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
"""
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: simplePEM)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
func testInvalidBase64IsForbidden() throws {
let simplePEM = """
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49
AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG
O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA==
-----END EC PRIVATE KEY-----
"""
XCTAssertThrowsError(try ASN1.PEMDocument(pemString: simplePEM)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidPEMDocument)
}
}
func testRejectSingleComponentOIDs() throws {
// This is an encoded OID that has only one subcomponent, 0.
let singleComponentOID: [UInt8] = [0x06, 0x01, 0x00]
let parsed = try ASN1.parse(singleComponentOID)
XCTAssertThrowsError(try ASN1.ASN1ObjectIdentifier(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidObjectIdentifier)
}
}
func testRejectZeroComponentOIDs() throws {
// This is an encoded OID that has no subcomponents..
let zeroComponentOID: [UInt8] = [0x06, 0x00]
let parsed = try ASN1.parse(zeroComponentOID)
XCTAssertThrowsError(try ASN1.ASN1ObjectIdentifier(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidObjectIdentifier)
}
}
func testAllowNonOctetNumberOfBitsInBitstring() throws {
for i in 1..<8 {
let lastByte = (UInt8.max << i)
let weirdBitString = [0x03, 0x02, UInt8(i), lastByte]
let parsed = try ASN1.parse(weirdBitString)
let string = try ASN1.ASN1BitString(asn1Encoded: parsed)
XCTAssertEqual(string.paddingBits, i)
XCTAssertEqual(string.bytes, [lastByte])
}
}
func testBitstringWithPaddingBitsSetTo1() throws {
for i in 1..<8 {
let weirdBitString = [0x03, 0x02, UInt8(i), 0xFF]
let parsed = try ASN1.parse(weirdBitString)
XCTAssertThrowsError(try ASN1.ASN1BitString(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
}
func testBitstringWithNoContent() throws {
// We don't allow bitstrings with no content.
let weirdBitString: [UInt8] = [0x03, 0x00]
let parsed = try ASN1.parse(weirdBitString)
XCTAssertThrowsError(try ASN1.ASN1BitString(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testEmptyBitstring() throws {
// Empty bitstrings must have their leading byte set to 0.
var bitString: [UInt8] = [0x03, 0x01, 0x00]
let parsed = try ASN1.parse(bitString)
let bs = try ASN1.ASN1BitString(asn1Encoded: parsed)
XCTAssertEqual(bs.bytes, [])
for i in 1..<8 {
bitString[2] = UInt8(i)
let parsed = try ASN1.parse(bitString)
XCTAssertThrowsError(try ASN1.ASN1BitString(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
}
func testIntegerZeroRequiresAZeroByte() throws {
// Integer zero requires a leading zero byte.
let weirdZero: [UInt8] = [0x02, 0x00]
let parsed = try ASN1.parse(weirdZero)
XCTAssertThrowsError(try Int(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1IntegerEncoding)
}
}
func testLeadingZero() throws {
// We should reject integers that have unnecessary leading zero bytes.
let overlongOne: [UInt8] = [0x02, 0x02, 0x00, 0x01]
let parsed = try ASN1.parse(overlongOne)
XCTAssertThrowsError(try Int(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1IntegerEncoding)
}
}
func testLeadingOnes() throws {
// We should reject integers that have unnecessary leading one bytes. This is supposed to be a -127, but we encode it as though it
// were an Int16.
let overlongOneTwoSeven: [UInt8] = [0x02, 0x02, 0xFF, 0x81]
let parsed = try ASN1.parse(overlongOneTwoSeven)
XCTAssertThrowsError(try Int(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1IntegerEncoding)
}
}
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
]
let parsed = try ASN1.parse(weirdASN1)
try ASN1.sequence(parsed, identifier: .sequence) { nodes in
XCTAssertThrowsError(try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific, { _ in })) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
}
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 decodedSPKI = Array(Data(base64Encoded: rsaSPKI)!)
var serializer = ASN1.Serializer()
serializer.appendPrimitiveNode(identifier: .null) { _ in }
let null = serializer.serializedBytes
let parsed = try ASN1.parse(decodedSPKI)
let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: parsed)
XCTAssertEqual(spki.algorithmIdentifier.algorithm, [1, 2, 840, 113549, 1, 1, 1]) // RSA encryption
serializer = ASN1.Serializer()
try serializer.serialize(spki.algorithmIdentifier.parameters!)
XCTAssertEqual(serializer.serializedBytes, null)
let expectedKey: ArraySlice<UInt8> = [
48, 129, 137, 2, 129, 129, 0, 208, 17, 195, 252, 170, 12, 42, 228, 152,
70, 130, 93, 102, 40, 199, 142, 89, 182, 244, 88, 82, 164, 36, 168, 248,
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,
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
]
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 decodedSPKI = Array(Data(base64Encoded: b64SPKI)!)
let parsed = try ASN1.parse(decodedSPKI)
let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: parsed)
XCTAssertEqual(spki.algorithmIdentifier.algorithm, .AlgorithmIdentifier.idEcPublicKey)
XCTAssertEqual(try ASN1.ASN1ObjectIdentifier(asn1Any: spki.algorithmIdentifier.parameters!), [1, 3, 132, 0, 10])
let expectedKey: ArraySlice<UInt8> = [
4, 204, 221, 61, 73, 182, 254, 154, 19, 8, 149, 70, 206, 118, 130, 40,
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
]
XCTAssertEqual(spki.key.bytes, expectedKey)
}
func testSEC1PrivateKeyWithUnknownVersion() throws {
// This is the beginning of a SEC1 private key with hypothetical version number 5. We should reject it
let weirdSEC1: [UInt8] = [0x30, 0x03, 0x02, 0x01, 0x05]
let parsed = try ASN1.parse(weirdSEC1)
XCTAssertThrowsError(try ASN1.SEC1PrivateKey(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
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 decodedSEC1 = Array(Data(base64Encoded: b64SEC1)!)
let parsed = try ASN1.parse(decodedSEC1)
XCTAssertThrowsError(try ASN1.SEC1PrivateKey(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
func testPKCS8KeyWithNonMatchingKeyOIDS() throws {
// This is a stubbed PKCS8 key with mismatched OIDs in the inner and outer payload. We have to serialize it out, sadly.
var serializer = ASN1.Serializer()
try serializer.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(0)
try coder.serialize(ASN1.RFC5480AlgorithmIdentifier.ecdsaP256)
var subCoder = ASN1.Serializer()
try subCoder.serialize(ASN1.SEC1PrivateKey(privateKey: [], algorithm: .ecdsaP384, publicKey: [])) // We won't notice these are empty either, but we will notice the algo mismatch.
let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...])
try coder.serialize(serializedKey)
}
let parsed = try ASN1.parse(serializer.serializedBytes)
XCTAssertThrowsError(try ASN1.PKCS8PrivateKey(asn1Encoded: parsed)) { error in
XCTAssertEqual(error as? ASN1Error, .invalidASN1Object)
}
}
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 decodedSPKI = Array(Data(base64Encoded: rsaSPKI)!)
let parsed = try ASN1.parse(decodedSPKI)
XCTAssertEqual(parsed.encodedBytes, decodedSPKI[...])
guard case .constructed(let firstLayerChildren) = parsed.content else {
XCTFail("Unexpected node")
return
}
var iterator = firstLayerChildren.makeIterator()
guard let algorithmId = iterator.next(), let key = iterator.next() else {
XCTFail("Invalid number of children")
return
}
XCTAssertNil(iterator.next())
// Initial offset of the algorithm ID is 3 (3 bytes of encoding for the parent sequence),
// the sequence itself is 13 bytes long, and there are 2 bytes of length and tag. End offset
// is therefore 3 + 13 + 2 == 18.
XCTAssertEqual(algorithmId.encodedBytes, decodedSPKI[3..<18])
// Initial offset of the key immediately follows the algorithm ID, so it's 18. It contains the bytes
// up to the end.
XCTAssertEqual(key.encodedBytes, decodedSPKI[18...])
guard case .constructed(let algorithmIDChildren) = algorithmId.content else {
XCTFail("Invalid content for algorithm ID node")
return
}
iterator = algorithmIDChildren.makeIterator()
guard let oid = iterator.next(), let null = iterator.next() else {
XCTFail("Invalid algorithm ID content")
return
}
// The oid begins at offset 5: 3 bytes for the outer sequence tag/length, 2 bytes for the inner sequence tag/length.
// The oid itself has a 2 byte tag/length combo and a 9 byte length, leaving its end index as 5 + 2 + 9 == 16
XCTAssertEqual(oid.encodedBytes, decodedSPKI[5..<16])
// The null is 2 bytes long.
XCTAssertEqual(null.encodedBytes, decodedSPKI[16..<18])
}
func testOptionalImplicitlyTaggedWithCustomTag() throws {
var serializer = ASN1.Serializer()
try serializer.appendConstructedNode(identifier: .sequence) { serializer in
try serializer.serializeOptionalImplicitlyTagged(1, withIdentifier: ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: false))
}
let bytes = serializer.serializedBytes
XCTAssertEqual(bytes, [0x30, 0x03, 0x81, 0x1, 0x1])
let parseResult = try ASN1.parse(bytes)
let int: Int? = try ASN1.sequence(parseResult, identifier: .sequence) { nodes in
try ASN1.optionalImplicitlyTagged(&nodes, tag: ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: false))
}
XCTAssertEqual(int, 1)
}
}
@@ -0,0 +1,180 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import SwiftASN1
final class GeneralizedTimeTests: XCTestCase {
private func assertRoundTrips<ASN1Object: ASN1Parseable & ASN1Serializable & Equatable>(_ value: ASN1Object) throws {
var serializer = ASN1.Serializer()
try serializer.serialize(value)
let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes)
XCTAssertEqual(parsed, value)
}
func testSimpleGeneralizedTimeTestVectors() throws {
// This is a small set of generalized time test vectors derived from the ASN.1 docs.
// We store the byte payload here as a string.
let vectors: [(String, ASN1.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
// Invalid representations
("19920520240000Z", nil), // midnight may not be 2400000
("19920622123421.0Z", nil), // spurious trailing zeros
("19920722132100.30Z", nil), // spurious trailing zeros
("19851106210627,3Z", nil), // comma as decimal separator
("1985110621.14159Z", nil), // missing minutes and seconds
("198511062106.14159Z", nil), // missing seconds
("19851106210627.3", nil), // missing trailing Z
("19851106210627.3-0500", nil), // explicit time zone
("20211300000000Z", nil), // there is no 13th month
("20210000000000Z", nil), // there is no zeroth month
("20210100000000Z", nil), // there is no zeroth day
("20210101000062Z", nil), // 62nd second is not allowed
("20210101236000Z", nil), // 60th minute is not allowed
("20210132000000Z", nil), // only 31 days in January
("20210229000000Z", nil), // only 28 days in February 2021
("20200230000000Z", nil), // only 29 days in February 2020
("21000229000000Z", nil), // only 28 days in February 2100
("20000230000000Z", nil), // only 29 days in February 2000
("20210332000000Z", nil), // only 31 days in March
("20210431000000Z", nil), // only 30 days in April
("20210532000000Z", nil), // only 31 days in May
("20210631000000Z", nil), // only 30 days in June
("20210732000000Z", nil), // only 31 days in July
("20210832000000Z", nil), // only 31 days in August
("20210931000000Z", nil), // only 30 days in September
("20211032000000Z", nil), // only 31 days in October
("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>()
serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime)
serialized.append(UInt8(stringRepresentation.utf8.count))
serialized.append(contentsOf: stringRepresentation.utf8)
let result = try? ASN1.GeneralizedTime(asn1Encoded: serialized)
XCTAssertEqual(result, expectedResult)
if let expected = expectedResult {
try self.assertRoundTrips(expected)
}
}
}
func testCreatingOutOfBoundsValuesViaInitFails() throws {
func mustFail(_ code: @autoclosure () throws -> ASN1.GeneralizedTime) {
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
}
func testTruncatedRepresentationsRejected() throws {
func mustNotDeserialize(_ stringRepresentation: Substring) {
var serialized = Array<UInt8>()
serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime)
serialized.append(UInt8(stringRepresentation.utf8.count))
serialized.append(contentsOf: stringRepresentation.utf8)
XCTAssertThrowsError(try ASN1.GeneralizedTime(asn1Encoded: serialized))
}
func deserializes(_ stringRepresentation: Substring) {
var serialized = Array<UInt8>()
serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime)
serialized.append(UInt8(stringRepresentation.utf8.count))
serialized.append(contentsOf: stringRepresentation.utf8)
XCTAssertNoThrow(try ASN1.GeneralizedTime(asn1Encoded: serialized))
}
// Anything that doesn't end up in a Z must fail to deserialize.
let string = Substring("19851106210627.14159Z")
for distance in 0..<string.count {
let sliced = string.prefix(distance)
mustNotDeserialize(sliced)
}
deserializes(string)
// Adding some excess data should fail too.
for junkByteCount in 1...string.count {
let junked = string + string.prefix(junkByteCount)
mustNotDeserialize(junked)
}
}
func testRequiresAppropriateTag() throws {
let rawValue = "19920521000000Z".utf8
var invalidBytes = Array<UInt8>()
invalidBytes.writeIdentifier(ASN1.ASN1Identifier.integer) // generalizedTime isn't an integer
invalidBytes.append(UInt8(rawValue.count))
invalidBytes.append(contentsOf: rawValue)
XCTAssertThrowsError(try ASN1.GeneralizedTime(asn1Encoded: invalidBytes))
}
}