diff --git a/.editorconfig b/.editorconfig
index 0eb3fa03..d351c8aa 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -312,8 +312,6 @@ dotnet_diagnostic.CA2201.severity = none
# CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2208.severity = none
-[**/YubiPosh/**/*.cs]
-
# CA1014: Mark assemblies with CLSCompliantAttribute
dotnet_diagnostic.CA1014.severity = none
diff --git a/.github/workflows/check-code-formatting.yml b/.github/workflows/check-code-formatting.yml
new file mode 100644
index 00000000..7828ba65
--- /dev/null
+++ b/.github/workflows/check-code-formatting.yml
@@ -0,0 +1,39 @@
+# Copyright 2021 Yubico AB
+#
+# 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.
+
+name: Check code formatting
+
+on:
+ pull_request:
+ branches:
+ - main
+ - 'develop**'
+ - 'release/**'
+
+jobs:
+ check-code-formatting:
+ runs-on: windows-2019
+
+ steps:
+ # Checkout the local repository
+ - uses: actions/checkout@v4
+
+ - name: Add local NuGet repository
+ run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json"
+
+ - name: Build Yubico.NET.SDK.sln
+ run: dotnet build --configuration Release --nologo --verbosity normal Yubico.NET.SDK.sln
+
+ - name: Check for correct formatting
+ run: dotnet format --verify-no-changes --no-restore -v d
\ No newline at end of file
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index 2731f404..a0bff54d 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -42,15 +42,15 @@ permissions:
jobs:
analyze:
name: Analyze
- runs-on: windows-2019
+ runs-on: windows-2022
steps:
- name: Checkout repository
- uses: actions/checkout@v2
+ uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@v2
+ uses: github/codeql-action/init@v3
with:
languages: csharp
@@ -62,4 +62,4 @@ jobs:
run: dotnet build --configuration Release --nologo --verbosity normal Yubico.NET.SDK.sln
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v2
+ uses: github/codeql-action/analyze@v3
diff --git a/.github/workflows/cross-build-nativeshims.yml b/.github/workflows/cross-build-nativeshims.yml
index 26b9a4c8..b261b88c 100644
--- a/.github/workflows/cross-build-nativeshims.yml
+++ b/.github/workflows/cross-build-nativeshims.yml
@@ -24,7 +24,7 @@ on:
version:
description: 'Version'
required: false
- default: "0.0.0-prerelease.YYYMMDD.B"
+ default: "0.0.0-prerelease.YYYYMMDD.B"
type: string
jobs:
@@ -32,65 +32,72 @@ jobs:
name: Build Windows
runs-on: windows-2019
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
- run: |
+ echo 'Running build script: Windows'
cd Yubico.NativeShims
- ./build-windows.cmd
- - uses: actions/upload-artifact@v3
+ & ./build-windows.ps1
+ - uses: actions/upload-artifact@v4
with:
name: win-x64
path: Yubico.NativeShims/win-x64/**
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: win-x86
path: Yubico.NativeShims/win-x86/**
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: win-arm64
path: Yubico.NativeShims/win-arm64/**
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: nuspec
path: Yubico.NativeShims/*.nuspec
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: msbuild
path: Yubico.NativeShims/msbuild/*
- build-ubuntu:
- name: Build Ubuntu
- runs-on: ubuntu-latest
+ build-linux-amd64:
+ name: Build Linux (amd64)
+ runs-on: ubuntu-20.04
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
- run: |
+ echo 'Running build script: Linux (amd64)'
cd Yubico.NativeShims
- sh ./build-ubuntu.sh
- - uses: actions/upload-artifact@v3
+ sh ./build-linux-amd64.sh
+ - uses: actions/upload-artifact@v4
with:
- name: ubuntu-x64
- path: Yubico.NativeShims/ubuntu-x64/**
- - uses: actions/upload-artifact@v3
- with:
- name: ubuntu-x86
- path: Yubico.NativeShims/ubuntu-x86/**
- - uses: actions/upload-artifact@v3
+ name: linux-x64
+ path: Yubico.NativeShims/linux-x64/*.so
+ build-linux-arm64:
+ name: Build Linux (arm64)
+ runs-on: ubuntu-20.04
+ steps:
+ - uses: actions/checkout@v4
+ - run: |
+ echo 'Running build script: Linux (arm64)'
+ cd Yubico.NativeShims
+ sh ./build-linux-arm64.sh
+ - uses: actions/upload-artifact@v4
with:
- name: ubuntu-arm64
- path: Yubico.NativeShims/ubuntu-arm64/**
-
+ name: linux-arm64
+ path: Yubico.NativeShims/linux-arm64/*.so
build-macos:
name: Build macOS
runs-on: macos-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
- run: |
+ echo 'Running build script: macOS'
cd Yubico.NativeShims
sh ./build-macOS.sh
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: osx-x64
path: Yubico.NativeShims/osx-x64/**
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: osx-arm64
path: Yubico.NativeShims/osx-arm64/**
@@ -98,9 +105,9 @@ jobs:
pack:
name: Package artifacts
runs-on: windows-2019
- needs: [build-windows, build-ubuntu, build-macos]
+ needs: [build-windows, build-linux-amd64, build-linux-arm64, build-macos]
steps:
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
- run: |
mv nuspec/*.nuspec .
del nuspec
@@ -113,7 +120,7 @@ jobs:
$nuspec.Save("Yubico.NativeShims.nuspec")
cat Yubico.NativeShims.nuspec
- run: nuget pack Yubico.NativeShims.nuspec
- - uses: actions/upload-artifact@v3
+ - uses: actions/upload-artifact@v4
with:
name: Yubico.NativeShims.nupkg
path: Yubico.NativeShims.*.nupkg
@@ -123,9 +130,11 @@ jobs:
runs-on: windows-2019
needs: pack
environment: Internal NuGet feed
+ permissions:
+ packages: write
if: ${{ github.event.inputs.push-to-dev == 'true' }}
steps:
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
with:
name: Yubico.NativeShims.nupkg
- run: |
diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml
index 8c589c22..6cd4ea1a 100644
--- a/.github/workflows/pull-requests.yml
+++ b/.github/workflows/pull-requests.yml
@@ -33,7 +33,7 @@ jobs:
# Even though we build for multiple platforms, we only need to run
# on a single host operating system. This is because we utilize cross-
# build functionality of the dotnet build system.
- runs-on: windows-2019
+ runs-on: windows-latest
# Build both Debug and ReleaseWithDocs configurations. Most people are probably building 'Debug' the most often. We
# should be sure that Release also builds, and that our documentation also compiles successfully.
strategy:
@@ -42,22 +42,24 @@ jobs:
steps:
# Checkout the local repository
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ global-json-file: global.json
+
+ - name: run dotnet version
+ run: dotnet --version
- name: Add local NuGet repository
run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json"
# Build the project
- # The default GitHub runners seem to have N and N-1 versions of .NET Framework installed. In practice, they seem
- # to have even more installed than that, but at a minimum N and N-1 seem like safe assumptions. We can therefore
- # save some time and use the pre-installed version rather than downloading a fresh copy.
-
- name: Build Yubico.NET.SDK.sln
run: dotnet build --configuration ${{matrix.configuration}} --nologo --verbosity normal Yubico.NET.SDK.sln
# Save the built NuGet packages, just in case we need to inspect the build output.
- name: Save build artifacts
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v4
with:
name: Nuget Packages ${{matrix.configuration}}
path: |
@@ -66,7 +68,7 @@ jobs:
Yubico.YubiKey/src/bin/${{matrix.configuration}}/*.nupkg
- name: Save build artifacts
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v4
with:
name: Assemblies ${{matrix.configuration}}
path: |
diff --git a/.github/workflows/test-and-cover.yml b/.github/workflows/test-and-cover.yml
new file mode 100644
index 00000000..bef7e328
--- /dev/null
+++ b/.github/workflows/test-and-cover.yml
@@ -0,0 +1,97 @@
+# Copyright 2021 Yubico AB
+#
+# 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.
+
+name: Tests and code coverage
+
+on:
+ pull_request:
+ branches:
+ - main
+ - 'develop**'
+ - 'release/**'
+
+jobs:
+ test:
+ runs-on: windows-2019
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Add local NuGet repository
+ run: dotnet nuget add source --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/Yubico/index.json"
+
+ - name: Test Yubico.YubiKey
+ run: dotnet test --configuration Release --nologo --logger trx --collect:"XPlat Code Coverage" Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj --settings coverlet.runsettings.xml
+
+ - name: Test Yubico.Core
+ run: dotnet test --configuration Release --nologo --logger trx --collect:"XPlat Code Coverage" Yubico.Core/tests/Yubico.Core.UnitTests.csproj --settings coverlet.runsettings.xml
+
+ - name: Upload Test Result Files
+ uses: actions/upload-artifact@v4
+ with:
+ name: TestResults
+ if-no-files-found: error
+ path: '**/TestResults/*'
+
+ coverage:
+ permissions:
+ contents: read
+ issues: read
+ checks: write
+ pull-requests: write
+ runs-on: ubuntu-latest
+ needs: test
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: TestResults
+ path: ${{ github.workspace }}
+
+ - name: Combine Coverage Reports # This is because one report is produced per project, and we want one result for all of them.
+ uses: danielpalme/ReportGenerator-GitHub-Action@5.2.4
+ with:
+ reports: "**/*.cobertura.xml" # REQUIRED # The coverage reports that should be parsed (separated by semicolon). Globbing is supported.
+ targetdir: "${{ github.workspace }}" # REQUIRED # The directory where the generated report should be saved.
+ reporttypes: "Cobertura" # The output formats and scope (separated by semicolon) Values: Badges, Clover, Cobertura, CsvSummary, Html, Html_Dark, Html_Light, Html_BlueRed, HtmlChart, HtmlInline, HtmlInline_AzurePipelines, HtmlInline_AzurePipelines_Dark, HtmlInline_AzurePipelines_Light, HtmlSummary, JsonSummary, Latex, LatexSummary, lcov, MarkdownSummary, MarkdownSummaryGithub, MarkdownDeltaSummary, MHtml, PngChart, SonarQube, TeamCitySummary, TextSummary, TextDeltaSummary, Xml, XmlSummary
+ verbosity: "Info" # The verbosity level of the log messages. Values: Verbose, Info, Warning, Error, Off
+ title: "Code Coverage" # Optional title.
+ tag: "${{ github.run_number }}_${{ github.run_id }}" # Optional tag or build version.
+ customSettings: "" # Optional custom settings (separated by semicolon). See: https://github.com/danielpalme/ReportGenerator/wiki/Settings.
+ toolpath: "reportgeneratortool" # Default directory for installing the dotnet tool.
+
+ - name: Publish Code Coverage Report
+ uses: irongut/CodeCoverageSummary@v1.3.0
+ with:
+ filename: "Cobertura.xml"
+ badge: true
+ fail_below_min: true
+ format: markdown
+ hide_branch_rate: false
+ hide_complexity: false
+ indicators: true
+ output: both
+ thresholds: "50 70"
+
+ - name: Add Coverage PR Comment
+ uses: marocchino/sticky-pull-request-comment@v2.9.0
+ if: github.event_name == 'pull_request'
+ with:
+ recreate: true
+ path: code-coverage-results.md
+
+ - name: Publish Test Results
+ uses: EnricoMi/publish-unit-test-result-action@v2.16.1
+ if: always()
+ with:
+ trx_files: "${{ github.workspace }}/**/*.trx"
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 52a158bc..e6cbea51 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,7 +9,7 @@ Yubico.NativeShims/build*/
Yubico.NativeShims/Yubico.NativeShims.h
Yubico.NativeShims/win-*
Yubico.NativeShims/osx-*
-Yubico.NativeShims/ubuntu-*
+Yubico.NativeShims/linux-*
# NuGet config
# We treat NuGet configs as per-user settings
@@ -551,3 +551,7 @@ cython_debug/
# XML Documentation Output
/Yubico.Core/src/Yubico.Core.xml
/Yubico.YubiKey/src/Yubico.YubiKey.xml
+
+# Coverage / Test Results
+coveragereport/
+TestResults/
\ No newline at end of file
diff --git a/README.md b/README.md
index 2f16ae24..29a43a64 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,9 @@ 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. -->
+> Dev: ![tests-dev](https://github.com/Yubico/Yubico.NET.SDK-private/actions/workflows/test-and-cover.yml/badge.svg?branch=yesdk-1315-skip-unsuitable-tests)
+> Main: ![tests-main](https://github.com/Yubico/Yubico.NET.SDK-private/actions/workflows/test-and-cover.yml/badge.svg?branch=main)
+
# .NET YubiKey SDK
This is a cross-platform, all encompassing SDK for the YubiKey aimed at large to mid-sized enterprise
diff --git a/Yubico.Core/src/AssemblyInfo.cs b/Yubico.Core/src/AssemblyInfo.cs
index b1da9f09..a8b816ed 100644
--- a/Yubico.Core/src/AssemblyInfo.cs
+++ b/Yubico.Core/src/AssemblyInfo.cs
@@ -14,4 +14,4 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
diff --git a/Yubico.Core/src/Yubico.Core.csproj b/Yubico.Core/src/Yubico.Core.csproj
index b4924a02..55f20805 100644
--- a/Yubico.Core/src/Yubico.Core.csproj
+++ b/Yubico.Core/src/Yubico.Core.csproj
@@ -111,6 +111,7 @@ limitations under the License. -->
+
diff --git a/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs b/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs
index d79dffa3..d3aa8bd2 100644
--- a/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs
+++ b/Yubico.Core/src/Yubico/Core/Buffers/Base16.cs
@@ -58,7 +58,7 @@ public class Base16 : ITextEncoding
///
public void Encode(ReadOnlySpan data, Span encoded)
{
- if (data.Length > (encoded.Length * 2))
+ if (data.Length > encoded.Length * 2)
{
throw new ArgumentException(
nameof(encoded),
diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs b/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs
index c8f1f16b..53cd3601 100644
--- a/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs
+++ b/Yubico.Core/src/Yubico/Core/Cryptography/AesGcmPrimitivesOpenSsl.cs
@@ -38,8 +38,8 @@ public void EncryptAndAuthenticate(
Span tag,
ReadOnlySpan associatedData)
{
- if ((nonce.Length != NonceLength) || (ciphertext.Length != plaintext.Length)
- || (tag.Length != AuthTagLength))
+ if (nonce.Length != NonceLength || ciphertext.Length != plaintext.Length
+ || tag.Length != AuthTagLength)
{
throw new ArgumentException(ExceptionMessages.InvalidAesGcmInput);
}
@@ -102,7 +102,7 @@ public void EncryptAndAuthenticate(
}
///
- public bool DecryptAndVerify (
+ public bool DecryptAndVerify(
ReadOnlySpan keyData,
ReadOnlySpan nonce,
ReadOnlySpan ciphertext,
@@ -110,8 +110,8 @@ public bool DecryptAndVerify (
Span plaintext,
ReadOnlySpan associatedData)
{
- if ((nonce.Length != NonceLength) || (plaintext.Length != ciphertext.Length)
- || (tag.Length != AuthTagLength))
+ if (nonce.Length != NonceLength || plaintext.Length != ciphertext.Length
+ || tag.Length != AuthTagLength)
{
throw new ArgumentException(ExceptionMessages.InvalidAesGcmInput);
}
diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs b/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs
index 436866b7..1403b5f2 100644
--- a/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs
+++ b/Yubico.Core/src/Yubico/Core/Cryptography/EcParametersSslExtensions.cs
@@ -80,7 +80,7 @@ _ when curve.HasSameOid(ECCurve.NamedCurves.nistP521) => 716,
///
/// This function only supports the NIST P256, P384, and P512 curves as of version 1.5.0.
///
- public static int BitLength (this ECCurve curve) =>
+ public static int BitLength(this ECCurve curve) =>
curve switch
{
_ when curve.HasSameOid(ECCurve.NamedCurves.nistP256) => NistP256BitLength,
diff --git a/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs b/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs
index 3d5ae879..b4aaa976 100644
--- a/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs
+++ b/Yubico.Core/src/Yubico/Core/Cryptography/IAesGcmPrimitives.cs
@@ -138,7 +138,7 @@ public void EncryptAndAuthenticate(
/// One of the arguments was not valid (e.g. tag is not exactly 16
/// bytes).
///
- public bool DecryptAndVerify (
+ public bool DecryptAndVerify(
ReadOnlySpan keyData,
ReadOnlySpan nonce,
ReadOnlySpan ciphertext,
diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs
index ffd7ad94..9f117f2e 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/HidCodeTranslator.cs
@@ -40,18 +40,17 @@ private HidCodeTranslator(
#endregion
#region Private fields
- private static readonly Dictionary _lookup
- = new Dictionary
- {
- [KeyboardLayout.en_US] = GetEN_US(),
- [KeyboardLayout.en_UK] = GetEN_UK(),
- [KeyboardLayout.de_DE] = GetDE_DE(),
- [KeyboardLayout.fr_FR] = GetFR_FR(),
- [KeyboardLayout.it_IT] = GetIT_IT(),
- [KeyboardLayout.es_US] = GetES_US(),
- [KeyboardLayout.sv_SE] = GetSV_SE(),
- [KeyboardLayout.ModHex] = GetModHex()
- };
+ private static readonly Dictionary _lookup = new Dictionary
+ {
+ [KeyboardLayout.en_US] = GetEN_US(),
+ [KeyboardLayout.en_UK] = GetEN_UK(),
+ [KeyboardLayout.de_DE] = GetDE_DE(),
+ [KeyboardLayout.fr_FR] = GetFR_FR(),
+ [KeyboardLayout.it_IT] = GetIT_IT(),
+ [KeyboardLayout.es_US] = GetES_US(),
+ [KeyboardLayout.sv_SE] = GetSV_SE(),
+ [KeyboardLayout.ModHex] = GetModHex()
+ };
private readonly Dictionary _byChar;
private readonly Dictionary _byCode;
#endregion
diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs
index 998ebd2b..9d53ebd2 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/IOKitHelpers.cs
@@ -51,9 +51,9 @@ public static int GetIntPropertyValue(IntPtr device, string propertyName)
// We want to rely on Nullable's null checking and subsequent exception.
// Rather than duplicate the messaging and exception ourselves, let's just
// use theirs.
- #pragma warning disable CS8629
+#pragma warning disable CS8629
return propertyValue.Value;
- #pragma warning restore CS8629
+#pragma warning restore CS8629
}
///
diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs
index 58e5629f..5ddbe2d9 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDevice.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Collections.Generic;
+using System.Runtime.InteropServices;
using Yubico.Core.Logging;
using Yubico.PlatformInterop;
@@ -210,7 +210,7 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL
// If the tag is 4, the value is the USAGE PAGE. If we already
// have a USAGE PAGE, ignore this one.
- if ((tag == UsagePageTag) && (!usagePageFound))
+ if (tag == UsagePageTag && !usagePageFound)
{
usagePageValue = value;
usagePageFound = true;
@@ -218,7 +218,7 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL
// If the tag is 8, the value is the USAGE. Go ahead and set the
// Usage property in this object. If we already have a USAGE,
// ignore this one.
- else if ((tag == UsageTag) && (!usageFound))
+ else if (tag == UsageTag && !usageFound)
{
Usage = (short)value;
usageFound = true;
@@ -234,11 +234,11 @@ private void ParseUsageProperties(byte[] descriptor, int offset, int descriptorL
// If it is not a valid combo, don't set the UsagePage.
// We set the Usage even though it might be one we don't support,
// because if the UsagePage is Unknown, the Usage won't matter.
- if ((usagePageValue == UsagePageGeneric) && (Usage == UsageKeyboard))
+ if (usagePageValue == UsagePageGeneric && Usage == UsageKeyboard)
{
UsagePage = HidUsagePage.Keyboard;
}
- else if ((usagePageValue == UsagePageFido) && (Usage == UsageU2FDevice))
+ else if (usagePageValue == UsagePageFido && Usage == UsageU2FDevice)
{
UsagePage = HidUsagePage.Fido;
}
@@ -296,7 +296,7 @@ private static int ReadValue(byte[] descriptor, int offset, int descriptorLength
int newOffset = offset + length;
- if ((length <= 4) && (length + offset <= descriptorLength))
+ if (length <= 4 && length + offset <= descriptorLength)
{
for (int index = 0; index < length; index++)
{
diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs
index 63157b50..1d725e1c 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidDeviceListener.cs
@@ -52,7 +52,7 @@ public LinuxHidDeviceListener()
{
_udevObject = udev_new();
_monitorObject = ThrowIfFailedNull(udev_monitor_new_from_netlink(_udevObject, UdevMonitorName));
-
+
RemoveNonBlockingFlagOnUdevMonitorSocket();
StartListening();
@@ -197,8 +197,8 @@ private void RemoveNonBlockingFlagOnUdevMonitorSocket()
{
IntPtr fd = udev_monitor_get_fd(_monitorObject);
- int flags = ThrowIfFailedNegative(fcntl(fd, F_GETFL));
-
+ int flags = ThrowIfFailedNegative(fcntl(fd, F_GETFL));
+
// Remove the O_NONBLOCK flag to set the file descriptor to blocking mode.
_ = ThrowIfFailedNegative(fcntl(fd, F_SETFL, flags & ~O_NONBLOCK));
}
diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs
index f544c763..867409bb 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/LinuxHidFeatureReportConnection.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Linq;
using System.Globalization;
+using System.Linq;
using System.Runtime.InteropServices;
using Yubico.PlatformInterop;
diff --git a/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs b/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs
index 26390725..20592a8a 100644
--- a/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs
+++ b/Yubico.Core/src/Yubico/Core/Devices/SmartCard/SmartCardDevice.cs
@@ -15,8 +15,8 @@
using System;
using System.Collections.Generic;
using Yubico.Core.Iso7816;
-using Yubico.PlatformInterop;
using Yubico.Core.Logging;
+using Yubico.PlatformInterop;
namespace Yubico.Core.Devices.SmartCard
{
diff --git a/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs b/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs
index add3a08a..a0b05ebb 100644
--- a/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs
+++ b/Yubico.Core/src/Yubico/Core/Iso7816/CommandApdu.cs
@@ -93,7 +93,7 @@ public int Ne
{
if (value < 0)
{
- throw new ArgumentOutOfRangeException(nameof(Ne),ExceptionMessages.CommandApduNeRangeError);
+ throw new ArgumentOutOfRangeException(nameof(Ne), ExceptionMessages.CommandApduNeRangeError);
}
else
{
@@ -214,7 +214,7 @@ private bool ValidNe(ApduEncoding apduEncoding)
{
int inclusiveUpperBound = GetInclusiveUpperBound(apduEncoding);
- return (Ne == int.MaxValue) || (Ne >= 0 && Ne <= inclusiveUpperBound);
+ return Ne == int.MaxValue || (Ne >= 0 && Ne <= inclusiveUpperBound);
}
// Validates Nc, then returns the Lc field as a byte array in the given encoding.
diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs
index df7bb80c..df76c017 100644
--- a/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs
+++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvEncoder.cs
@@ -126,7 +126,7 @@ public static byte[] BuildTagAndLength(int tag, int length)
///
public static void VerifyTag(int tag)
{
- if ((tag < 0) || (tag > MaximumTag))
+ if (tag < 0 || tag > MaximumTag)
{
throw new TlvException(ExceptionMessages.TlvUnsupportedTag);
}
@@ -148,7 +148,7 @@ public static void VerifyTag(int tag)
///
public static void VerifyLength(int length)
{
- if ((length < 0) || (length > MaximumLength))
+ if (length < 0 || length > MaximumLength)
{
throw new TlvException(ExceptionMessages.TlvUnsupportedLengthField);
}
diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs
index b29e0517..ab398925 100644
--- a/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs
+++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvNestedTlv.cs
@@ -128,7 +128,7 @@ public void AddSubElement(TlvEncoder subElement)
override public bool TryEncode(Span encoding, int offset, out int bytesWritten)
{
bytesWritten = 0;
- if (encoding.Length < (offset + _encodedLength))
+ if (encoding.Length < offset + _encodedLength)
{
return false;
}
diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs
index f23c781a..0f3f5f27 100644
--- a/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs
+++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvReader.cs
@@ -418,7 +418,7 @@ public bool TryReadByte(out byte value, int expectedTag)
FixedLengthByte,
false);
- if (isValid == true)
+ if (isValid)
{
value = fullValue.Span[0];
}
@@ -474,7 +474,7 @@ public short ReadInt16(int expectedTag, bool bigEndian = true)
{
_ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt16, true);
- if (bigEndian == true)
+ if (bigEndian)
{
return BinaryPrimitives.ReadInt16BigEndian(value.Span);
}
@@ -528,9 +528,9 @@ public bool TryReadInt16(out short value, int expectedTag, bool bigEndian = true
FixedLengthInt16,
false);
- if (isValid == true)
+ if (isValid)
{
- if (bigEndian == true)
+ if (bigEndian)
{
value = BinaryPrimitives.ReadInt16BigEndian(fullValue.Span);
}
@@ -591,7 +591,7 @@ public ushort ReadUInt16(int expectedTag, bool bigEndian = true)
{
_ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt16, true);
- if (bigEndian == true)
+ if (bigEndian)
{
return BinaryPrimitives.ReadUInt16BigEndian(value.Span);
}
@@ -646,9 +646,9 @@ public bool TryReadUInt16(out ushort value, int expectedTag, bool bigEndian = tr
FixedLengthInt16,
false);
- if (isValid == true)
+ if (isValid)
{
- if (bigEndian == true)
+ if (bigEndian)
{
value = BinaryPrimitives.ReadUInt16BigEndian(fullValue.Span);
}
@@ -709,7 +709,7 @@ public int ReadInt32(int expectedTag, bool bigEndian = true)
{
_ = CommonReadValue(out ReadOnlyMemory value, expectedTag, FixedLengthInt32, true);
- if (bigEndian == true)
+ if (bigEndian)
{
return BinaryPrimitives.ReadInt32BigEndian(value.Span);
}
@@ -763,9 +763,9 @@ public bool TryReadInt32(out int value, int expectedTag, bool bigEndian = true)
FixedLengthInt32,
false);
- if (isValid == true)
+ if (isValid)
{
- if (bigEndian == true)
+ if (bigEndian)
{
value = BinaryPrimitives.ReadInt32BigEndian(fullValue.Span);
}
@@ -1108,38 +1108,57 @@ private bool CommonReadValue(
int fixedLength,
bool throwIfFailed)
{
- value = Memory.Empty;
-
- int result = ReadTagExpected(expectedTag);
- if (result != ValidEncoding)
+ bool isValidTlv = IsValidTlv(expectedTag, fixedLength, out int resultCode);
+ if (isValidTlv)
{
- goto exit;
+ value = _encoding.Slice(_currentValueOffset, _currentLength);
+ _currentOffset = _currentValueOffset + _currentLength;
+
+ ResetState();
+ return true;
}
- result = ReadLength();
- if (result != ValidEncoding)
+ // We must reset the state before we throw or return as well, so ResetState() is duplicated but the
+ // intent is more clear that we need to reset the state in all (3) cases.
+ ResetState();
+ if (throwIfFailed)
{
- goto exit;
+ ThrowOnFailedRead(resultCode);
}
- result = VerifyValue(fixedLength);
- if (result != ValidEncoding)
+ value = Memory.Empty;
+ return false;
+ }
+
+ ///
+ /// Attempts to read and validate the expected tag, its length, and its value, indicating success through the return value and providing a result code.
+ ///
+ /// The tag expected to be read.
+ /// The fixed length that the value is expected to adhere to.
+ /// Out parameter that returns the result code of the operation, indicating the specific outcome or error.
+ /// Returns true if the tag, length, and value are successfully read and validated. Returns false if any validation fails, along with the appropriate result code.
+ private bool IsValidTlv(int expectedTag, int fixedLength, out int resultCode)
+ {
+ resultCode = ReadTagExpected(expectedTag);
+ if (resultCode != ValidEncoding)
{
- goto exit;
+ return false;
}
- value = _encoding.Slice(_currentValueOffset, _currentLength);
- _currentOffset = _currentValueOffset + _currentLength;
-
-exit:
- ResetState();
+ resultCode = ReadLength();
+ if (resultCode != ValidEncoding)
+ {
+ return false;
+ }
- if ((result != ValidEncoding) && (throwIfFailed == true))
+ resultCode = VerifyValue(fixedLength);
+ if (resultCode != ValidEncoding)
{
- ThrowOnFailedRead(result);
+ return false;
}
- return result == ValidEncoding;
+ // Valid Tlv, we were able to read the tag, length and verify the value
+ return true;
}
// Read the tag, verifying the tag in the encoding is the same as the
@@ -1168,9 +1187,9 @@ private int ReadTagExpected(int expectedTag)
}
int result = ReadTag(tagLength);
- if ((result == ValidEncoding) && (_currentTag != expectedTag))
+ if (result == ValidEncoding && _currentTag != expectedTag)
{
- result = UnexpectedEncoding;
+ return UnexpectedEncoding;
}
return result;
@@ -1184,7 +1203,7 @@ private int ReadTagExpected(int expectedTag)
// UnexpectedEnd (not enough bytes to read)
private int ReadTag(int tagLength)
{
- if ((tagLength <= 0) || (tagLength > MaximumTagLength))
+ if (tagLength <= 0 || tagLength > MaximumTagLength)
{
return UnsupportedTag;
}
@@ -1196,7 +1215,7 @@ private int ReadTag(int tagLength)
ResetState();
- if ((_currentOffset + tagLength) > _encoding.Length)
+ if (_currentOffset + tagLength > _encoding.Length)
{
return UnexpectedEnd;
}
@@ -1228,7 +1247,7 @@ private int ReadLength()
}
int count = 1;
- if ((_currentOffset + _currentTagLength) < _encoding.Length)
+ if (_currentOffset + _currentTagLength < _encoding.Length)
{
_currentLength = (int)_encoding.Span[_currentOffset + _currentTagLength];
if (_currentLength <= 0x7F)
@@ -1244,11 +1263,11 @@ private int ReadLength()
// If the initial length byte is 0x80, that is an unsupported value
// (it's BER for indefinite length and we support DER only). In that
// case, we would have set count to 0 (0x80 & 0x7F yields 0).
- if ((count == 0) || (count > MaximumLengthCount))
+ if (count == 0 || count > MaximumLengthCount)
{
return UnsupportedLength;
}
- if ((_currentOffset + _currentTagLength + count + 1) > _encoding.Length)
+ if (_currentOffset + _currentTagLength + count + 1 > _encoding.Length)
{
return UnexpectedEnd;
}
@@ -1289,7 +1308,7 @@ private int VerifyValue(int fixedLength)
break;
}
- return (_currentValueOffset + _currentLength) <= _encoding.Length
+ return _currentValueOffset + _currentLength <= _encoding.Length
? ValidEncoding
: UnexpectedEnd;
}
diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs
index ff212c5c..86da0e77 100644
--- a/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs
+++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvSubElement.cs
@@ -70,7 +70,7 @@ public TlvSubElement(int tag, ReadOnlySpan value)
_tagAndLength = BuildTagAndLength(tag, value.Length);
_value = value.ToArray();
- _encodedLength = _tagAndLength.Length + _value.Length;
+ _encodedLength = _tagAndLength.Length + _value.Length;
}
///
@@ -97,7 +97,7 @@ public TlvSubElement(ReadOnlySpan encodedTlv)
override public bool TryEncode(Span encoding, int offset, out int bytesWritten)
{
bytesWritten = 0;
- if (encoding.Length < (offset + _encodedLength))
+ if (encoding.Length < offset + _encodedLength)
{
return false;
}
diff --git a/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs b/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs
index 57ff262d..e12cbbf5 100644
--- a/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs
+++ b/Yubico.Core/src/Yubico/Core/Tlv/TlvWriter.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Collections.Generic;
using System.Buffers.Binary;
+using System.Collections.Generic;
using System.Text;
namespace Yubico.Core.Tlv
@@ -126,6 +126,7 @@ private void EndNestedTlv()
{
throw new TlvException(ExceptionMessages.TlvInvalidSchema);
}
+
TlvNestedTlv nestedToEnd = _nestedTlvStack.Pop();
TlvNestedTlv parent = _nestedTlvStack.Peek();
parent.AddSubElement(nestedToEnd);
@@ -254,6 +255,7 @@ public void WriteString(int tag, string value, Encoding encoding)
{
throw new ArgumentNullException(nameof(encoding));
}
+
WriteValue(tag, encoding.GetBytes(value));
}
@@ -299,7 +301,8 @@ public void WriteByte(int tag, byte value)
public void WriteInt16(int tag, short value, bool bigEndian = true)
{
byte[] valueArray = new byte[2];
- if (bigEndian == true)
+
+ if (bigEndian)
{
BinaryPrimitives.WriteInt16BigEndian(valueArray, value);
}
@@ -330,7 +333,8 @@ public void WriteInt16(int tag, short value, bool bigEndian = true)
public void WriteUInt16(int tag, ushort value, bool bigEndian = true)
{
byte[] valueArray = new byte[2];
- if (bigEndian == true)
+
+ if (bigEndian)
{
BinaryPrimitives.WriteUInt16BigEndian(valueArray, value);
}
@@ -363,7 +367,8 @@ public void WriteUInt16(int tag, ushort value, bool bigEndian = true)
public void WriteInt32(int tag, int value, bool bigEndian = true)
{
byte[] valueArray = new byte[4];
- if (bigEndian == true)
+
+ if (bigEndian)
{
BinaryPrimitives.WriteInt32BigEndian(valueArray, value);
}
@@ -420,6 +425,7 @@ public byte[] Encode()
TlvNestedTlv initialNested = GetInitialNestedTlv();
byte[] encoding = new byte[initialNested.EncodedLength];
+
if (initialNested.TryEncode(encoding, 0, out _) == false)
{
throw new TlvException(ExceptionMessages.TlvInvalidSchema);
@@ -561,6 +567,7 @@ private TlvNestedTlv GetInitialNestedTlv()
///
///
///
+
//
// When we're following a schema, we want to make sure the elements that
// belong under a particular NestedTlv are placed there and not anywhere
@@ -632,7 +639,7 @@ private TlvNestedTlv GetInitialNestedTlv()
// method and allow the using construction. Hence, there is no need to
// compare instances. We could have made this a Class instead of a
// Struct, but we are following the AsnWriter pattern.
-#pragma warning disable CA1034, CA1815 // see comments above
+#pragma warning disable CA1034, CA1815 // see comments above
public struct TlvScope : IDisposable
{
private TlvWriter? _writer;
@@ -655,6 +662,7 @@ internal TlvScope(TlvWriter writer)
/// will make sure the Nested TLV is ended and any new additions to the
/// TlvWriter object will be associated with the Nested TLV's parent.
///
+
// Note that .NET recommends a Dispose method call Dispose(true) and
// GC.SuppressFinalize(this). The actual disposal is in the
// Dispose(bool) method.
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs
index 6136ff4d..3f48cee4 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardCardHandle.cs
@@ -12,10 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
-
+using Microsoft.Win32.SafeHandles;
using static Yubico.PlatformInterop.NativeMethods;
namespace Yubico.PlatformInterop
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs
index 51a8c91a..6df6ef73 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Desktop/SCard/SCardContext.cs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
+using Microsoft.Win32.SafeHandles;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs
index c6feccf3..8354534c 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/Libc.Interop.cs
@@ -95,18 +95,17 @@ public enum OpenFlags
// Read count bytes. Place them into outputBuffer.
[DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "read", SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
- public static extern int read(
- LinuxFileSafeHandle handle,
- [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] outputBuffer,
- int count);
+ public static extern int read(LinuxFileSafeHandle handle,
+ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
+ byte[] outputBuffer,
+ int count);
// Write the count bytes in inputBuffer.
[DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "write", SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
- public static extern int write(
- int handle,
- [MarshalAs(UnmanagedType.LPArray)] byte[] inputBuffer,
- int count);
+ public static extern int write(int handle,
+ [MarshalAs(UnmanagedType.LPArray)] byte[] inputBuffer,
+ int count);
[DllImport(Libraries.LinuxKernelLib, CharSet = CharSet.Ansi, EntryPoint = "fcntl", SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs
index 15a91a53..98d8b268 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Libc/LinuxFileSafeHandle.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs
index 5c55f2de..7096eafa 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevDeviceSafeHandle.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs
index c05938d3..58060a45 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevEnumerateSafeHandle.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs
index 061ae96a..71cc97f0 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevMonitorSafeHandle.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs
index cdf9643d..11a9920f 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevSafeHandle.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
+using System.Runtime.InteropServices;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs
index d7f20ce6..1dd35eeb 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/LinuxUdevScan.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Text;
using Yubico.Core.Devices.Hid;
namespace Yubico.PlatformInterop
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs
index 2b0bdadf..825488d0 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Linux/Udev/Udev.Interop.cs
@@ -259,13 +259,13 @@ public static extern int udev_monitor_filter_add_match_subsystem_devtype(
// struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor);
[DllImport(Libraries.LinuxUdevLib, CharSet = CharSet.Ansi, EntryPoint = "udev_monitor_receive_device", SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
- public static extern LinuxUdevDeviceSafeHandle udev_monitor_receive_device (LinuxUdevMonitorSafeHandle monitorObject);
-
+ public static extern LinuxUdevDeviceSafeHandle udev_monitor_receive_device(LinuxUdevMonitorSafeHandle monitorObject);
+
// Get the socket file descriptor associated with the monitor.
// The C signature is
// int udev_monitor_get_fd(struct udev_monitor *udev_monitor);
[DllImport(Libraries.LinuxUdevLib, CharSet = CharSet.Ansi, EntryPoint = "udev_monitor_get_fd", SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
- public static extern IntPtr udev_monitor_get_fd (LinuxUdevMonitorSafeHandle monitorObject);
+ public static extern IntPtr udev_monitor_get_fd(LinuxUdevMonitorSafeHandle monitorObject);
}
}
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs b/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs
index 4b71a02c..78237ee7 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/SdkPlatformInfo.cs
@@ -14,8 +14,8 @@
using System;
using System.Runtime.InteropServices;
-using System.Text;
using System.Security.Principal;
+using System.Text;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs
index e392e198..22244218 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Cfgmgr32/CmDevice.cs
@@ -12,13 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
using Yubico.Core.Buffers;
using static Yubico.PlatformInterop.NativeMethods;
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs
index cf307810..40f37172 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidD.Interop.cs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs
index f161ba32..052a6485 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/HidD/HidDDevice.cs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
using Yubico.Core;
using static Yubico.PlatformInterop.NativeMethods;
diff --git a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs
index 2253c6ce..368cdbd4 100644
--- a/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs
+++ b/Yubico.Core/src/Yubico/PlatformInterop/Windows/Kernel32/Kernel32.Interop.cs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
namespace Yubico.PlatformInterop
{
diff --git a/Yubico.Core/tests/Yubico.Core.UnitTests.csproj b/Yubico.Core/tests/Yubico.Core.UnitTests.csproj
index c07faf01..03350dab 100644
--- a/Yubico.Core/tests/Yubico.Core.UnitTests.csproj
+++ b/Yubico.Core/tests/Yubico.Core.UnitTests.csproj
@@ -44,9 +44,9 @@ limitations under the License. -->
-
-
-
+
+
+
diff --git a/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs b/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs
index 3792340d..45cd24d3 100644
--- a/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Cryptography/BnTests.cs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.PlatformInterop;
using Xunit;
+using Yubico.PlatformInterop;
namespace Yubico.Core.Cryptography
{
diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs
index 1830a8aa..ce007f7f 100644
--- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs
@@ -12,16 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Moq;
using System;
using System.Linq;
+using Moq;
using Xunit;
using Yubico.Core.Buffers;
using Yubico.PlatformInterop;
namespace Yubico.Core.Devices.Hid.UnitTests
{
-
+
#if false
public class HidConnectionTests
{
diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs
index ec219cc2..4f2526c6 100644
--- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidDeviceListenerTests.cs
@@ -20,7 +20,7 @@ namespace Yubico.Core.Devices.Hid.UnitTests
class FakeHidDevice : IHidDevice
{
public DateTime LastAccessed { get; } = DateTime.Now;
- public string Path { get; } = String.Empty;
+ public string Path { get; } = string.Empty;
public string? ParentDeviceId { get; } = null;
public short VendorId { get; }
public short ProductId { get; }
@@ -43,7 +43,7 @@ public class HidDeviceListenerTests
public void Create_ReturnsInstanceOfListener()
{
var listener = HidDeviceListener.Create();
- Assert.IsAssignableFrom(listener);
+ _ = Assert.IsAssignableFrom(listener);
}
[Fact]
@@ -57,7 +57,7 @@ public void OnArrived_WithNoListeners_NoOps()
public void OnArrived_WithEventListener_RaisesArrivedEvent()
{
var listener = new FakeHidListener();
- Assert.Raises(
+ _ = Assert.Raises(
e => listener.Arrived += e,
e => listener.Arrived -= e,
() => listener.FireArrival());
@@ -74,7 +74,7 @@ public void OnRemoved_WithNoListeners_NoOps()
public void OnRemoved_WithEventListener_RaisesRemovedEvent()
{
var listener = new FakeHidListener();
- Assert.Raises(
+ _ = Assert.Raises(
e => listener.Removed += e,
e => listener.Removed -= e,
() => listener.FireRemoval());
diff --git a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs
index a31bb99e..32616a6d 100644
--- a/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Devices/Hid/HidTranslatorTests.cs
@@ -206,10 +206,10 @@ private static (char, byte)[] GetDataForKeyboard(KeyboardLayout layout)
-1 => $"ToAscii returned -1 converting scan code to a char, which means that it is a dead key (https://bit.ly/3tZOIi0).",
0 => $"ToAscii returned 0 converting scan code to a char, which means that there is no mapping for the current code.",
2 => $"ToAscii returned 2, which means that a dead key (https://bit.ly/3tZOIi0) had state in the keyboard state buffer. Should never happen here.",
- _ => $"ToAscii returned { result }. This is not a documented return value for ToAscii."
+ _ => $"ToAscii returned {result}. This is not a documented return value for ToAscii."
};
string message = error + Environment.NewLine +
- $"HID Usage Code[{ code.ToString("x2") }], PS/2 Scan Code[{ scanCode.ToString("x2") }], VKey[{ vkey.ToString("x2") }]";
+ $"HID Usage Code[{code.ToString("x2")}], PS/2 Scan Code[{scanCode.ToString("x2")}], VKey[{vkey.ToString("x2")}]";
throw new InvalidOperationException(message);
}
// Windows returns \r for the enter key, so we'll just swap.
@@ -285,7 +285,7 @@ private static IntPtr GetKeyboardLayout(KeyboardLayout layout) =>
KeyboardLayout.sv_SE => NativeMethods.LoadKeyboardLayout("0000410d", 0),
// We'll use the en_US layout for ModHex.
KeyboardLayout.ModHex => NativeMethods.LoadKeyboardLayout("00000409", 0),
- _ => throw new NotSupportedException($"Layout [{ layout }] not implemented."
+ _ => throw new NotSupportedException($"Layout [{layout}] not implemented."
+ Environment.NewLine + "Did you implement a new layout without adding it here?")
};
diff --git a/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs b/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs
index 0cc9b7ff..5464027a 100644
--- a/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Iso7816/CommandApduTests.cs
@@ -26,8 +26,8 @@ public class CommandApduTests
private static readonly byte[] _header = new byte[] { 0xBA, 0xDF, 0x00, 0xD };
private static byte _cla => _header[0];
private static byte _ins => _header[1];
- private static byte _p1 => _header[2];
- private static byte _p2 => _header[3];
+ private static byte _p1 => _header[2];
+ private static byte _p2 => _header[3];
//
// Private utility functions
@@ -577,11 +577,11 @@ public void AsEncodingByteArray_NeSetIntMaxValue_EmitsCorrectApduMaxNe(ApduEncod
{
int ne = int.MaxValue;
byte[] expectedLe = apduEncoding switch
- {
- ApduEncoding.ShortLength => new byte[] { 0x00 },
- ApduEncoding.ExtendedLength => new byte[] { 0x00, 0x00, 0x00 },
- _ => Array.Empty(), // Shouldn't be reached
- };
+ {
+ ApduEncoding.ShortLength => new byte[] { 0x00 },
+ ApduEncoding.ExtendedLength => new byte[] { 0x00, 0x00, 0x00 },
+ _ => Array.Empty(), // Shouldn't be reached
+ };
var expectedByteArray = new List();
expectedByteArray.AddRange(_header);
diff --git a/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs b/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs
index b49a7465..1969c453 100644
--- a/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Tlv/TlvReaderTests.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Text;
using System.Linq;
+using System.Text;
using Xunit;
namespace Yubico.Core.Tlv.UnitTests
@@ -296,7 +296,7 @@ public void ReadInt32_ReturnsCorrect(int value, bool bigEndian)
{
byte value0 = (byte)(value >> 24);
byte value1 = (byte)(value >> 16);
- byte value2 = (byte)(value >> 8);
+ byte value2 = (byte)(value >> 8);
byte value3 = (byte)value;
byte[] encoding = new byte[] { 0x01, 0x04, value0, value1, value2, value3 };
if (bigEndian == false)
diff --git a/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs b/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs
index 8438c8c5..a5c240b7 100644
--- a/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs
+++ b/Yubico.Core/tests/Yubico/Core/Tlv/TlvTryTests.cs
@@ -15,7 +15,6 @@
using System;
using System.Security.Cryptography;
using Xunit;
-using Yubico.Core.Tlv;
namespace Yubico.Core.Tlv.UnitTests
{
@@ -24,7 +23,8 @@ public class TlvTryTests
[Fact]
public void Tlv_TryReadValue()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x02, 0x05, 0x31, 0x32, 0x33, 0x34, 0x35
};
@@ -58,18 +58,19 @@ public void Tlv_TryReadValue_ReturnsCorrectValue()
[Fact]
public void Tlv_TryReadNested()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x72, 0x61, 0x0A,
- 0x01, 0x02, 0x41, 0x42,
- 0x02, 0x04, 0x31, 0x32, 0x33, 0x34
+ 0x01, 0x02, 0x41, 0x42,
+ 0x02, 0x04, 0x31, 0x32, 0x33, 0x34
};
var reader = new TlvReader(encoding);
bool validRead = reader.TryReadNestedTlv(out TlvReader nested, 0x7261);
- if (validRead == true)
+ if (validRead)
{
validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x01);
- if (validRead == true)
+ if (validRead)
{
Assert.Equal(2, value.Length);
validRead = nested.TryReadValue(out value, 0x02);
@@ -111,7 +112,7 @@ public void Tlv_TryReadInt16_LittleEndian()
var reader = new TlvReader(encoding);
bool validRead = reader.TryReadInt16(out short value, 0xFF);
- if (validRead == true)
+ if (validRead)
{
validRead = reader.TryReadInt16(out value, 0xFE, false);
}
@@ -139,7 +140,7 @@ public void Tlv_TryReadUInt16_LittleEndian()
var reader = new TlvReader(encoding);
bool validRead = reader.TryReadUInt16(out ushort value, 0xFF);
- if (validRead == true)
+ if (validRead)
{
validRead = reader.TryReadUInt16(out value, 0xFE, false);
}
@@ -176,7 +177,8 @@ public void Tlv_TryReadInt32_LittleEndian()
public void Tlv_TryReadString()
{
string expectedValue = "12345";
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x02, 0x05, 0x31, 0x32, 0x33, 0x34, 0x35
};
@@ -190,25 +192,25 @@ public void Tlv_TryReadString()
[Fact]
public void TlvTryRead_MultipleValues_Correct()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x72, 0x61, 0x0A,
- 0x01, 0x02, 0x41, 0x42,
- 0x02, 0x04, 0x31, 0x32, 0x33, 0x34
+ 0x01, 0x02, 0x41, 0x42,
+ 0x02, 0x04, 0x31, 0x32, 0x33, 0x34
};
var reader = new TlvReader(encoding);
bool validRead = reader.TryReadNestedTlv(out TlvReader nested, 0x7261);
- if (validRead == true)
+ if (validRead)
{
- validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x91);
+ validRead = nested.TryReadValue(out _, 0x91);
Assert.False(validRead);
-
- validRead = nested.TryReadValue(out value, 0x01);
- if (validRead == true)
+ validRead = nested.TryReadValue(out ReadOnlyMemory value, 0x01);
+ if (validRead)
{
Assert.Equal(2, value.Length);
- validRead = nested.TryReadValue(out value, 0x92);
+ validRead = nested.TryReadValue(out _, 0x92);
Assert.False(validRead);
validRead = nested.TryReadValue(out value, 0x02);
@@ -245,13 +247,14 @@ public void TryReadValue_TwoByteLength()
[Fact]
public void TryReadNested_WrongTag_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x13,
- 0x01, 0x02, 0x31, 0x32,
- 0x82, 0x0B,
- 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
- 0x91, 0x00
+ 0x01, 0x02, 0x31, 0x32,
+ 0x82, 0x0B,
+ 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0x00
};
var reader = new TlvReader(encoding);
@@ -271,11 +274,12 @@ public void TryReadNested_WrongTag_ReturnsFalse()
[Fact]
public void TryReadValue_WrongTag_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x13,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
- 0x91, 0x00
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0x00
};
var reader = new TlvReader(encoding);
@@ -291,11 +295,12 @@ public void TryReadValue_WrongTag_ReturnsFalse()
[Fact]
public void TryReadValue_InvalidLength_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x13,
- 0x11, 0x80, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
- 0x91, 0x00
+ 0x11, 0x80, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0x00
};
var reader = new TlvReader(encoding);
@@ -311,11 +316,12 @@ public void TryReadValue_InvalidLength_ReturnsFalse()
[Fact]
public void TryReadValue_NotEnoughData_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x13,
- 0x11, 0x12, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
- 0x91, 0x00
+ 0x11, 0x12, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0x00
};
var reader = new TlvReader(encoding);
@@ -331,11 +337,12 @@ public void TryReadValue_NotEnoughData_ReturnsFalse()
[Fact]
public void TryReadByte_LengthZero_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x13,
- 0x91, 0x00,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
+ 0x91, 0x00,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
};
var reader = new TlvReader(encoding);
@@ -351,11 +358,12 @@ public void TryReadByte_LengthZero_ReturnsFalse()
[Fact]
public void TryReadByte_LengthTwo_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x15,
- 0x91, 0x02, 0x41, 0x42,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0x02, 0x41, 0x42,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
};
var reader = new TlvReader(encoding);
@@ -371,11 +379,12 @@ public void TryReadByte_LengthTwo_ReturnsFalse()
[Fact]
public void TryReadInt16_LengthZero_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x14,
- 0x91, 0xFF, 0x00,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
+ 0x91, 0xFF, 0x00,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
};
var reader = new TlvReader(encoding);
@@ -391,11 +400,12 @@ public void TryReadInt16_LengthZero_ReturnsFalse()
[Fact]
public void TryReadInt16_LengthOne_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x15,
- 0x91, 0xFF, 0x01, 0x41,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0xFF, 0x01, 0x41,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
};
var reader = new TlvReader(encoding);
@@ -411,11 +421,12 @@ public void TryReadInt16_LengthOne_ReturnsFalse()
[Fact]
public void TryReadUInt16_LengthZero_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x14,
- 0x91, 0xFF, 0x00,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
+ 0x91, 0xFF, 0x00,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65
};
var reader = new TlvReader(encoding);
@@ -431,11 +442,12 @@ public void TryReadUInt16_LengthZero_ReturnsFalse()
[Fact]
public void TryReadUInt16_LengthOne_ReturnsFalse()
{
- byte[] encoding = new byte[] {
+ byte[] encoding = new byte[]
+ {
0x81, 0x15,
- 0x91, 0xFF, 0x01, 0x41,
- 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
- 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
+ 0x91, 0xFF, 0x01, 0x41,
+ 0x11, 0x08, 0x31, 0x32, 0x82, 0x0B, 0x03, 0x02, 0x41, 0x42,
+ 0x04, 0x05, 0x61, 0x62, 0x63, 0x64, 0x65,
};
var reader = new TlvReader(encoding);
diff --git a/Yubico.DotNetPolyfills/src/AssemblyInfo.cs b/Yubico.DotNetPolyfills/src/AssemblyInfo.cs
index b1da9f09..a8b816ed 100644
--- a/Yubico.DotNetPolyfills/src/AssemblyInfo.cs
+++ b/Yubico.DotNetPolyfills/src/AssemblyInfo.cs
@@ -14,4 +14,4 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
diff --git a/Yubico.NativeShims/CMakeLists.txt b/Yubico.NativeShims/CMakeLists.txt
index 73accfe2..b1e6cdfd 100644
--- a/Yubico.NativeShims/CMakeLists.txt
+++ b/Yubico.NativeShims/CMakeLists.txt
@@ -1,32 +1,56 @@
-cmake_minimum_required(VERSION 3.10)
+cmake_minimum_required(VERSION 3.13)
+project(Yubico.NativeShims VERSION 1.10.1)
+include(CheckCCompilerFlag)
-project(Yubico.NativeShims VERSION 1.3.0)
+if (APPLE OR UNIX)
+ if (APPLE)
+ set(PLATFORM_MACOS true)
+ set(BACKEND "macscard")
+ add_link_options("-exported_symbols_list ${CMAKE_CURRENT_SOURCE_DIR}/exports.llvm")
+ elseif(UNIX)
+ find_package(PkgConfig REQUIRED)
+ set(PLATFORM_LINUX true)
+ set(BACKEND "pcsc")
+ add_link_options("-Wl,-z,relro,-z,now,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports.gnu")
+ endif()
+ if (CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
+ CMAKE_C_COMPILER_ID STREQUAL "AppleClang" OR
+ CMAKE_C_COMPILER_ID STREQUAL "GNU")
-if (APPLE)
- set(PLATFORM_MACOS true)
- set(BACKEND "macscard")
-elseif(UNIX)
- set(PLATFORM_LINUX true)
- set(BACKEND "pcsc")
- find_package(PkgConfig REQUIRED)
+ add_compile_options(-Wall -Wextra -Werror)
+ add_compile_options(-Wformat -Wformat-nonliteral -Wformat-security)
+ add_compile_options(-Wshadow)
+ add_compile_options(-Wcast-qual)
+ add_compile_options(-Wbad-function-cast)
+ add_compile_options(-pedantic -pedantic-errors)
+ add_compile_options(-fpic)
+ add_compile_options(-O2)
+ add_compile_definitions (-D_FORTIFY_SOURCE=2)
+ add_link_options(-fpic)
+
+ check_c_compiler_flag("-fstack-protector-all" HAVE_STACK_PROTECTOR_ALL)
+ if (HAVE_STACK_PROTECTOR_ALL)
+ message(STATUS "-fstack-protector-all support detected")
+ add_compile_options(-fstack-protector-all)
+ add_link_options(-fstack-protector-all)
+ else ()
+ check_c_compiler_flag("-fstack-protector" HAVE_STACK_PROTECTOR)
+ if(HAVE_STACK_PROTECTOR)
+ message(STATUS "-fstack-protector support detected")
+ add_compile_options(-fstack-protector)
+ add_link_options(-fstack-protector)
+ else ()
+ message(WARNING "No stack protection supported.")
+ endif ()
+ endif()
+ elseif()
+ message(WARNING "No compatible compiler found for setting additional security compiler flags.")
+ endif()
elseif(WIN32)
set(PLATFORM_WINDOWS true)
set(BACKEND "winscard")
-endif()
-
-# export list
-if(APPLE AND (CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
- CMAKE_C_COMPILER_ID STREQUAL "AppleClang"))
- # clang + lld
- string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS}
- " -exported_symbols_list ${CMAKE_CURRENT_SOURCE_DIR}/exports.llvm")
-elseif(NOT MSVC)
- # clang/gcc + gnu ld
- string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS}
- " -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports.gnu")
-else()
- string(CONCAT CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS}
- " /def:\"${CMAKE_CURRENT_SOURCE_DIR}/exports.msvc\"")
+ add_link_options("/guard:cf" "/def:${CMAKE_CURRENT_SOURCE_DIR}/exports.msvc")
+ add_compile_options("/GS" "/Gs")
endif()
@@ -36,7 +60,6 @@ endif()
include(${CMAKE_SOURCE_DIR}/cmake/pcscd.cmake)
find_pcscd()
-
find_package(OpenSSL REQUIRED)
#
diff --git a/Yubico.NativeShims/Yubico.NativeShims.nuspec b/Yubico.NativeShims/Yubico.NativeShims.nuspec
index 52265f24..48b1d8bf 100644
--- a/Yubico.NativeShims/Yubico.NativeShims.nuspec
+++ b/Yubico.NativeShims/Yubico.NativeShims.nuspec
@@ -2,7 +2,7 @@
Yubico.NativeShims
- 1.6.1
+ 1.0.0
Yubico AB
Yubico AB
@@ -21,17 +21,15 @@
+
+
-
-
-
-
-
-
+
+
diff --git a/Yubico.NativeShims/build-linux-amd64.sh b/Yubico.NativeShims/build-linux-amd64.sh
new file mode 100644
index 00000000..de54e5eb
--- /dev/null
+++ b/Yubico.NativeShims/build-linux-amd64.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+# Set environment variables
+export VCPKG_INSTALLATION_ROOT=$GITHUB_WORKSPACE/vcpkg \
+ PATH=/usr/local/bin:$PATH
+
+# Install necessary packages
+sudo apt-get update -qq && \
+DEBIAN_FRONTEND=noninteractive sudo apt-get install -yq \
+ git \
+ tar \
+ curl \
+ zip \
+ unzip \
+ wget \
+ build-essential \
+ software-properties-common \
+ ca-certificates \
+ pkg-config \
+ gnupg \
+ libpcsclite-dev \
+ zlib1g-dev \
+ ninja-build \
+ g++ \
+ gcc
+
+# Install latest version of CMake for Ubuntu 20.04
+wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /usr/share/keyrings/kitware-archive-keyring.gpg >/dev/null
+echo 'deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ focal main' | sudo tee /etc/apt/sources.list.d/kitware.list >/dev/null
+sudo apt-get update -qq
+sudo apt-get install cmake -yq
+
+# Install VCPKG
+git clone https://github.com/Microsoft/vcpkg.git ${VCPKG_INSTALLATION_ROOT} && ${VCPKG_INSTALLATION_ROOT}/bootstrap-vcpkg.sh
+
+## Build
+if [ ! -f ./CMakeLists.txt ]; then
+ cd ~/Yubico.NativeShims
+fi
+
+build_dir="linux-x64"
+rm -rf "$build_dir"
+mkdir -p "$build_dir"
+
+echo "Building for x64-linux ..."
+cmake -S . -B "$build_dir" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_TOOLCHAIN_FILE="$VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" \
+ -DVCPKG_TARGET_TRIPLET=x64-linux
+
+cmake --build "$build_dir" -- -j $(nproc)
diff --git a/Yubico.NativeShims/build-linux-arm64.sh b/Yubico.NativeShims/build-linux-arm64.sh
new file mode 100644
index 00000000..e6bb8f3d
--- /dev/null
+++ b/Yubico.NativeShims/build-linux-arm64.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+
+# Set environment variables
+export VCPKG_INSTALLATION_ROOT=$GITHUB_WORKSPACE/vcpkg \
+ VCPKG_FORCE_SYSTEM_BINARIES=1 \
+ PATH=/usr/local/bin:$VCPKG_INSTALLATION_ROOT:$PATH
+
+# Install necessary packages
+sudo apt-get update -qq && \
+DEBIAN_FRONTEND=noninteractive sudo apt-get install -yq \
+ git \
+ tar \
+ curl \
+ zip \
+ unzip \
+ wget \
+ build-essential \
+ software-properties-common \
+ ca-certificates \
+ pkg-config \
+ gnupg \
+ zlib1g-dev \
+ ninja-build \
+ g++-aarch64-linux-gnu \
+ gcc-aarch64-linux-gnu
+
+# Install latest version of CMake for Ubuntu 20.04
+wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /usr/share/keyrings/kitware-archive-keyring.gpg >/dev/null
+echo 'deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ focal main' | sudo tee /etc/apt/sources.list.d/kitware.list >/dev/null
+sudo apt-get update -qq
+sudo apt-get install cmake -yq
+
+# Install VCPKG
+git clone https://github.com/Microsoft/vcpkg.git ${VCPKG_INSTALLATION_ROOT} && ${VCPKG_INSTALLATION_ROOT}/bootstrap-vcpkg.sh
+
+# Install arm64 version of libpcsclite
+echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe multiverse
+deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe multiverse
+deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse
+deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list > /dev/null
+sudo dpkg --add-architecture arm64
+sudo apt-get update -qq
+sudo apt-get install libpcsclite-dev:arm64 -yq
+
+## Build
+if [ ! -f ./CMakeLists.txt ]; then
+ cd ~/Yubico.NativeShims
+fi
+
+# Add paths to our libraries so that CMake finds the correct arm64 ones
+export PKG_CONFIG_PATH="/usr/lib/aarch64-linux-gnu/pkgconfig:$(pwd)/arm64-linux/vcpkg_installed/arm64-linux/lib/pkgconfig"
+
+build_dir=linux-arm64
+rm -rf "$build_dir"
+mkdir -p "$build_dir"
+
+echo "Building for arm64-linux ..."
+cmake -S . -B "$build_dir" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_TOOLCHAIN_FILE="$VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" \
+ -DVCPKG_TARGET_TRIPLET="arm64-linux" \
+ -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$(pwd)/cmake/aarch64-linux-gnu.toolchain.cmake" \
+ -DOPENSSL_ROOT_DIR=$(pwd)/linux-arm64/vcpkg_installed/arm64-linux
+
+cmake --build "$build_dir" -- -j $(nproc)
diff --git a/Yubico.NativeShims/build-ubuntu.sh b/Yubico.NativeShims/build-ubuntu.sh
deleted file mode 100644
index a8bf325b..00000000
--- a/Yubico.NativeShims/build-ubuntu.sh
+++ /dev/null
@@ -1,87 +0,0 @@
-# We use Docker Build Kit as it supports advanced features such as
-# cross-architecture building using QEMU, and extracting files from
-# the final build image.
-
-export DOCKER_BUILDKIT=1
-
-# Download the Docker image / plugin that allows QEMU to run non-
-# native container architectures. This step is necessary to run
-# the cross build steps below.
-docker run --pull always --rm --privileged multiarch/qemu-user-static --reset -p yes
-
-
-# Parameter guide:
-#
-# Tag: Right now, we do not save these images to any container
-# registry. Because of this, it is fine that we're using a static
-# version number in the tag. If building native shims become something
-# we need to do on a more regular basis (like daily), we can look into
-# caching the build environment to save on our CI runner workload.
-#
-# File: Points to the docker file definition that we wish to build.
-# Each flavor of Linux should have their own Dockerfile to customize
-# the build process to that particular distribution.
-#
-# Platform: The Docker platform identifier to build. The platforms
-# we're interested in as part of the SDK are: linux/{amd64,386,arm64,arm/v7}
-#
-# Build-args: We pass in the hosts' user and group ID so that all files
-# are ACL'd according to the host system.
-#
-# Output: We tell Docker to output the contents of the final image to
-# the local fileystem, inside of the artifacts/{distro} directory.
-# Within that folder, there should be a folder for each platform built.
-# This will typically mean that there is a `linux` directory, followed
-# by another folder for the processor architecture.
-# For example: `artifacts/linux/386` for the 32-bit Linux build
-#
-# . : This tells Docker to use the current directory as the basis for
-# the "context" to pass into the image using the COPY Dockerfile
-# instruction. This should be the Yubico.NativeShims folder containing
-# this script, as well as the CMakeLists.txt file.
-#
-# Extending this script:
-#
-# If we're adding a new build, say for a new distribution, we should
-# simply add another docker buildx command. We need to add a call for
-# each of the supported processor architectures (usually amd64 and arm64).
-#
-# We may want to consider refactoring this script to use functions at
-# some point to make adding new distributions and architectures even
-# easier.
-
-# Distro: Ubuntu
-# Arch: amd64/x64
-# Output: ./ubuntu-x64/libYubico.NativeShims.so
-docker buildx build \
- --tag yubico/nativeshims-ubuntu:1.0 \
- --file docker/Ubuntu/Dockerfile \
- --platform=linux/amd64 \
- --build-arg USER_ID=`id -u` \
- --build-arg GROUP_ID=`id -g` \
- --output type=local,dest=ubuntu-x64 \
- .
-
-# Distro: Ubuntu
-# Arch: i386/x86
-# Output: ./ubuntu-x86/libYubico.NativeShims.so
-docker buildx build \
- --tag yubico/nativeshims-ubuntu:1.0 \
- --file docker/Ubuntu/Dockerfile \
- --platform=linux/386 \
- --build-arg USER_ID=`id -u` \
- --build-arg GROUP_ID=`id -g` \
- --output type=local,dest=ubuntu-x86 \
- .
-
-# Distro: Ubuntu
-# Arch: arm64
-# Output: ./ubuntu-arm64/libYubico.NativeShims.so
-docker buildx build \
- --tag yubico/nativeshims-ubuntu:1.0 \
- --file docker/Ubuntu/Dockerfile \
- --platform=linux/arm64 \
- --build-arg USER_ID=`id -u` \
- --build-arg GROUP_ID=`id -g` \
- --output type=local,dest=ubuntu-arm64 \
- .
diff --git a/Yubico.NativeShims/build-windows.cmd b/Yubico.NativeShims/build-windows.cmd
deleted file mode 100644
index 92aebfc8..00000000
--- a/Yubico.NativeShims/build-windows.cmd
+++ /dev/null
@@ -1,25 +0,0 @@
-:: Update to latest vcpkg baseline
-pushd %VCPKG_INSTALLATION_ROOT%
-git checkout master
-git restore .
-git pull
-vcpkg x-update-baseline
-popd
-
-:: 32-bit builds
-cmake -S . -B build32 -A Win32 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x86-windows-static
-cmake --build build32 --config Release
-mkdir win-x86
-copy build32\Release\Yubico.NativeShims.dll win-x86
-
-:: 64-bit builds
-cmake -S . -B build64 -A x64 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
-cmake --build build64 --config Release
-mkdir win-x64
-copy build64\Release\Yubico.NativeShims.dll win-x64
-
-:: ARM64 builds
-cmake -S . -B buildarm -A arm64 -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=arm64-windows-static
-cmake --build buildarm --config Release
-mkdir win-arm64
-copy buildarm\Release\Yubico.NativeShims.dll win-arm64
\ No newline at end of file
diff --git a/Yubico.NativeShims/build-windows.ps1 b/Yubico.NativeShims/build-windows.ps1
new file mode 100644
index 00000000..94817659
--- /dev/null
+++ b/Yubico.NativeShims/build-windows.ps1
@@ -0,0 +1,25 @@
+# Update to latest vcpkg baseline
+Push-Location $env:VCPKG_INSTALLATION_ROOT
+git checkout master
+git restore .
+git pull
+vcpkg x-update-baseline
+Pop-Location
+
+# 32-bit builds
+cmake -S . -B build32 -A Win32 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=x86-windows-static
+cmake --build build32 --config Release
+mkdir win-x86
+Copy-Item build32\Release\Yubico.NativeShims.dll win-x86
+
+# 64-bit builds
+cmake -S . -B build64 -A x64 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=x64-windows-static
+cmake --build build64 --config Release
+mkdir win-x64
+Copy-Item build64\Release\Yubico.NativeShims.dll win-x64
+
+# ARM64 builds
+cmake -S . -B buildarm -A arm64 -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=arm64-windows-static
+cmake --build buildarm --config Release
+mkdir win-arm64
+Copy-Item buildarm\Release\Yubico.NativeShims.dll win-arm64
\ No newline at end of file
diff --git a/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake b/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake
new file mode 100644
index 00000000..3895a361
--- /dev/null
+++ b/Yubico.NativeShims/cmake/aarch64-linux-gnu.toolchain.cmake
@@ -0,0 +1,7 @@
+set(CMAKE_SYSTEM_NAME Linux)
+set(CMAKE_SYSTEM_PROCESSOR aarch64)
+
+set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
+set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
+
+set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
\ No newline at end of file
diff --git a/Yubico.NativeShims/docker/Ubuntu/Dockerfile b/Yubico.NativeShims/docker/Ubuntu/Dockerfile
deleted file mode 100644
index c8290a62..00000000
--- a/Yubico.NativeShims/docker/Ubuntu/Dockerfile
+++ /dev/null
@@ -1,86 +0,0 @@
-# We use Bionic as the basis for our image. Bionic is the last Ubuntu long-term support
-# release that is both still supported and still supports i386 processors. Once Bionic
-# leaves support, we can consider upgrading to the next LTS release.
-FROM ubuntu:bionic AS env
-
-# These arguments are passed in from the console or by Docker-CLI itself. User/Group ID
-# is used to run the shell as the host's user identity. Artifact_dir should be set to
-# the NuGet runtime-id for this platform (e.g. ubuntu-x64) to aid in artifact discovery
-# in the GitHub Action workflow.
-ARG USER_ID
-ARG GROUP_ID
-ARG ARTIFACT_DIR
-
-# Set up basic environment variables such as the path.
-ENV PATH=/usr/local/bin:$PATH
-
-# Add the host user and group to the image.
-RUN groupadd -f -g ${GROUP_ID} local && useradd -u ${USER_ID} -g ${GROUP_ID} -s /bin/sh local
-
-# Install build tools
-RUN apt-get update -qq \
-&& DEBIAN_FRONTEND=noninteractive apt-get install -yq \
- wget \
- ca-certificates \
- gnupg \
- software-properties-common \
- build-essential \
- pkg-config \
- ninja-build \
-&& apt-get clean \
-&& rm -rf /var/lib/apt/lists/* /tmp/* /var/temp/*
-
-# Install latest CMake
-# Ubuntu Bionic contains a very old version of CMake (3.10). Our project requires a newer
-# version of the tool. This is the easiest way to update CMake using the official builds
-# from Kitware (makers of CMake).
-RUN apt-get update -qq \
-&& wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | apt-key add - \
-&& add-apt-repository 'deb https://apt.kitware.com/ubuntu/ bionic main' \
-&& apt-get update -qq \
-&& apt-get install cmake -yq \
-&& cmake -version
-
-# Install build dependencies
-# This is where we should add any additional dependencies needed by Yubico.NativeShims.
-# We could use vcpkg to help with dependencies, but for Linux, the distro's package
-# manager is still almost always going to be the easiest way of finding the necessary
-# headers and pre-built libraries. Be sure to use the -dev packages, as these typically
-# denote the package that contains headers and libs.
-RUN apt-get update -qq \
-&& apt-get install -yq \
- libpcsclite-dev \
- libssl-dev
-
-# Snapshot the base environment. If we ever decide to cache our images in a container
-# registry, `env` is the target we'd want to capture. The dependencies will be installed
-# but we have not yet copied the source code to build into the image. That happens in
-# this (devel) stage.
-FROM env AS devel
-# Let's work out of a folder that's out of the way on the filesystem.
-WORKDIR /home/build
-# Copy the host context (source code) into the image. See the notes in the shell script
-# that invokes Docker to see the other end of specifying the context. Copies all of the
-# host context (recursively) into the current working dir in the Docker image.
-COPY . .
-RUN rm -rf artifacts
-
-# Build the Yubico.NativeShims shared object
-# Now we take the `devel` target, and fork another image for building. This way, we can
-# quickly roll back a failed build and retry (or try interactively). Put all of the
-# build instructions in this stage. For now, this simply means generating the CMake
-# cache, and building using CMake. We move the build artifacts into a well known
-# location to help the artifact stage.
-FROM devel AS build
-RUN cmake -S . -B build_out -DCMAKE_BUILD_TYPE=Release
-RUN cmake --build build_out --target all -v
-RUN mkdir -p /home/build/artifacts/$ARTIFACT_DIR \
-&& cp /home/build/build_out/*.so /home/build/artifacts/$ARTIFACT_DIR
-
-# Copy over the build artifacts to a blank image. This way we can easily retrieve the
-# build results without copying all of the previous image's filesystem. `Scratch` is
-# a completely blank image. We then use the `COPY` instruction to pull only the files
-# we care about into this blank space. The `--output` argument to the `docker` command
-# specifies what we do with this result.
-FROM scratch AS build_install
-COPY --from=build /home/build/artifacts/$ARTIFACT_DIR/ .
diff --git a/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets b/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets
index 0be8b18a..89de7cac 100644
--- a/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets
+++ b/Yubico.NativeShims/msbuild/Yubico.NativeShims.targets
@@ -1,8 +1,12 @@
-
+ Since .NET Framework is Windows only, we only need to worry about that platform.
+ -->
+
+
Yubico.NativeShims.dll
@@ -10,6 +14,8 @@
false
+
+
Yubico.NativeShims.dll
@@ -17,6 +23,8 @@
false
+
+
Yubico.NativeShims.dll
diff --git a/Yubico.NativeShims/pcsc.c b/Yubico.NativeShims/pcsc.c
index 1bf6c148..5f580dd0 100644
--- a/Yubico.NativeShims/pcsc.c
+++ b/Yubico.NativeShims/pcsc.c
@@ -26,7 +26,7 @@ typedef struct
#pragma pack()
-int32_t
+uint32_t
NATIVEAPI
Native_SCardEstablishContext(
uint32_t dwScope,
@@ -41,7 +41,7 @@ Native_SCardEstablishContext(
);
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardReleaseContext(
SCARDCONTEXT hContext
@@ -50,7 +50,7 @@ Native_SCardReleaseContext(
return SCardReleaseContext(hContext);
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardConnect(
SCARDCONTEXT hContext,
@@ -74,7 +74,7 @@ Native_SCardConnect(
return status;
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardReconnect(
SCARDHANDLE hCard,
@@ -96,7 +96,7 @@ Native_SCardReconnect(
return status;
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardDisconnect(
SCARDHANDLE hCard,
@@ -109,7 +109,7 @@ Native_SCardDisconnect(
);
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardBeginTransaction(
SCARDHANDLE hCard
@@ -118,7 +118,7 @@ Native_SCardBeginTransaction(
return SCardBeginTransaction(hCard);
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardEndTransaction(
SCARDHANDLE hCard,
@@ -131,7 +131,7 @@ Native_SCardEndTransaction(
);
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardGetStatusChange(
SCARDCONTEXT hContext,
@@ -158,7 +158,7 @@ Native_SCardGetStatusChange(
memcpy(readerStates[i].rgbAtr, rgReaderStates[i].rgbAtr, sizeof(readerStates[i].rgbAtr));
}
- int32_t result = SCardGetStatusChange(
+ uint32_t result = SCardGetStatusChange(
hContext,
dwTimeout,
readerStates,
@@ -178,7 +178,7 @@ Native_SCardGetStatusChange(
return result;
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardTransmit(
SCARDHANDLE hCard,
@@ -204,7 +204,7 @@ Native_SCardTransmit(
return status;
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardListReaders(
SCARDCONTEXT hContext,
@@ -224,7 +224,7 @@ Native_SCardListReaders(
return status;
}
-int32_t
+uint32_t
NATIVEAPI
Native_SCardCancel(
SCARDCONTEXT hContext
diff --git a/Yubico.NativeShims/ssl.cmac.c b/Yubico.NativeShims/ssl.cmac.c
index fbbcc464..23647124 100644
--- a/Yubico.NativeShims/ssl.cmac.c
+++ b/Yubico.NativeShims/ssl.cmac.c
@@ -1,9 +1,6 @@
#include "native_abi.h"
#include "Yubico.NativeShims.h"
#include "openssl/evp.h"
-#ifdef PLATFORM_LINUX
-#include "openssl/cmac.h"
-#endif
#define CMAC_MAX_BLOCK_SIZE 16
typedef void* Native_EVP_MAC_CTX;
@@ -12,7 +9,6 @@ Native_EVP_MAC_CTX
NATIVEAPI
Native_CMAC_EVP_MAC_CTX_new()
{
-#ifndef PLATFORM_LINUX
EVP_MAC *mac = NULL;
EVP_MAC_CTX *macCtx = NULL;
@@ -24,9 +20,7 @@ Native_CMAC_EVP_MAC_CTX_new()
}
return macCtx;
-#else
- return CMAC_CTX_new();
-#endif
+
}
void
@@ -35,11 +29,7 @@ Native_EVP_MAC_CTX_free(
Native_EVP_MAC_CTX c
)
{
-#ifndef PLATFORM_LINUX
EVP_MAC_CTX_free(c);
-#else
- CMAC_CTX_free(c);
-#endif
}
int32_t
@@ -51,7 +41,6 @@ Native_CMAC_EVP_MAC_init(
int32_t keyLen
)
{
-#ifndef PLATFORM_LINUX
char *cipherString;
int32_t cipherStringLen;
int32_t blockSize;
@@ -88,26 +77,7 @@ Native_CMAC_EVP_MAC_init(
};
return EVP_MAC_init(c, keyData, keyLen, params);
-#else
- EVP_CIPHER *evpCipher;
-
- switch (algorithm)
- {
- default:
- evpCipher = EVP_aes_128_cbc();
- break;
-
- case 2:
- evpCipher = EVP_aes_192_cbc();
- break;
- case 3:
- evpCipher = EVP_aes_256_cbc();
- break;
- }
-
- return CMAC_Init(c, keyData, keyLen, evpCipher, NULL);
-#endif
}
int32_t
@@ -118,11 +88,7 @@ Native_CMAC_EVP_MAC_update(
int32_t inLen
)
{
-#ifndef PLATFORM_LINUX
return EVP_MAC_update(c, input, inLen);
-#else
- return CMAC_Update(c, input, inLen);
-#endif
}
int32_t
@@ -136,11 +102,8 @@ Native_CMAC_EVP_MAC_final(
{
int status;
size_t outputLen = (size_t)outputSize;
-#ifndef PLATFORM_LINUX
status = EVP_MAC_final(c, output, &outputLen, outputSize);
-#else
- status = CMAC_Final(c, output, &outputLen);
-#endif
+
*outLen = (int32_t)outputLen;
return status;
}
diff --git a/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md b/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md
index 8305a50a..dfbc8e7c 100644
--- a/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md
+++ b/Yubico.YubiKey/docs/users-manual/getting-started/overview-of-sdk.md
@@ -44,7 +44,7 @@ in the standard but not actually implemented in Framework 4.6.x.
| ---- | ---- | ---- |
| macOS | x64, arm64 | Catalina, Big Sur |
| Windows | x86, x64, arm64 | Windows 10, Windows 11 |
-| Linux | x86, x64, arm64 | Debian, Ubuntu, RHEL, CentOS |
+| Linux | x64, arm64 | Debian, Ubuntu, RHEL, CentOS |
## Supported YubiKey applications
diff --git a/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md b/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md
index a9fc80f1..44f20b48 100644
--- a/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md
+++ b/Yubico.YubiKey/docs/users-manual/getting-started/whats-new.md
@@ -15,7 +15,43 @@ limitations under the License. -->
# What's new in the SDK?
Here you can find all of the updates and release notes for published versions of the SDK.
-
+## 1.10.x Releases
+
+### 1.10.0
+
+Release date: April 10th, 2024
+
+This is a release aimed to address inconsistencies in dependencies (OpenSSL), compiler warnings and hardening. The objective of compiler options hardening is to produce application binaries (executables) with security mechanisms against potential attacks and/or misbehavior. is to produce application binaries (executables) with security mechanisms against potential attacks and/or misbehavior.
+
+This release improves our native dependencies exposed through the `Yubico.NativeShims` package. We have also worked to improve the build and test experience of this repository by improving our automation and build files.
+
+Changes:
+- **Yubico.NativeShims targets OpenSSL version 3.x on all platforms** - OpenSSL v1.1.x has reached end-of-life. The SDK now removes this dependency on all platforms, now upgrading to the supported 3.x version.
+- **Dropped support for 32-bit Linux** - Yubico.NativeShims no longer builds for 32-bit (x86) Linux. We now depend on Ubuntu releases that contain OpenSSL 3.x by default. These newer releases no longer have mainstream support for this platform.
+- **[Compilation hardening of Yubico.NativeShims](https://github.com/Yubico/Yubico.NET.SDK/pull/67)** - Added commonly used compiler flags to increase security and code quality
+ **MacOS / Linux:**
+ -Wformat: Warn about format string issues in printf-like functions.
+ -Wformat-nonliteral: Warn about format strings that are not string literals.
+ -Wformat-security: Warn about potential security issues related to format strings.
+ -Wall: Enable most warning messages
+ -Wextra: Enable some additional warning messages not included in -Wall
+ -Werror: Treat all warnings as errors
+ -Wcast-qual: Warn when casting away const-ness
+ -Wshadow: Warn when a local variable shadows another variable
+ -pedantic: Issue warnings for language features beyond the C standard
+ -pedantic-errors: Treat pedantic warnings as errors
+ -Wbad-function-cast: Warn about dubious function pointer casts
+ -O2: Optimize code for performance
+ -fpic: Generate position-independent code
+ -fstack-protector-all: Enable stack protection for all functions
+ -D_FORTIFY_SOURCE=2: Enable runtime and compile-time checks for certain security-critical functions
+ **Windows flags:**
+ /guard:cf: Enable control flow guard security feature
+ /GS: Enable buffer security check
+ /Gs: Control stack security check
+- [Addressed compiler warning concerning Runtime Identifiers (RID) ](https://github.com/Yubico/Yubico.NET.SDK/issues/59)
+- **Enabled `dotnet format`** - The repository now uses `dotnet format` to ensure that pull requests adhere to the repository's coding standards. A pass of the tool has been run against the entire repository and a new baseline has been checked in.
+
## 1.9.x Releases
### 1.9.1
diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs b/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs
index ecc73524..890c491d 100644
--- a/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs
+++ b/Yubico.YubiKey/examples/Fido2SampleCode/KeyCollector/Fido2SampleKeyCollector.cs
@@ -24,16 +24,16 @@ namespace Yubico.YubiKey.Sample.Fido2SampleCode
// This sample key collector is specifically built for FIDO2 only.
public class Fido2SampleKeyCollector
{
- // This allows the caller to specify what the operation is.
- // Some messages (such as Touch) can contain more information if this is
- // known.
- public Fido2KeyCollectorOperation Operation { get; set; }
-
public Fido2SampleKeyCollector()
{
Operation = Fido2KeyCollectorOperation.None;
}
+ // This allows the caller to specify what the operation is.
+ // Some messages (such as Touch) can contain more information if this is
+ // known.
+ public Fido2KeyCollectorOperation Operation { get; set; }
+
public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
{
if (keyEntryData is null)
@@ -41,17 +41,20 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
return false;
}
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
SampleMenu.WriteMessage(MessageType.Title, 0, "A previous entry was incorrect, do you want to retry?");
if (!(keyEntryData.RetriesRemaining is null))
{
- string retryString = ((int)keyEntryData.RetriesRemaining).ToString("D", CultureInfo.InvariantCulture);
- SampleMenu.WriteMessage(MessageType.Title, 0, "(retries remainin until blocked: " + retryString + ")");
+ string retryString =
+ ((int)keyEntryData.RetriesRemaining).ToString("D", CultureInfo.InvariantCulture);
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "(retries remainin until blocked: " + retryString + ")");
}
+
SampleMenu.WriteMessage(MessageType.Title, 0, "y/n");
char[] answer = SampleMenu.ReadResponse(out int _);
- if ((answer.Length == 0) || ((answer[0] != 'y') && (answer[0] != 'Y')))
+ if (answer.Length == 0 || (answer[0] != 'y' && answer[0] != 'Y'))
{
return false;
}
@@ -70,18 +73,22 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
case KeyEntryRequest.TouchRequest:
ReportOperation();
- SampleMenu.WriteMessage(MessageType.Title, 0, "touch the YubiKey's contact to complete the operation.\n");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "touch the YubiKey's contact to complete the operation.\n");
return true;
case KeyEntryRequest.EnrollFingerprint:
if (!(keyEntryData.LastBioEnrollSampleResult is null))
{
string lastResult = keyEntryData.LastBioEnrollSampleResult.LastEnrollSampleStatus.ToString();
- SampleMenu.WriteMessage(MessageType.Title, 0, " Sample result: " + lastResult);
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ " Sample result: " + lastResult);
SampleMenu.WriteMessage(
MessageType.Title, 0,
- "Number of good samples still needed: " + keyEntryData.LastBioEnrollSampleResult.RemainingSampleCount);
+ "Number of good samples still needed: " +
+ keyEntryData.LastBioEnrollSampleResult.RemainingSampleCount);
}
+
SampleMenu.WriteMessage(MessageType.Title, 0, "\nPlease provide a fingerprint sample.\n");
return true;
@@ -91,7 +98,8 @@ public virtual bool Fido2SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
return true;
case KeyEntryRequest.SetFido2Pin:
- SampleMenu.WriteMessage(MessageType.Title, 0, "Setting the FIDO2 application's PIN, enter the PIN.");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "Setting the FIDO2 application's PIN, enter the PIN.");
collectedValue = SampleMenu.ReadResponse(out int _);
pinValue = ConvertCharArrayToByteArray(collectedValue);
keyEntryData.SubmitValue(pinValue);
@@ -142,7 +150,8 @@ private void ReportOperation()
break;
case Fido2KeyCollectorOperation.Reset:
- SampleMenu.WriteMessage(MessageType.Title, 0, "\nThe YubiKey is trying to reset the FIDO2 application,");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "\nThe YubiKey is trying to reset the FIDO2 application,");
break;
}
}
diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs
index c0ac93c7..f7d830a2 100644
--- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs
+++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs
@@ -13,11 +13,11 @@
// limitations under the License.
#if WINDOWS
using System;
-using System.Windows.Forms;
using System.Drawing;
+using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
-using System.Security.Cryptography;
+using System.Windows.Forms;
using Yubico.YubiKey;
using Yubico.YubiKey.Sample.SharedCode;
@@ -44,7 +44,7 @@ public Fido2SampleGui()
public void RunSample()
{
using var tokenSource = new CancellationTokenSource();
- var sampleRunTask = Task.Run( () => CreateSampleRunThread(), tokenSource.Token);
+ var sampleRunTask = Task.Run(() => CreateSampleRunThread(), tokenSource.Token);
_ = _parentForm.ShowDialog();
tokenSource.Cancel();
}
@@ -125,7 +125,7 @@ public ParentForm()
{
Answered = true;
Text = "FIDO2 Sample";
- Size = new Size(600,660);
+ Size = new Size(600, 660);
MaximizeBox = false;
MinimizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
@@ -331,7 +331,7 @@ public class PinPopupForm : Form
public PinPopupForm(string message)
{
Text = "User Action Required";
- Size = new Size(400,400);
+ Size = new Size(400, 400);
MaximizeBox = false;
MinimizeBox = false;
ControlBox = true;
@@ -399,7 +399,7 @@ public PinPopupForm(string message)
protected override void OnShown(EventArgs e)
{
- _ = (_state < 3) ? _pinBox.Focus() : _newPinBox.Focus();
+ _ = _state < 3 ? _pinBox.Focus() : _newPinBox.Focus();
}
private void OkButton_Click(object sender, EventArgs e)
@@ -468,7 +468,7 @@ private int UpdatePinBox(KeyEventArgs e, Span pinBuffer, int currentLen)
return 0;
}
- if ((e.KeyValue < 0x21) || (e.KeyValue > 0x7E) || (currentLen >= 63))
+ if (e.KeyValue < 0x21 || e.KeyValue > 0x7E || currentLen >= 63)
{
EndPinPopup(DialogResult.Retry);
return 0;
@@ -571,7 +571,7 @@ public class FpTouchPopupForm : Form
public FpTouchPopupForm(string message)
{
Text = "User Action Required";
- Size = new Size(400,400);
+ Size = new Size(400, 400);
MaximizeBox = false;
MinimizeBox = false;
ControlBox = true;
@@ -644,4 +644,4 @@ protected override void Dispose(bool disposing)
}
#pragma warning restore CA1303
}
-#endif
\ No newline at end of file
+#endif
diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs
index a6cfae1f..d28fbbad 100644
--- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs
+++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs
@@ -13,16 +13,16 @@
// limitations under the License.
using System;
-using System.Text;
using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
using System.Security.Cryptography;
-using Yubico.YubiKey.Sample.SharedCode;
+using System.Text;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2;
using Yubico.YubiKey.Fido2.Commands;
using Yubico.YubiKey.Fido2.Cose;
-using System.Globalization;
-using System.Linq;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.Fido2SampleCode
{
@@ -34,8 +34,8 @@ public partial class Fido2SampleRun
{
public bool RunMenuItem(Fido2MainMenuItem menuItem)
{
- if ((menuItem >= Fido2MainMenuItem.MakeCredential)
- &&(menuItem < Fido2MainMenuItem.Reset))
+ if (menuItem >= Fido2MainMenuItem.MakeCredential
+ && menuItem < Fido2MainMenuItem.Reset)
{
SampleMenu.WriteMessage(
MessageType.Title, 0,
@@ -720,7 +720,7 @@ public bool RunDeleteLargeBlobData()
CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount);
- if ((userInfo is null) || (userInfo.LargeBlobKey is null))
+ if (userInfo is null || userInfo.LargeBlobKey is null)
{
SampleMenu.WriteMessage(
MessageType.Title, 0,
@@ -1194,7 +1194,7 @@ private int FindCredential(ReadOnlyMemory credentialId)
}
}
- return (index < _credentialList.Count) ? index : -1;
+ return index < _credentialList.Count ? index : -1;
}
// This does not build a real ClientDataHash. It builds something that
@@ -1490,7 +1490,7 @@ private static void ReportCredential(
}
if (largeBlobReport)
{
- string lbKeyStatus = (userInfo.LargeBlobKey is null) ? "not available" : "available";
+ string lbKeyStatus = userInfo.LargeBlobKey is null ? "not available" : "available";
SampleMenu.WriteMessage(MessageType.Title, 0, " Large Blob Key: " + lbKeyStatus);
SampleMenu.WriteMessage(MessageType.Title, 0, "-----------");
}
diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs
index 7a079f59..86467759 100644
--- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs
+++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System.Collections.Generic;
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Fido2;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.Fido2SampleCode
{
diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs
index 6654fda6..653b3839 100644
--- a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs
+++ b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Text;
-using System.Linq;
using System.Collections.Generic;
+using System.Linq;
using System.Security.Cryptography;
+using System.Text;
using Yubico.YubiKey.Fido2;
using Yubico.YubiKey.Fido2.Commands;
diff --git a/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs b/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs
index f0a77493..6c5efe06 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/KeyCollector/SampleKeyCollector.cs
@@ -21,7 +21,7 @@ namespace Yubico.YubiKey.Sample.OathSampleCode
// This KeyCollector is not secure. It simply asks for the user to enter password at the keyboard,
// with no hiding.
public static class SampleKeyCollector
- {
+ {
// This is the callback. When the SDK needs a password,
// this is the method that will be called.
public static bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
diff --git a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs
index af341283..6caea741 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Oath;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.OathSampleCode
{
@@ -224,7 +224,7 @@ private bool RunRenameCredentialMenuItem(int? index)
_yubiKeyChosen,
SampleKeyCollector.SampleKeyCollectorDelegate,
_credentialChosen,
- "Yubico",
+ "Yubico",
"testRename@example.com");
}
else
diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs
index ee18e061..a449e443 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs
@@ -15,8 +15,8 @@
using System;
using System.Globalization;
using System.Text;
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Oath;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.OathSampleCode
{
@@ -266,7 +266,8 @@ private static Credential CollectTotpCredential(SampleMenu menuObject)
SampleMenu.WriteMessage(MessageType.Title, 0, "Set require touch property? Answer Yes or No.");
_ = SampleMenu.ReadResponse(out string touch);
- var credential = new Credential {
+ var credential = new Credential
+ {
Issuer = issuer,
AccountName = account,
Type = CredentialType.Totp,
diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs
index 36382a47..4a15bda0 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs
@@ -56,7 +56,7 @@ public static bool RunCalculateOneCredential(
return true;
}
- private static void ReportAllResults(IDictionary credentials)
+ private static void ReportAllResults(IDictionary credentials)
{
// Are there any?
var outputList = new StringBuilder("");
diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs
index 7f5c94bb..ed01b25a 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs
@@ -53,7 +53,7 @@ public static bool RunChooseCredential(
return false;
}
- if ((credentials.Count == 1) && (alwaysAsk == false))
+ if (credentials.Count == 1 && alwaysAsk == false)
{
chosenCredential = credentials[0];
return true;
@@ -68,7 +68,7 @@ public static bool RunChooseCredential(
}
int indexChosen = menuObject.RunMenu("Which Credential do you want to use?", choices);
- if ((indexChosen >= 0) && (indexChosen < credentials.Count))
+ if (indexChosen >= 0 && indexChosen < credentials.Count)
{
chosenCredential = credentials[indexChosen];
return true;
@@ -98,7 +98,7 @@ public static bool RunChooseAddCredentialOption(SampleMenu menuObject, out int?
int indexChosen = menuObject.RunMenu("How would you want to add it?", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
index = indexChosen;
return true;
@@ -130,7 +130,7 @@ public static bool RunChooseCredentialOption(SampleMenu menuObject, out int? ind
int indexChosen = menuObject.RunMenu("What kind of credential do you want to add?", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
index = indexChosen;
return true;
@@ -159,7 +159,7 @@ public static bool RunChooseAction(SampleMenu menuObject, out int? index, string
int indexChosen = menuObject.RunMenu("How would you want to " + name + " it?", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
index = indexChosen;
return true;
diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs
index 5c3cd004..072d557a 100644
--- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs
+++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredentialProperties.cs
@@ -36,7 +36,7 @@ public static bool RunChooseTypeOption(SampleMenu menuObject, out CredentialType
int indexChosen = menuObject.RunMenu("Choose credential type", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
type = _types[choices[indexChosen]];
return true;
@@ -60,7 +60,7 @@ public static bool RunChoosePeriodOption(SampleMenu menuObject, out CredentialPe
int indexChosen = menuObject.RunMenu("Choose credential period", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
period = _periods[choices[indexChosen]];
return true;
@@ -85,7 +85,7 @@ public static bool RunChooseAlgorithmOption(SampleMenu menuObject, out HashAlgor
int indexChosen = menuObject.RunMenu("Choose credential algorithm", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
algorithm = _hashAlgorithms[choices[indexChosen]];
return true;
@@ -109,7 +109,7 @@ public static bool RunChooseDigitsOption(SampleMenu menuObject, out int? digits)
int indexChosen = menuObject.RunMenu("Choose the number of digits in OTP code", choices);
- if ((indexChosen >= 0) && (indexChosen < choices.Length))
+ if (indexChosen >= 0 && indexChosen < choices.Length)
{
digits = _digits[choices[indexChosen]];
return true;
diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs
index 58e34bf3..240eb6be 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs
@@ -16,8 +16,8 @@
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
-using Yubico.YubiKey.Piv;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Piv;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
@@ -192,11 +192,11 @@ public static bool GetSignedCert(
// and KeyUsage, and their values are acceptable.
int index = 0;
int count = 2;
- while ((index < signerCert.Extensions.Count) && (count < 2))
+ while (index < signerCert.Extensions.Count && count < 2)
{
if (signerCert.Extensions[index] is X509BasicConstraintsExtension basicConstraints)
{
- if ((!basicConstraints.CertificateAuthority) || (basicConstraints.PathLengthConstraint < pathLength))
+ if (!basicConstraints.CertificateAuthority || basicConstraints.PathLengthConstraint < pathLength)
{
return false;
}
@@ -264,8 +264,8 @@ public static bool GetSignedCert(
// 04
// where each coordinate is exactly 48 bytes (384 bits) long.
HashAlgorithmName signerHash = HashAlgorithmName.SHA256;
- if ((string.Equals(signerCert.PublicKey.Oid.FriendlyName, "ECC", StringComparison.Ordinal))
- && (signerCert.PublicKey.EncodedKeyValue.RawData.Length == 97))
+ if (string.Equals(signerCert.PublicKey.Oid.FriendlyName, "ECC", StringComparison.Ordinal)
+ && signerCert.PublicKey.EncodedKeyValue.RawData.Length == 97)
{
signerHash = HashAlgorithmName.SHA384;
}
@@ -325,14 +325,14 @@ public static bool GetSignedCert(
// Another bit of information to extract from the cert would be the RSA
// padding scheme, if the signature algorithm is RSA. However, to avoid
// writing a lot more code, this sample always uses PSS.
- public static CertificateRequest BuildCertRequestFromDer(byte[] requestDer, HashAlgorithmName signerHash)
- {
- using AsymmetricAlgorithm requestPublicKey = GetComponentsFromCertRequestDer(
- requestDer,
- out byte[] _,
- out SignatureAlgIdConverter _,
- out X500DistinguishedName requestName,
- out byte[] _);
+ public static CertificateRequest BuildCertRequestFromDer(byte[] requestDer, HashAlgorithmName signerHash)
+ {
+ using AsymmetricAlgorithm requestPublicKey = GetComponentsFromCertRequestDer(
+ requestDer,
+ out byte[] _,
+ out SignatureAlgIdConverter _,
+ out X500DistinguishedName requestName,
+ out byte[] _);
if (requestPublicKey is ECDsa ecDsa)
{
diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs
index 491d90c1..f3c675fd 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs
@@ -131,11 +131,11 @@ public X500DistinguishedName GetDistinguishedName()
// the extensions (OID, etc.).
public enum X500NameElement
{
- Country = 0,
- State = 1,
- Locality = 2,
- Organization = 3,
- CommonName = 4,
+ Country = 0,
+ State = 1,
+ Locality = 2,
+ Organization = 3,
+ CommonName = 4,
}
public static class X500NameElementExtensions
@@ -189,22 +189,22 @@ public static byte[] GetDerEncoding(this X500NameElement nameElement, string val
public static byte[] GetOid(this X500NameElement nameElement) => nameElement switch
{
- X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 },
- X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 },
- X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 },
- X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A },
- X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 },
+ X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 },
+ X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 },
+ X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 },
+ X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A },
+ X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 },
_ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage),
};
// Is the given length valid for the specified nameElement?
public static bool IsValidValueLength(this X500NameElement nameElement, int length) => nameElement switch
{
- X500NameElement.Country => length == 2,
- X500NameElement.State => (length > 0) && (length < 32),
- X500NameElement.Locality => (length > 0) && (length < 32),
- X500NameElement.Organization => (length > 0) && (length < 64),
- X500NameElement.CommonName => (length > 0) && (length < 64),
+ X500NameElement.Country => length == 2,
+ X500NameElement.State => length > 0 && length < 32,
+ X500NameElement.Locality => length > 0 && length < 32,
+ X500NameElement.Organization => length > 0 && length < 64,
+ X500NameElement.CommonName => length > 0 && length < 64,
_ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage),
};
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs
index 7446e164..f703bce5 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs
@@ -14,8 +14,8 @@
using System;
using System.Globalization;
-using Yubico.YubiKey.Piv;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Piv;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
@@ -114,7 +114,7 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, PivAlgorith
}
}
- isValid = ((rValue.Length - offsetR) <= elementLength) && ((sValue.Length - offsetS) <= elementLength);
+ isValid = rValue.Length - offsetR <= elementLength && sValue.Length - offsetS <= elementLength;
}
}
}
@@ -150,7 +150,7 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, PivAlgorith
// greater than zero and even.
public static byte[] GetStandardDsaFromNonStandard(byte[] signature)
{
- if ((signature is null) || (signature.Length == 0))
+ if (signature is null || signature.Length == 0)
{
throw new ArgumentNullException(nameof(signature));
}
@@ -191,8 +191,8 @@ public static byte[] GetStandardDsaFromNonStandard(byte[] signature)
// The first half of the buffer is r, the second is s.
// For each element, build an INTEGER: 02 len value.
// If the msBit of value is set, prepend a 00 byte.
- int startR = ((signature[offsetR] & 0x80) != 0) ? 1 : 0;
- int startS = ((signature[offsetS] & 0x80) != 0) ? 1 : 0;
+ int startR = (signature[offsetR] & 0x80) != 0 ? 1 : 0;
+ int startS = (signature[offsetS] & 0x80) != 0 ? 1 : 0;
byte[] rBuffer = new byte[elementLength + 1];
byte[] sBuffer = new byte[elementLength + 1];
diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs
index a450b94c..af1dc20e 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs
@@ -305,7 +305,7 @@ private static byte[] GetEncodedKey(char[] pemKeyString, bool isPrivate, out int
private static int GetNextTagOffset(byte[] buffer, int offset)
{
// Make sure there are enough bytes to read.
- if ((offset < 0) || (buffer.Length < offset + 2))
+ if (offset < 0 || buffer.Length < offset + 2)
{
return -1;
}
@@ -321,7 +321,7 @@ private static int GetNextTagOffset(byte[] buffer, int offset)
// beyond 83). This says the length is the next 1, 2, or 3 octets.
int length = buffer[offset + 1];
int increment = 2;
- if ((length == 0x80) || (length > 0x83))
+ if (length == 0x80 || length > 0x83)
{
return -1;
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs
index 61b94a9a..a9bd9909 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/PemOperations.cs
@@ -185,9 +185,9 @@ private static bool VerifyPemHeaderAndFooter(char[] pemKeyString, string title)
char[] targetStart = (Part1 + title + Part2And4).ToCharArray();
char[] targetEnd = (Part3 + title + Part2And4).ToCharArray();
bool returnValue = false;
- if (pemKeyString.Length > (targetStart.Length + targetEnd.Length))
+ if (pemKeyString.Length > targetStart.Length + targetEnd.Length)
{
- if (CompareToTarget(pemKeyString, 0, targetStart) == true)
+ if (CompareToTarget(pemKeyString, 0, targetStart))
{
returnValue = CompareToTarget(pemKeyString, pemKeyString.Length - targetEnd.Length, targetEnd);
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs
index 2646b0cf..c882196d 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs
@@ -264,7 +264,7 @@ private void ReadPssParams(ReadOnlyMemory algIdParams)
{
if (algIdParams.Length == 2)
{
- if ((algIdParams.Span[0] == 0x30) && (algIdParams.Span[1] == 0))
+ if (algIdParams.Span[0] == 0x30 && algIdParams.Span[1] == 0)
{
PssSaltLength = 20;
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs b/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs
index 2fbf12a2..f1d71021 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/KeyCollector/SampleKeyCollector.cs
@@ -48,7 +48,7 @@ public bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
return false;
}
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
if (!(keyEntryData.RetriesRemaining is null))
{
@@ -90,20 +90,25 @@ public bool SampleKeyCollectorDelegate(KeyEntryData keyEntryData)
break;
case KeyEntryRequest.AuthenticatePivManagementKey:
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
return false;
}
- currentValue = CollectValue(DefaultMgmtKeyString, "Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
+
+ currentValue = CollectValue(DefaultMgmtKeyString,
+ "Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
break;
case KeyEntryRequest.ChangePivManagementKey:
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
return false;
}
- currentValue = CollectValue(DefaultMgmtKeyString, "Current Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
- newValue = CollectValue(DefaultMgmtKeyString, "New Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
+
+ currentValue = CollectValue(DefaultMgmtKeyString,
+ "Current Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
+ newValue = CollectValue(DefaultMgmtKeyString,
+ "New Management Key (24 bytes in hex, e.g. A1 29 07... or A12907...)");
break;
}
@@ -128,7 +133,8 @@ private bool GetUserInputOnRetries(KeyEntryData keyEntryData)
}
string title = keyEntryData.RetriesRemaining + " tries remaining, continue?";
- string[] menuItems = new string[] {
+ string[] menuItems = new string[]
+ {
"Yes, try again",
"No, cancel operation"
};
@@ -146,13 +152,14 @@ public static byte[] CollectValue(string defaultValueString, string name)
SampleMenu.WriteMessage(MessageType.Title, 0, "Enter D for default value (" + defaultValueString + ")");
char[] collectedValue = SampleMenu.ReadResponse(out int _);
- if ((collectedValue.Length == 1) && (collectedValue[0] == 'D'))
+ if (collectedValue.Length == 1 && collectedValue[0] == 'D')
{
return defaultValueString switch
{
DefaultPinString => new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 },
DefaultPukString => new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 },
- DefaultMgmtKeyString => new byte[] {
+ DefaultMgmtKeyString => new byte[]
+ {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
@@ -188,6 +195,7 @@ private static byte[] ConvertCharArrayToByteArray(string valueType, char[] value
break;
}
}
+
indexV++;
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs
index 200719bf..32dd7c64 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs
@@ -14,10 +14,10 @@
using System;
using System.Linq;
-using Yubico.YubiKey.Sample.SharedCode;
-using Yubico.YubiKey.Piv;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
+using Yubico.YubiKey.Piv;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
@@ -178,7 +178,7 @@ public bool RunRecoverPinOnlyMode()
SampleMenu.WriteMessage(MessageType.Title, 0, "overwritten. The result is the PivPinOnly mode of the YubiKey");
SampleMenu.WriteMessage(MessageType.Title, 0, "after recovery.\n");
if (PinOnlyMode.RunRecoverPivPinOnlyMode(
- _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, out PivPinOnlyMode mode))
+ _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, out PivPinOnlyMode mode))
{
SampleMenu.WriteMessage(MessageType.Title, 0, "PIN-only mode: " + mode.ToString() + "\n");
return true;
@@ -661,7 +661,7 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber)
{
return false;
}
- if ((valueChars[0] != '8') && (valueChars[0] != '9'))
+ if (valueChars[0] != '8' && valueChars[0] != '9')
{
return false;
}
@@ -672,13 +672,13 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber)
hiVal = (byte)((hiVal - subVal) << 4);
- if ((valueChars[1] < '0') || (valueChars[1] > '9'))
+ if (valueChars[1] < '0' || valueChars[1] > '9')
{
subVal = 0x37;
- if ((valueChars[1] < 'A') || (valueChars[1] > 'F'))
+ if (valueChars[1] < 'A' || valueChars[1] > 'F')
{
subVal = 0x57;
- if ((valueChars[1] < 'a') || (valueChars[1] > 'f'))
+ if (valueChars[1] < 'a' || valueChars[1] > 'f')
{
return false;
}
@@ -688,11 +688,11 @@ private static bool GetAsymmetricSlotNumber(out byte slotNumber)
loVal -= subVal;
slotNumber = (byte)(hiVal + loVal);
- if ((slotNumber < 0x82) || (slotNumber > 0x9E))
+ if (slotNumber < 0x82 || slotNumber > 0x9E)
{
return false;
}
- if ((slotNumber > 0x95) && (slotNumber < 0x9A))
+ if (slotNumber > 0x95 && slotNumber < 0x9A)
{
return false;
}
@@ -769,12 +769,12 @@ private static bool GetNewRetryCounts(out byte newRetryCountPin, out byte newRet
SampleMenu.WriteMessage(MessageType.Title, 0, "PIN retry count? (1 to 255)");
_ = SampleMenu.ReadResponse(out int response);
- if ((response != 0) && (response <= 255))
+ if (response != 0 && response <= 255)
{
newRetryCountPin = (byte)response;
SampleMenu.WriteMessage(MessageType.Title, 0, "PUK retry count? (1 to 255)");
_ = SampleMenu.ReadResponse(out response);
- if ((response != 0) && (response <= 255))
+ if (response != 0 && response <= 255)
{
newRetryCountPuk = (byte)response;
return true;
diff --git a/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs b/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs
index b9613390..5ec0c8b2 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/SlotContents/SamplePivSlotContents.cs
@@ -14,8 +14,8 @@
using System;
using System.Security.Cryptography.X509Certificates;
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Piv;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs
index 3e663d89..6b16cabe 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/ChangeSecret.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Piv;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs
index f189b39c..cc04d5a1 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using Yubico.YubiKey.Piv;
using System.Security.Cryptography.X509Certificates;
+using Yubico.YubiKey.Piv;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
@@ -41,10 +41,10 @@ public static bool RunGenerateKeyPair(
slotContents = new SamplePivSlotContents()
{
SlotNumber = slotNumber,
- Algorithm = algorithm,
- PinPolicy = pinPolicy,
- TouchPolicy = touchPolicy,
- PublicKey = pivPublicKey,
+ Algorithm = algorithm,
+ PinPolicy = pinPolicy,
+ TouchPolicy = touchPolicy,
+ PublicKey = pivPublicKey,
};
}
diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs
index f026f68c..c3c67e4e 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PinOnlyMode.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.Piv;
+using Yubico.YubiKey.Sample.SharedCode;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs
index 0bce1ae5..1da57695 100644
--- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs
+++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/PrivateKeyOperations.cs
@@ -14,8 +14,8 @@
using System;
using System.Security.Cryptography;
-using Yubico.YubiKey.Piv;
using Yubico.YubiKey.Cryptography;
+using Yubico.YubiKey.Piv;
namespace Yubico.YubiKey.Sample.PivSampleCode
{
@@ -94,7 +94,7 @@ public static bool RunSignData(
digest = RsaFormat.FormatPkcs1Sign(digest, digestAlgorithm, keySizeBits);
}
}
-
+
using (var pivSession = new PivSession(yubiKey))
{
pivSession.KeyCollector = KeyCollectorDelegate;
@@ -167,11 +167,11 @@ public static bool RunKeyAgree(
PivPublicKey correspondentPublicKey,
out byte[] computedSecret)
{
- using (var pivSession = new PivSession(yubiKey))
- {
- pivSession.KeyCollector = KeyCollectorDelegate;
- computedSecret = pivSession.KeyAgree(slotNumber, correspondentPublicKey);
- }
+ using (var pivSession = new PivSession(yubiKey))
+ {
+ pivSession.KeyCollector = KeyCollectorDelegate;
+ computedSecret = pivSession.KeyAgree(slotNumber, correspondentPublicKey);
+ }
return true;
}
diff --git a/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs b/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs
index 88aa4545..1fa23605 100644
--- a/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs
+++ b/Yubico.YubiKey/examples/SharedSampleCode/Menu/SampleMenu.cs
@@ -55,7 +55,7 @@ public class SampleMenu
public SampleMenu(int maxInvalidCount, Type mainMenuEnumType, int exitValue)
{
_maxInvalidCount = DefaultMaxInvalidCount;
- if ((maxInvalidCount >= LowMaxInvalidCount) && (maxInvalidCount <= HighMaxInvalidCount))
+ if (maxInvalidCount >= LowMaxInvalidCount && maxInvalidCount <= HighMaxInvalidCount)
{
_maxInvalidCount = maxInvalidCount;
}
@@ -75,7 +75,7 @@ public SampleMenu(int maxInvalidCount, Type mainMenuEnumType, int exitValue)
public int RunMainMenu(string title)
{
int indexChosen = RunMenu(title, _mainMenuStrings);
- if ((indexChosen >= 0) && (indexChosen < _mainMenuStrings.Length))
+ if (indexChosen >= 0 && indexChosen < _mainMenuStrings.Length)
{
object? returnValue = _mainMenuValues.GetValue(indexChosen);
if (!(returnValue is null))
@@ -118,7 +118,7 @@ public int RunMenu(string title, string[] menuItems)
}
_ = ReadResponse(out int response);
- if ((response > 0) && (response <= menuItems.Length))
+ if (response > 0 && response <= menuItems.Length)
{
// When writing the menu, counting begins at 1. So to get the
// index of the choice, subtract 1.
diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs
index 905d78e2..072e4199 100644
--- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs
+++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs
@@ -14,8 +14,8 @@
using System;
using System.Collections.Generic;
-using System.Linq;
using System.Globalization;
+using System.Linq;
namespace Yubico.YubiKey.Sample.SharedCode
{
@@ -84,7 +84,7 @@ public static bool RunChooseYubiKey(
for (int index = 0; index < yubiKeyArray.Length; index++)
{
if (!(yubiKeyArray[index].SerialNumber is null)
- && (yubiKeyChosen.SerialNumber == yubiKeyArray[index].SerialNumber))
+ && yubiKeyChosen.SerialNumber == yubiKeyArray[index].SerialNumber)
{
return true;
}
@@ -96,7 +96,7 @@ public static bool RunChooseYubiKey(
// return value to null.
yubiKeyChosen = null;
- if ((yubiKeyArray.Length == 1) && (alwaysAsk == false))
+ if (yubiKeyArray.Length == 1 && alwaysAsk == false)
{
yubiKeyChosen = yubiKeyArray[0];
return true;
@@ -112,7 +112,7 @@ public static bool RunChooseYubiKey(
}
int indexChosen = menuObject.RunMenu("Which YubiKey do you want to use?", choices);
- if ((indexChosen >= 0) && (indexChosen < yubiKeyArray.Length))
+ if (indexChosen >= 0 && indexChosen < yubiKeyArray.Length)
{
yubiKeyChosen = yubiKeyArray[indexChosen];
return true;
diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs
index 4fc35fcb..ff0b8004 100644
--- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs
+++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System.Collections.Generic;
-using System.Linq;
using System.Globalization;
+using System.Linq;
using Yubico.YubiKey;
namespace Yubico.YubiKey.Sample.SharedCode
diff --git a/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs b/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs
index c2dc50f7..ec4a97d2 100644
--- a/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs
+++ b/Yubico.YubiKey/examples/U2fSampleCode/KeyCollector/U2fSampleKeyCollector.cs
@@ -24,16 +24,16 @@ namespace Yubico.YubiKey.Sample.U2fSampleCode
// not allow for retries.
public class U2fSampleKeyCollector
{
- // This allows the caller to specify what the operation is.
- // Before calling an SDK method that will call the KeyCollector. Set this
- // property so the KeyCollector knows what message to report.
- public U2fKeyCollectorOperation Operation { get; set; }
-
public U2fSampleKeyCollector()
{
Operation = U2fKeyCollectorOperation.None;
}
+ // This allows the caller to specify what the operation is.
+ // Before calling an SDK method that will call the KeyCollector. Set this
+ // property so the KeyCollector knows what message to report.
+ public U2fKeyCollectorOperation Operation { get; set; }
+
public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData)
{
if (keyEntryData is null)
@@ -41,7 +41,7 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData)
return false;
}
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
return false;
}
@@ -59,11 +59,13 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData)
case KeyEntryRequest.TouchRequest:
ReportOperation();
- SampleMenu.WriteMessage(MessageType.Title, 0, "touch the YubiKey's contact to complete the operation.\n");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "touch the YubiKey's contact to complete the operation.\n");
return true;
case KeyEntryRequest.SetU2fPin:
- SampleMenu.WriteMessage(MessageType.Title, 0, "Setting the U2F application on the YubiKey to have a PIN, enter the PIN.");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "Setting the U2F application on the YubiKey to have a PIN, enter the PIN.");
collectedValue = SampleMenu.ReadResponse(out int _);
pinValue = ConvertCharArrayToByteArray(collectedValue);
keyEntryData.SubmitValue(pinValue);
@@ -74,12 +76,14 @@ public bool U2fSampleKeyCollectorDelegate(KeyEntryData keyEntryData)
case KeyEntryRequest.VerifyU2fPin:
if (Operation == U2fKeyCollectorOperation.Register)
{
- SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the PIN in order to complete registration.");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "Enter the PIN in order to complete registration.");
}
else
{
SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the PIN in order to verify.");
}
+
collectedValue = SampleMenu.ReadResponse(out int _);
pinValue = ConvertCharArrayToByteArray(collectedValue);
keyEntryData.SubmitValue(pinValue);
@@ -113,15 +117,18 @@ private void ReportOperation()
break;
case U2fKeyCollectorOperation.Register:
- SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to register a U2F credential,");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "The YubiKey is trying to register a U2F credential,");
break;
case U2fKeyCollectorOperation.Authenticate:
- SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to authenticate a U2F credential,");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "The YubiKey is trying to authenticate a U2F credential,");
break;
case U2fKeyCollectorOperation.Reset:
- SampleMenu.WriteMessage(MessageType.Title, 0, "The YubiKey is trying to reset the U2F application,");
+ SampleMenu.WriteMessage(MessageType.Title, 0,
+ "The YubiKey is trying to reset the U2F application,");
break;
}
}
diff --git a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs
index 12225b2c..6f483c54 100644
--- a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs
+++ b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs
@@ -14,10 +14,10 @@
using System;
using System.Linq;
+using System.Security.Cryptography;
+using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Sample.SharedCode;
using Yubico.YubiKey.U2f;
-using Yubico.YubiKey.Cryptography;
-using System.Security.Cryptography;
namespace Yubico.YubiKey.Sample.U2fSampleCode
{
@@ -288,9 +288,9 @@ public bool RunReset()
{
string versionNumber = _yubiKeyChosen.FirmwareVersion.ToString();
- if ((_yubiKeyChosen.FirmwareVersion >= new FirmwareVersion(5, 0, 0))
- || (_yubiKeyChosen.FirmwareVersion < new FirmwareVersion(4, 0, 0))
- || (!_yubiKeyChosen.IsFipsSeries))
+ if (_yubiKeyChosen.FirmwareVersion >= new FirmwareVersion(5, 0, 0)
+ || _yubiKeyChosen.FirmwareVersion < new FirmwareVersion(4, 0, 0)
+ || !_yubiKeyChosen.IsFipsSeries)
{
SampleMenu.WriteMessage(MessageType.Title, 0, "It is possible to reset the U2F application on only version 4");
SampleMenu.WriteMessage(MessageType.Title, 0, "FIPS series YubiKeys.");
diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs
index 448d1779..317bbc1c 100644
--- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs
+++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs
@@ -26,7 +26,7 @@ public static class U2fFips
public static bool GetFipsMode(IYubiKeyDevice yubiKey, out bool isFipsMode)
{
isFipsMode = false;
- if ((yubiKey is null) || (!yubiKey.IsFipsSeries))
+ if (yubiKey is null || !yubiKey.IsFipsSeries)
{
return false;
}
diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs
index f2e94169..bc4362d7 100644
--- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs
+++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs
@@ -13,12 +13,12 @@
// limitations under the License.
using System;
+using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
-using System.Diagnostics;
-using Yubico.YubiKey.U2f.Commands;
using Yubico.YubiKey.Sample.SharedCode;
+using Yubico.YubiKey.U2f.Commands;
namespace Yubico.YubiKey.Sample.U2fSampleCode
{
diff --git a/Yubico.YubiKey/src/AssemblyInfo.cs b/Yubico.YubiKey/src/AssemblyInfo.cs
index b1da9f09..a8b816ed 100644
--- a/Yubico.YubiKey/src/AssemblyInfo.cs
+++ b/Yubico.YubiKey/src/AssemblyInfo.cs
@@ -14,4 +14,4 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs
index ec31432d..b9eb6eca 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/CcidConnection.cs
@@ -14,14 +14,13 @@
using System;
using System.Globalization;
+using System.Linq;
using Yubico.Core.Buffers;
-using Yubico.YubiKey.InterIndustry.Commands;
-using Yubico.YubiKey.Pipelines;
-using Yubico.YubiKey.Scp03;
using Yubico.Core.Devices.SmartCard;
using Yubico.Core.Iso7816;
using Yubico.Core.Logging;
-using System.Linq;
+using Yubico.YubiKey.InterIndustry.Commands;
+using Yubico.YubiKey.Pipelines;
namespace Yubico.YubiKey
{
@@ -39,7 +38,7 @@ internal class CcidConnection : IYubiKeyConnection
protected CcidConnection(ISmartCardDevice smartCardDevice, YubiKeyApplication application, byte[]? applicationId)
{
- if ((applicationId is null) && (application == YubiKeyApplication.Unknown))
+ if (applicationId is null && application == YubiKeyApplication.Unknown)
{
throw new NotSupportedException();
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs b/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs
index 8d2d8810..aca9824c 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/ConnectionManager.cs
@@ -43,9 +43,9 @@ namespace Yubico.YubiKey
// JUSTIFICATION: This class is a singleton, which means its lifetime will span the process lifetime. It contains
// a lock which is disposable, so we must call its Dispose method at some point. The only reasonable time to do that
// is in this class's finalizer. This analyzer doesn't seem to see this and still warns.
- #pragma warning disable CA1001
+#pragma warning disable CA1001
internal class ConnectionManager
- #pragma warning restore CA1001
+#pragma warning restore CA1001
{
// Easy thread-safe singleton pattern using Lazy<>
private static readonly Lazy _instance =
@@ -318,5 +318,5 @@ public void EndConnection(IYubiKeyDevice yubiKeyDevice)
_hashSetLock.ExitWriteLock();
}
}
- }
+ }
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs
index 3921b388..3763e095 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs
@@ -16,8 +16,8 @@
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Yubico.Core.Tlv;
-using Yubico.YubiKey.Piv;
using Yubico.YubiKey.Fido2.Cose;
+using Yubico.YubiKey.Piv;
namespace Yubico.YubiKey.Cryptography
{
@@ -184,7 +184,7 @@ public EcdsaVerify(PivPublicKey pivPublicKey)
throw new ArgumentNullException(nameof(pivPublicKey));
}
- ReadOnlySpan pubPoint = (pivPublicKey is PivEccPublicKey eccKey)
+ ReadOnlySpan pubPoint = pivPublicKey is PivEccPublicKey eccKey
? eccKey.PublicPoint : ReadOnlySpan.Empty;
ECDsa = ConvertPublicKey(pubPoint.ToArray());
@@ -365,7 +365,7 @@ private static ECDsa ConvertPublicKey(ReadOnlyMemory encodedEccPoint)
byte[] xCoordinate = Array.Empty();
byte[] yCoordinate = Array.Empty();
- if ((encodedEccPoint.Length >= MinEncodedPointLength) && (encodedEccPoint.Span[0] == EncodedPointTag))
+ if (encodedEccPoint.Length >= MinEncodedPointLength && encodedEccPoint.Span[0] == EncodedPointTag)
{
int coordLength = (encodedEccPoint.Length - 1) / 2;
xCoordinate = encodedEccPoint.Slice(1, coordLength).ToArray();
@@ -412,9 +412,9 @@ private static ECDsa CheckECDsa(ECDsa toCheck)
_ => -1,
};
- if ((eccParams.Q.X.Length > 0) && (eccParams.Q.X.Length <= coordinateLength))
+ if (eccParams.Q.X.Length > 0 && eccParams.Q.X.Length <= coordinateLength)
{
- if ((eccParams.Q.Y.Length > 0) && (eccParams.Q.Y.Length <= coordinateLength))
+ if (eccParams.Q.Y.Length > 0 && eccParams.Q.Y.Length <= coordinateLength)
{
return toCheck;
}
@@ -474,7 +474,7 @@ private static bool TryCopyNextInteger(TlvReader tlvReader, Memory signatu
}
// If we still have data and it is not too long, copy
- if ((length > 0) && (length <= coordinateLength))
+ if (length > 0 && length <= coordinateLength)
{
rsValue[index..].CopyTo(signatureValue[(coordinateLength - length)..]);
return true;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs
index 5b9edfbb..70406411 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs
@@ -14,8 +14,8 @@
using System;
using System.Globalization;
-using System.Security.Cryptography;
using System.Runtime.CompilerServices;
+using System.Security.Cryptography;
using Yubico.Core.Tlv;
namespace Yubico.YubiKey.Cryptography
@@ -264,13 +264,13 @@ public static bool TryParsePkcs1Verify(ReadOnlySpan formattedSignature,
digestAlgorithm = 0;
digest = Array.Empty();
- if ((formattedSignature.Length != 128) && (formattedSignature.Length != 256))
+ if (formattedSignature.Length != 128 && formattedSignature.Length != 256)
{
return false;
}
// We expect to find 00 01 FF ... FF 00
- if ((formattedSignature[0] != Pkcs1LeadByte) || (formattedSignature[1] != Pkcs1SignByte))
+ if (formattedSignature[0] != Pkcs1LeadByte || formattedSignature[1] != Pkcs1SignByte)
{
return false;
}
@@ -664,7 +664,7 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature,
mPrimeAndH = Array.Empty();
isVerified = false;
- if ((formattedSignature.Length != 128) && (formattedSignature.Length != 256))
+ if (formattedSignature.Length != 128 && formattedSignature.Length != 256)
{
return false;
}
@@ -716,7 +716,7 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature,
// Verify that all PS bytes are 0, and that the byte after PS is 01.
int index = Array.FindIndex(buffer, p => p != 0);
- if ((index != psLength) || (buffer[psLength] != 1))
+ if (index != psLength || buffer[psLength] != 1)
{
return false;
}
@@ -843,7 +843,7 @@ public static byte[] FormatPkcs1Encrypt(ReadOnlySpan inputData, int keySiz
// There must be at least 8 bytes of pad, plus 3 extra bytes, the
// leading 00 02, then the separator between pad and data: 00. If
// there's too much data, we can't format.
- if ((inputData.Length == 0) || (inputData.Length > buffer.Length - (Pkcs1MinPadLength + 3)))
+ if (inputData.Length == 0 || inputData.Length > buffer.Length - (Pkcs1MinPadLength + 3))
{
throw new ArgumentException(
string.Format(
@@ -932,7 +932,7 @@ public static bool TryParsePkcs1Decrypt(ReadOnlySpan formattedData, out by
// Return this buffer if there is any error.
outputData = Array.Empty();
- if ((formattedData.Length != 128) && (formattedData.Length != 256))
+ if (formattedData.Length != 128 && formattedData.Length != 256)
{
return false;
}
@@ -963,7 +963,7 @@ public static bool TryParsePkcs1Decrypt(ReadOnlySpan formattedData, out by
// byte was 0 (startIndex will be 0), or if the zero byte does not
// allow for more than 8 pad bytes (startIndex will be < 10), this is
// an error.
- if (startIndex < (Pkcs1MinPadLength + 2))
+ if (startIndex < Pkcs1MinPadLength + 2)
{
errorFlag |= 1;
}
@@ -1095,7 +1095,7 @@ public static byte[] FormatPkcs1Oaep(ReadOnlySpan inputData, int digestAlg
int digestLength = digester.HashSize / 8;
- if ((inputData.Length == 0) || (inputData.Length > (buffer.Length - ((2 * digestLength) + 2))))
+ if (inputData.Length == 0 || inputData.Length > buffer.Length - ((2 * digestLength) + 2))
{
throw new ArgumentException(
string.Format(
@@ -1376,7 +1376,7 @@ private static int BuildDigestInfo(ReadOnlySpan digest, int digestAlgorith
// If the digest.Length is not digestLength, either isValid will be
// false or the outputLength won't be totalLength. So this is where
// digest.Length is checked.
- if ((isValid == false) || (outputLength != totalLength))
+ if (isValid == false || outputLength != totalLength)
{
throw new ArgumentException(
string.Format(
@@ -1504,7 +1504,7 @@ private static bool TryParseOid(bool isValid,
bool sameOid = oid.Span.SequenceEqual(new Span(supportedOid));
- if ((sameOid == false) || (digest.Length != digestLength) || (oidParams.Length != 0))
+ if (sameOid == false || digest.Length != digestLength || oidParams.Length != 0)
{
returnValue = false;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs
index 6f54906a..2f86af2f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorData.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Collections.Generic;
using System.Buffers.Binary;
+using System.Collections.Generic;
using System.Formats.Cbor;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
@@ -191,7 +191,7 @@ public AuthenticatorData(ReadOnlyMemory encodedData)
// determines that the caller is not allowed to get that data or it
// is not available. So don't try to read any extensions unless we
// know for sure there is data to read.
- if (extensions && (offset < EncodedAuthenticatorData.Length))
+ if (extensions && offset < EncodedAuthenticatorData.Length)
{
var extensionList = new Dictionary();
var cbor = new CborReader(EncodedAuthenticatorData[offset..], CborConformanceMode.Ctap2Canonical);
@@ -290,7 +290,7 @@ public byte[] GetCredBlobExtension()
/// used to create the
/// GetAssertion parameters.
///
- ///
+ ///
/// If you are getting assertions using
/// , you can use the
/// property.
@@ -364,7 +364,7 @@ public CredProtectPolicy GetCredProtectExtension()
if (Extensions.ContainsKey(KeyCredProtect))
{
byte[] encodedValue = Extensions[KeyCredProtect];
- if ((encodedValue.Length == 1) && (encodedValue[0] >= 1) && (encodedValue[0] <= 3))
+ if (encodedValue.Length == 1 && encodedValue[0] >= 1 && encodedValue[0] <= 3)
{
return (CredProtectPolicy)encodedValue[0];
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs
index 7c90387c..2fbfacdc 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Linq;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
+using System.Linq;
using Yubico.YubiKey.Fido2.Cbor;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
@@ -136,7 +136,7 @@ public class AuthenticatorInfo
/// This property is OPTIONAL, and if the YubiKey provides no value, this
/// will be null.
///
- public IReadOnlyDictionary? Options {get; private set; }
+ public IReadOnlyDictionary? Options { get; private set; }
///
/// The maximum size, in bytes, of a message sent to the YubiKey.
@@ -329,7 +329,7 @@ public AuthenticatorInfo(ReadOnlyMemory cborEncoding)
Aaguid = new ReadOnlyMemory(_aaguid);
if (cborMap.Contains(KeyExtensions))
{
- Extensions = (IReadOnlyList)cborMap.ReadArray(KeyExtensions);
+ Extensions = cborMap.ReadArray(KeyExtensions);
}
if (cborMap.Contains(KeyOptions))
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs
index e4645149..21c8c73a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorOptions.cs
@@ -176,33 +176,30 @@ public static OptionValue GetDefaultOptionValue(string option)
{
switch (option)
{
- default:
- return OptionValue.Unknown;
-
- case "plat":
- case "rk":
- case "noMcGaPermissionsWithClientPin":
- case "makeCredUvNotRqd":
+ case plat:
+ case rk:
+ case noMcGaPermissionsWithClientPin:
+ case makeCredUvNotRqd:
return OptionValue.False;
-
- case "up":
+ case up:
return OptionValue.True;
-
- case "clientPin":
- case "uv":
- case "pinUvAuthToken":
- case "largeBlobs":
- case "ep":
- case "bioEnroll":
- case "userVerificationMgmtPreview":
- case "uvBioEnroll":
- case "authnrCfg":
- case "uvAcfg":
- case "credMgmt":
- case "credentialMgmtPreview":
- case "setMinPINLength":
- case "alwaysUv":
+ case clientPin:
+ case uv:
+ case pinUvAuthToken:
+ case largeBlobs:
+ case ep:
+ case bioEnroll:
+ case userVerificationMgmtPreview:
+ case uvBioEnroll:
+ case authnrCfg:
+ case uvAcfg:
+ case credMgmt:
+ case credentialMgmtPreview:
+ case setMinPINLength:
+ case alwaysUv:
return OptionValue.NotSupported;
+ default:
+ return OptionValue.Unknown;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs
index 02fa1f3f..03491a02 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorTransports.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
using System.Formats.Cbor;
+using System.Globalization;
using Yubico.YubiKey.Fido2.Cbor;
namespace Yubico.YubiKey.Fido2
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs
index 67b1da3d..52cff753 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs
@@ -104,7 +104,7 @@ internal static class CborHelpers
///
public static byte[] EncodeStringArray(IReadOnlyList? localData)
{
- if ((localData is null) || (localData.Count == 0))
+ if (localData is null || localData.Count == 0)
{
return Array.Empty();
}
@@ -141,7 +141,7 @@ public static byte[] EncodeStringArray(IReadOnlyList? localData)
///
public static byte[] EncodeArrayOfObjects(IReadOnlyList? localData)
{
- if ((localData is null) || (localData.Count == 0))
+ if (localData is null || localData.Count == 0)
{
return Array.Empty();
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs
index 9e2303f6..147ff45b 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
using System.Formats.Cbor;
+using System.Globalization;
namespace Yubico.YubiKey.Fido2.Cbor
{
@@ -98,9 +98,9 @@ public CborMap(ReadOnlyMemory encoding)
///
/// A new IDictionary representing this map.
///
- public IReadOnlyDictionary AsDictionary()
+ public IReadOnlyDictionary AsDictionary()
{
- var returnValue = new Dictionary(_dict.Count);
+ var returnValue = new Dictionary(_dict.Count);
foreach (KeyValuePair entry in _dict)
{
object? currentValue = ConvertValue(entry.Value);
@@ -147,7 +147,7 @@ public IReadOnlyList ReadArray(TKey key)
{
object? currentValue = ConvertValue(entries[index]);
- if (!(currentValue is null) && (currentValue is TValue typedValue))
+ if (!(currentValue is null) && currentValue is TValue typedValue)
{
returnValue.Add(typedValue);
continue;
@@ -223,8 +223,6 @@ private static int ReadInt32(object? value)
{
throw new InvalidCastException(null, overflowException);
}
-
- throw new InvalidCastException();
}
///
@@ -247,7 +245,6 @@ private static uint ReadUInt32(object? value)
throw new InvalidCastException(null, overflowException);
}
- throw new InvalidCastException();
}
///
@@ -265,8 +262,6 @@ private static long ReadInt64(object? value)
{
throw new InvalidCastException(null, overflowException);
}
-
- throw new InvalidCastException();
}
///
@@ -288,8 +283,6 @@ private static ulong ReadUInt64(object? value)
{
throw new InvalidCastException(null, overflowException);
}
-
- throw new InvalidCastException();
}
///
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs
index 6eb84af5..df45ac4e 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
@@ -85,7 +85,7 @@ public BioEnrollBeginResponse CreateResponseForApdu(ResponseApdu responseApdu) =
// 03 int
private static byte[]? EncodeParams(int? timeoutMilliseconds)
{
- return (timeoutMilliseconds is null) ? null
+ return timeoutMilliseconds is null ? null
: new CborMapWriter()
.Entry(KeyTimeout, timeoutMilliseconds.Value)
.Encode();
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs
index e6a79227..5fa3da02 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs
index e2b8db01..6a5c6161 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollRemoveCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs
index 398b8021..fd7cf95f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollSetFriendlyNameCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs
index 24b63fa2..50d41e5d 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs
@@ -16,8 +16,8 @@
using System.Globalization;
using System.Security.Cryptography;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Cryptography;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
@@ -147,7 +147,7 @@ public ChangePinCommand(PinUvAuthProtocolBase pinProtocol, ReadOnlyMemory
CultureInfo.CurrentCulture,
ExceptionMessages.InvalidCallOrder));
}
- if ((currentPin.Length > MaximumPinLength) || (newPin.Length > MaximumPinLength))
+ if (currentPin.Length > MaximumPinLength || newPin.Length > MaximumPinLength)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs
index e994fbc1..6df3047c 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/CredentialManagementData.cs
@@ -136,7 +136,7 @@ public class CredentialManagementData
/// Not all calls to get credential management data will return this
/// element, hence, it can be null.
///
- public CredentialId? CredentialId {get; private set; }
+ public CredentialId? CredentialId { get; private set; }
///
/// The public key for a credential returned.
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs
index 4a73678e..24c81e9d 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/DeleteCredentialCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs
index 7707aa20..30e40da0 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnableEnterpriseAttestationCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs
index 04f19d84..223fe4d9 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs
index 83e637b9..e1501d7a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoCommand.cs
@@ -38,14 +38,14 @@ public sealed class GetFingerprintSensorInfoCommand : IYubiKeyCommand
- public CommandApdu CreateCommandApdu() => _command.CreateCommandApdu();
+ public CommandApdu CreateCommandApdu() => _command.CreateCommandApdu();
///
- public GetFingerprintSensorInfoResponse CreateResponseForApdu(ResponseApdu responseApdu) =>
- new GetFingerprintSensorInfoResponse(responseApdu);
+ public GetFingerprintSensorInfoResponse CreateResponseForApdu(ResponseApdu responseApdu) =>
+ new GetFingerprintSensorInfoResponse(responseApdu);
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs
index 982484d7..7562cdc7 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
using System.Globalization;
+using System.Security.Cryptography;
+using Yubico.Core.Iso7816;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2.PinProtocols;
-using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs
index 09ef93fc..4db4bc8b 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
using System.Globalization;
+using System.Security.Cryptography;
+using Yubico.Core.Iso7816;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2.PinProtocols;
-using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs
index 3f838f2d..93ac6862 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingUvCommand.cs
@@ -14,8 +14,8 @@
using System;
using System.Globalization;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs
index dfb50bc7..534b20d7 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/RequirementValue.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using Yubico.YubiKey.Fido2.Cbor;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs
index d03b2bde..797fd625 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetLargeBlobCommand.cs
@@ -161,7 +161,7 @@ public SetLargeBlobCommand(
///
public CommandApdu CreateCommandApdu()
{
- int count = (_offset == 0) ? CborMapCountInit : CborMapCountUpdate;
+ int count = _offset == 0 ? CborMapCountInit : CborMapCountUpdate;
var cborWriter = new CborWriter(CborConformanceMode.Ctap2Canonical, convertIndefiniteLengthEncodings: true);
cborWriter.WriteStartMap(count);
cborWriter.WriteInt32(CborKeySet);
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs
index 2450bf2d..d8f2eb84 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/SetMinPinLengthCommand.cs
@@ -15,8 +15,8 @@
using System;
using System.Collections.Generic;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
@@ -202,7 +202,7 @@ public Fido2Response CreateResponseForApdu(ResponseApdu responseApdu) =>
// 03 bool
private static byte[]? EncodeParams(int? minPinLength, IReadOnlyList? rpIds, bool? forceChangePin)
{
- if ((minPinLength is null) && (rpIds is null) && (forceChangePin is null))
+ if (minPinLength is null && rpIds is null && forceChangePin is null)
{
return null;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs
index 2507cf14..9c5acb6f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ToggleAlwaysUvCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs
index 5bf4f9c4..7101ed74 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/UpdateUserInfoCommand.cs
@@ -14,8 +14,8 @@
using System;
using Yubico.Core.Iso7816;
-using Yubico.YubiKey.Fido2.PinProtocols;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.PinProtocols;
namespace Yubico.YubiKey.Fido2.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs
index bf9d479c..7a8d3fbc 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseEcPublicKey.cs
@@ -157,8 +157,8 @@ private CoseEcPublicKey()
///
public CoseEcPublicKey(CoseEcCurve curve, ReadOnlyMemory xCoordinate, ReadOnlyMemory yCoordinate)
{
- if ((curve != CoseEcCurve.P256) || (xCoordinate.Length == 0) || (xCoordinate.Length > P256CoordinateLength)
- || (yCoordinate.Length == 0) || (yCoordinate.Length > P256CoordinateLength))
+ if (curve != CoseEcCurve.P256 || xCoordinate.Length == 0 || xCoordinate.Length > P256CoordinateLength
+ || yCoordinate.Length == 0 || yCoordinate.Length > P256CoordinateLength)
{
throw new ArgumentException(ExceptionMessages.InvalidPublicKeyData);
}
@@ -248,7 +248,7 @@ public ECParameters ToEcParameters()
///
public override byte[] Encode()
{
- if ((_xCoordinate.Length != P256CoordinateLength) || (_yCoordinate.Length != P256CoordinateLength))
+ if (_xCoordinate.Length != P256CoordinateLength || _yCoordinate.Length != P256CoordinateLength)
{
throw new InvalidOperationException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs
index 820959be..82a7e7df 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cose/CoseKey.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Formats.Cbor;
+using System.Globalization;
using Yubico.YubiKey.Fido2.Cbor;
namespace Yubico.YubiKey.Fido2.Cose
@@ -119,7 +119,7 @@ public static CoseKey Create(ReadOnlyMemory coseEncodedKey, out int bytesR
// (ECDHwHKDF256). If the -25 seems odd, it is specified in the FIDO2
// standard.
var algorithm = (CoseAlgorithmIdentifier)map.ReadInt32(TagAlgorithm);
- if ((algorithm == CoseAlgorithmIdentifier.ECDHwHKDF256) || (algorithm == CoseAlgorithmIdentifier.ES256))
+ if (algorithm == CoseAlgorithmIdentifier.ECDHwHKDF256 || algorithm == CoseAlgorithmIdentifier.ES256)
{
return new CoseEcPublicKey(coseEncodedKey);
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs
index 151d9725..01a6f466 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using Yubico.YubiKey.Fido2.Cbor;
namespace Yubico.YubiKey.Fido2
@@ -201,7 +201,7 @@ public void AddTransport(string transport)
{
_transports.Add(transport);
}
- }
+ }
///
public byte[] CborEncode()
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs
index 1c3b3979..a6761f48 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialUserInfo.cs
@@ -32,7 +32,7 @@ public class CredentialUserInfo
///
/// The credential ID for a credential returned.
///
- public CredentialId CredentialId {get; private set; }
+ public CredentialId CredentialId { get; private set; }
///
/// The public key for a credential returned.
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs
index 5d54d892..01bbfff8 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Threading;
-using System.Threading.Tasks;
using System.Collections.Generic;
using System.Security;
+using System.Threading;
+using System.Threading.Tasks;
using Yubico.Core.Logging;
using Yubico.YubiKey.Fido2.Commands;
@@ -47,7 +47,7 @@ public BioModality GetBioModality()
var cmd = new GetBioModalityCommand();
GetBioModalityResponse rsp = Connection.SendCommand(cmd);
- int modality = (rsp.Status == ResponseStatus.Success) ? rsp.GetData() : 0;
+ int modality = rsp.Status == ResponseStatus.Success ? rsp.GetData() : 0;
return modality switch
{
@@ -79,7 +79,7 @@ public FingerprintSensorInfo GetFingerprintSensorInfo()
var cmd = new GetFingerprintSensorInfoCommand();
GetFingerprintSensorInfoResponse rsp = Connection.SendCommand(cmd);
- return (rsp.Status == ResponseStatus.Success) ?
+ return rsp.Status == ResponseStatus.Success ?
rsp.GetData() : throw new NotSupportedException(ExceptionMessages.NotSupportedByYubiKeyVersion);
}
@@ -265,7 +265,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec
if (!string.IsNullOrEmpty(friendlyName))
{
returnName = friendlyName!;
- foreach(TemplateInfo templateInfo in templateList)
+ foreach (TemplateInfo templateInfo in templateList)
{
if (returnName!.Equals(templateInfo.FriendlyName, StringComparison.Ordinal))
{
@@ -320,7 +320,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec
generalErrorMsg = nextRsp.StatusMessage;
}
- if ((status == CtapStatus.Ok) && !string.IsNullOrEmpty(returnName))
+ if (status == CtapStatus.Ok && !string.IsNullOrEmpty(returnName))
{
var nameCmd = new BioEnrollSetFriendlyNameCommand(templateId, returnName, currentToken, AuthProtocol);
Fido2Response nameRsp = Connection.SendCommand(nameCmd);
@@ -432,7 +432,7 @@ public bool TryRemoveBioTemplate(ReadOnlyMemory templateId)
removeRsp = Connection.SendCommand(removeCmd);
}
- return (removeRsp.Status == ResponseStatus.Success) || (removeRsp.CtapStatus == CtapStatus.InvalidOption);
+ return removeRsp.Status == ResponseStatus.Success || removeRsp.CtapStatus == CtapStatus.InvalidOption;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs
index a510ada5..1d3faf4a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs
@@ -165,7 +165,7 @@ public bool TryToggleAlwaysUv()
_log.LogInformation("Try to ToggleAlwaysUv.");
OptionValue alwaysUvValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.alwaysUv);
- if ((alwaysUvValue != OptionValue.True) && (alwaysUvValue != OptionValue.False))
+ if (alwaysUvValue != OptionValue.True && alwaysUvValue != OptionValue.False)
{
return false;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs
index 7a1ef37a..2e38ebfa 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
+using System.Text;
using Yubico.Core.Logging;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2.Commands;
@@ -442,7 +442,7 @@ public void DeleteCredential(CredentialId credentialId)
}
// If the response is Success, we're done.
- if ((rsp.Status == ResponseStatus.Success) || (rsp.CtapStatus == CtapStatus.NoCredentials))
+ if (rsp.Status == ResponseStatus.Success || rsp.CtapStatus == CtapStatus.NoCredentials)
{
// After a credential has been deleted, the number of
// discoverable credentials can change. Hence, this operation can
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs
index 180b338b..623fcb44 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs
@@ -15,8 +15,8 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
-using Yubico.YubiKey.Fido2.Commands;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Fido2.Commands;
namespace Yubico.YubiKey.Fido2
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs
index abc74e14..df99a5e0 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs
@@ -13,13 +13,13 @@
// limitations under the License.
using System;
-using System.IO;
using System.Buffers.Binary;
+using System.IO;
using System.Security.Cryptography;
using Yubico.Core.Logging;
using Yubico.YubiKey.Cryptography;
-using Yubico.YubiKey.Fido2.Commands;
using Yubico.YubiKey.Fido2.Cbor;
+using Yubico.YubiKey.Fido2.Commands;
namespace Yubico.YubiKey.Fido2
{
@@ -118,7 +118,7 @@ public SerializedLargeBlobArray GetSerializedLargeBlobArray()
int maxFragmentLength = AuthenticatorInfo.MaximumMessageSize ?? AuthenticatorInfo.DefaultMaximumMessageSize;
using var fullEncoding = new MemoryStream(maxFragmentLength);
- maxFragmentLength -= MessageOverhead;
+ maxFragmentLength -= MessageOverhead;
ReadOnlyMemory currentData;
@@ -234,7 +234,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge
int offset = 0;
int remaining = encodedArray.Length;
int maxFragmentLength = AuthenticatorInfo.MaximumMessageSize ?? AuthenticatorInfo.DefaultMaximumMessageSize;
- maxFragmentLength -= MessageOverhead;
+ maxFragmentLength -= MessageOverhead;
int currentLength;
bool forceToken = false;
@@ -246,7 +246,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge
forceToken, PinUvAuthTokenPermissions.LargeBlobWrite, null);
currentToken.CopyTo(token.AsMemory());
- currentLength = (remaining >= maxFragmentLength) ? maxFragmentLength : remaining;
+ currentLength = remaining >= maxFragmentLength ? maxFragmentLength : remaining;
byte[] dataToAuth = BuildDataToAuth(encodedArray, offset, currentLength, digester);
byte[] pinUvAuthParam = AuthProtocol.AuthenticateUsingPinToken(token, 0, currentToken.Length, dataToAuth);
@@ -264,7 +264,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge
offset += currentLength;
forceToken = false;
}
- else if ((response.CtapStatus == CtapStatus.PinAuthInvalid) && !forceToken)
+ else if (response.CtapStatus == CtapStatus.PinAuthInvalid && !forceToken)
{
forceToken = true;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs
index 42f89fef..d568f345 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs
@@ -14,8 +14,8 @@
using System;
using System.Security.Cryptography;
-using Yubico.YubiKey.Fido2.Commands;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Fido2.Commands;
namespace Yubico.YubiKey.Fido2
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs
index c723e142..917870cd 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs
@@ -15,10 +15,10 @@
using System;
using System.Globalization;
using System.Security;
+using Yubico.Core.Logging;
using Yubico.YubiKey.Fido2.Commands;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
-using Yubico.Core.Logging;
namespace Yubico.YubiKey.Fido2
{
@@ -314,7 +314,7 @@ public void AddPermissions(PinUvAuthTokenPermissions permissions, string? relyin
// If the permissions requested require an RpId, then make sure there
// is one.
- if ((allPermissions.GetRpIdRequirement() == RequirementValue.Required) && (rpId is null))
+ if (allPermissions.GetRpIdRequirement() == RequirementValue.Required && rpId is null)
{
throw new InvalidOperationException(ExceptionMessages.Fido2RelyingPartyMissing);
}
@@ -1008,7 +1008,7 @@ public bool TryVerifyPin(
ObtainSharedSecret();
- if (!permissions.HasValue || (permissions == PinUvAuthTokenPermissions.None))
+ if (!permissions.HasValue || permissions == PinUvAuthTokenPermissions.None)
{
if (!string.IsNullOrEmpty(relyingPartyId))
{
@@ -1188,7 +1188,7 @@ public bool TryVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPa
_log.LogInformation("Try to verify UV (use KeyCollector).");
CtapStatus status = DoVerifyUv(permissions, relyingPartyId, out string statusMessage);
- switch(status)
+ switch (status)
{
case CtapStatus.Ok:
return true;
@@ -1215,8 +1215,8 @@ public bool TryVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPa
private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPartyId, out string statusMessage)
{
- if ((AuthenticatorInfo.GetOptionValue("pinUvAuthToken") != OptionValue.True)
- || (AuthenticatorInfo.GetOptionValue("uv") != OptionValue.True))
+ if (AuthenticatorInfo.GetOptionValue("pinUvAuthToken") != OptionValue.True
+ || AuthenticatorInfo.GetOptionValue("uv") != OptionValue.True)
{
statusMessage = "";
return CtapStatus.UnsupportedOption;
@@ -1266,7 +1266,7 @@ private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? rel
status = CtapStatus.LimitExceeded;
}
}
- } while(status == CtapStatus.UvInvalid);
+ } while (status == CtapStatus.UvInvalid);
return status;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs
index 8833d5e0..601fe00d 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using System.Security.Cryptography;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2.Cbor;
@@ -48,7 +48,6 @@ public class GetAssertionData : IDisposable
private const string KeyUserName = "name";
private const string KeyUserDisplayName = "displayName";
-// private readonly Logger _log = Log.GetLogger();
private bool _disposed;
private readonly byte[]? _keyData;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs
index 2b716191..9014d1d0 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.Extensions.cs
@@ -208,7 +208,7 @@ public void RequestHmacSecretExtension(
if (salt1.Length == HmacSecretSaltLength)
{
- int s2Len = (salt2 is null) ? HmacSecretSaltLength : salt2.Value.Length;
+ int s2Len = salt2 is null ? HmacSecretSaltLength : salt2.Value.Length;
_salt1 = salt1;
if (s2Len == HmacSecretSaltLength)
{
@@ -286,7 +286,7 @@ public void EncodeHmacSecretExtension(PinUvAuthProtocolBase authProtocol)
{
throw new ArgumentNullException(nameof(authProtocol));
}
- if ((authProtocol.EncryptionKey is null) || (authProtocol.PlatformPublicKey is null))
+ if (authProtocol.EncryptionKey is null || authProtocol.PlatformPublicKey is null)
{
throw new InvalidOperationException(ExceptionMessages.Fido2NotEncapsulated);
}
@@ -319,5 +319,5 @@ public void EncodeHmacSecretExtension(PinUvAuthProtocolBase authProtocol)
.Entry(TagPinProtocol, (int)authProtocol.Protocol)
.Encode();
}
- }
+ }
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs
index 3fe89dd0..4b0db309 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionParameters.cs
@@ -272,5 +272,5 @@ public byte[] CborEncode()
.OptionalEntry(TagProtocol, (int?)Protocol)
.Encode();
}
- }
+ }
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs
index 0e155e8c..f449ebf2 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.IO;
-using System.IO.Compression;
using System.Buffers.Binary;
using System.Formats.Cbor;
+using System.IO;
+using System.IO.Compression;
using System.Security.Cryptography;
using Yubico.Core.Cryptography;
using Yubico.Core.Logging;
@@ -176,7 +176,7 @@ internal LargeBlobEntry(ReadOnlyMemory cborEncoding)
// Make sure the data includes the tag plus at least one byte,
// and that there is original data.
- if ((OriginalDataLength > 0) && (Ciphertext.Length > GcmTagSize))
+ if (OriginalDataLength > 0 && Ciphertext.Length > GcmTagSize)
{
return;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs
index 2ddcc476..3ebd7f9c 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
-using System.Security.Cryptography;
using System.Globalization;
+using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
-using System.Collections.Generic;
using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Fido2.Cbor;
using Yubico.YubiKey.Fido2.Cose;
@@ -200,7 +200,7 @@ public MakeCredentialData(ReadOnlyMemory cborEncoding)
Format = map.ReadTextString(KeyFormat);
AuthenticatorData = new AuthenticatorData(map.ReadByteString(KeyAuthData));
if (!(AuthenticatorData.CredentialPublicKey is CoseEcPublicKey)
- || (AuthenticatorData.CredentialPublicKey.Type != CoseKeyType.Ec2)
+ || AuthenticatorData.CredentialPublicKey.Type != CoseKeyType.Ec2
|| !map.Contains(KeyAttestationStatement)
|| !ReadAttestation(map))
{
@@ -240,8 +240,8 @@ private bool ReadAttestation(CborMap map)
EncodedAttestationStatement = attest.Encoded;
if (!Format.Equals(PackedString, StringComparison.Ordinal)
|| !attest.Contains(AlgString) || !attest.Contains(SigString)
- || (attest.Count > MaxAttestationMapCount)
- || ((attest.Count == MaxAttestationMapCount) && !attest.Contains(X5cString)))
+ || attest.Count > MaxAttestationMapCount
+ || (attest.Count == MaxAttestationMapCount && !attest.Contains(X5cString)))
{
return false;
}
@@ -288,7 +288,7 @@ private bool ReadAttestation(CborMap map)
///
public bool VerifyAttestation(ReadOnlyMemory clientDataHash)
{
- if ((AttestationCertificates is null) || (AttestationCertificates.Count == 0))
+ if (AttestationCertificates is null || AttestationCertificates.Count == 0)
{
throw new InvalidOperationException(ExceptionMessages.MissingCtap2Data);
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs
index c25f42c1..1cb1e3f7 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialParameters.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Formats.Cbor;
using System.Collections.Generic;
-using System.Linq;
+using System.Formats.Cbor;
using System.Globalization;
+using System.Linq;
using Yubico.YubiKey.Fido2.Cbor;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
@@ -695,8 +695,8 @@ public byte[] CborEncode()
.Entry(TagUserEntity, UserEntity)
.Entry(TagAlgorithmsList, EncodeAlgorithms, this)
.OptionalEntry>(TagExcludeList, CborHelpers.EncodeArrayOfObjects, ExcludeList)
- .OptionalEntry>(TagExtensions, ParameterHelpers.EncodeKeyValues, _extensions)
- .OptionalEntry>(TagOptions, ParameterHelpers.EncodeKeyValues, _options)
+ .OptionalEntry>(TagExtensions, ParameterHelpers.EncodeKeyValues, _extensions)
+ .OptionalEntry>(TagOptions, ParameterHelpers.EncodeKeyValues, _options)
.OptionalEntry(TagPinUvAuth, PinUvAuthParam)
.OptionalEntry(TagProtocol, (int?)Protocol)
.OptionalEntry(TagEnterpriseAttestation, (int?)EnterpriseAttestation)
@@ -705,7 +705,7 @@ public byte[] CborEncode()
private byte[] EncodeAlgorithms(MakeCredentialParameters? localData)
{
- if ((localData is null) || (localData.Algorithms.Count == 0))
+ if (localData is null || localData.Algorithms.Count == 0)
{
return Array.Empty();
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs
index af698c7f..961e32c1 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/OptionValue.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using Yubico.YubiKey.Fido2.Cbor;
using Yubico.YubiKey.Fido2.Cose;
using Yubico.YubiKey.Fido2.PinProtocols;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs
index 5d453e56..9e9382ac 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
using System.Formats.Cbor;
+using System.Globalization;
using Yubico.YubiKey.Fido2.Cose;
namespace Yubico.YubiKey.Fido2
@@ -44,7 +44,7 @@ public static List AddToList(T itemToAdd, List? currentList)
throw new ArgumentNullException();
}
- List returnList = (currentList is null) ? new List() : currentList;
+ List returnList = currentList is null ? new List() : currentList;
returnList.Add(itemToAdd);
return returnList;
@@ -71,7 +71,7 @@ public static Dictionary AddKeyValue(
}
Dictionary returnDictionary =
- (currentDictionary is null) ? new Dictionary() : currentDictionary;
+ currentDictionary is null ? new Dictionary() : currentDictionary;
// If the key already exists, replace the current value in the
// dictionary with this one.
@@ -103,9 +103,9 @@ public static Dictionary AddKeyValue(
/// (localData is null or a the Count is zero), the
/// return will be an empty byte array.
///
- public static byte[] EncodeKeyValues(IReadOnlyDictionary? localData)
+ public static byte[] EncodeKeyValues(IReadOnlyDictionary? localData)
{
- if ((localData is null) || (localData.Count == 0))
+ if (localData is null || localData.Count == 0)
{
return Array.Empty();
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs
index 52697b9e..74d945ca 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs
@@ -56,7 +56,7 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length)
{
throw new ArgumentNullException(nameof(plaintext));
}
- if ((length < BlockSize) || ((length % BlockSize) != 0) || ((offset + length) > plaintext.Length))
+ if (length < BlockSize || length % BlockSize != 0 || offset + length > plaintext.Length)
{
throw new ArgumentException(
string.Format(
@@ -92,7 +92,7 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length)
{
throw new ArgumentNullException(nameof(ciphertext));
}
- if ((length == 0) || (length % BlockSize != 0) || (offset + length > ciphertext.Length))
+ if (length == 0 || length % BlockSize != 0 || offset + length > ciphertext.Length)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs
index b3c5cde5..f69c5e76 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs
@@ -15,8 +15,8 @@
using System;
using System.Globalization;
using System.IO;
-using System.Text;
using System.Security.Cryptography;
+using System.Text;
using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Fido2.PinProtocols
@@ -63,7 +63,7 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length)
{
throw new ArgumentNullException(nameof(plaintext));
}
- if ((length == 0) || ((length % BlockSize) != 0) || ((offset + length) > plaintext.Length))
+ if (length == 0 || length % BlockSize != 0 || offset + length > plaintext.Length)
{
throw new ArgumentException(
string.Format(
@@ -109,7 +109,7 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length)
}
// The first BlockSize bytes are the IV, so there should be at least
// 2 blocks.
- if ((length < 2 * BlockSize) || ((length % BlockSize) != 0) || ((offset + length) > ciphertext.Length))
+ if (length < 2 * BlockSize || length % BlockSize != 0 || offset + length > ciphertext.Length)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs
index 15a765b8..a143dbce 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs
@@ -13,12 +13,12 @@
// limitations under the License.
using System;
-using System.Text;
using System.Formats.Cbor;
using System.Globalization;
using System.Security.Cryptography;
-using Yubico.YubiKey.Fido2.Cbor;
+using System.Text;
using Yubico.YubiKey.Cryptography;
+using Yubico.YubiKey.Fido2.Cbor;
namespace Yubico.YubiKey.Fido2
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs
index 2eb09c06..df5998c2 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using System.Security.Cryptography;
using Yubico.Core.Logging;
using Yubico.YubiKey.Cryptography;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs
index 7eebb87d..3e4c39f1 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/UserEntity.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
+using System.Collections.Generic;
using System.Formats.Cbor;
using System.Globalization;
-using System.Collections.Generic;
using Yubico.YubiKey.Fido2.Cbor;
namespace Yubico.YubiKey.Fido2
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs
index acfc7ae3..ccf36a64 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.YubiKey.Pipelines;
using Yubico.Core.Devices.Hid;
using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Pipelines;
namespace Yubico.YubiKey
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs
index 53304571..3240c602 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs
@@ -12,13 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.Core.Devices.Hid;
-using Yubico.YubiKey.DeviceExtensions;
-using System.Diagnostics;
using System;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging;
+using Yubico.Core.Devices.Hid;
using Yubico.Core.Logging;
+using Yubico.YubiKey.DeviceExtensions;
namespace Yubico.YubiKey
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs
index e1677b3b..2ce17a4f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs
@@ -174,7 +174,7 @@ public int CompareTo(FirmwareVersion other)
{
return 0;
}
- else if (other is null)
+ if (other is null)
{
return 1;
}
@@ -190,15 +190,11 @@ public int CompareTo(FirmwareVersion other)
int patchComparison = Patch.CompareTo(other.Patch);
return patchComparison;
}
- else
- {
- return minorComparison;
- }
- }
- else
- {
- return majorComparison;
+
+ return minorComparison;
}
+
+ return majorComparison;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs
index 13a6fd5a..097f8d1b 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs
@@ -12,11 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.Core.Devices.Hid;
-using Yubico.YubiKey.DeviceExtensions;
using System;
using System.Diagnostics.CodeAnalysis;
+using Yubico.Core.Devices.Hid;
using Yubico.Core.Logging;
+using Yubico.YubiKey.DeviceExtensions;
namespace Yubico.YubiKey
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs
index 21fe9974..ef7992dd 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardReport.cs
@@ -98,11 +98,11 @@ public KeyboardReport(Memory reportBuffer)
public override string ToString()
{
return
- $"TouchPending: { TouchPending }, " +
- $"ReadPending: { ReadPending }, " +
- $"WritePending: { WritePending }, " +
- $"SequenceNumber: { SequenceNumber }, " +
- $"Payload: { BitConverter.ToString(PayloadSpan().ToArray()) }";
+ $"TouchPending: {TouchPending}, " +
+ $"ReadPending: {ReadPending}, " +
+ $"WritePending: {WritePending}, " +
+ $"SequenceNumber: {SequenceNumber}, " +
+ $"Payload: {BitConverter.ToString(PayloadSpan().ToArray())}";
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs
index c680c7d5..2403bf68 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetDeviceInfoBaseCommand.cs
@@ -79,7 +79,7 @@ public int? AutoEjectTimeout
{
if (value.HasValue)
{
- if ((value < ushort.MinValue) || (value > ushort.MaxValue))
+ if (value < ushort.MinValue || value > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs
index 6f76cd20..755da34a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/SetLegacyDeviceConfigBase.cs
@@ -74,7 +74,7 @@ public static bool ContainsOnlyValidInterfaceFlags(YubiKeyCapabilities yubiKeyIn
public YubiKeyCapabilities YubiKeyInterfaces
{
get => _yubiKeyInterfaces;
-
+
set
{
if (!ContainsOnlyValidInterfaceFlags(value))
@@ -112,7 +112,7 @@ public int AutoEjectTimeout
set
{
- if ((value < ushort.MinValue) || (value > ushort.MaxValue))
+ if (value < ushort.MinValue || value > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs
index b5420a0a..d43ef489 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs
@@ -75,7 +75,8 @@ public Code(string? value, CredentialPeriod period)
throw new ArgumentException(ExceptionMessages.InvalidCredentialPeriod);
}
- if (!string.IsNullOrWhiteSpace(value)) {
+ if (!string.IsNullOrWhiteSpace(value))
+ {
Value = value;
DateTimeOffset timestamp = DateTimeOffset.UtcNow;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs
index 900b13f5..af5e458b 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommand.cs
@@ -25,7 +25,7 @@ public class CalculateAllCredentialsCommand : OathChallengeResponseBaseCommand,
{
private const byte CalculateAllInstruction = 0xA4;
private const byte ChallengeTag = 0x74;
-
+
///
/// Full or truncated response to receive back.
///
@@ -65,7 +65,7 @@ public CalculateAllCredentialsCommand(ResponseFormat responseFormat)
public CommandApdu CreateCommandApdu()
{
var tlvWriter = new TlvWriter();
-
+
// Using default period which is 30 seconds for calculating all credentials.
// Credentials that have different period are recalculated later in CalculateAllCredentialsResponse.
tlvWriter.WriteValue(ChallengeTag, GenerateTotpChallenge(CredentialPeriod.Period30));
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs
index 7539f162..cf61c015 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommand.cs
@@ -92,7 +92,7 @@ public CommandApdu CreateCommandApdu()
{
throw new InvalidOperationException(ExceptionMessages.InvalidCredentialType);
}
-
+
if (Credential.Period is null)
{
throw new InvalidOperationException(ExceptionMessages.InvalidCredentialPeriod);
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs
index 1dfda351..c291b3a8 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListCommand.cs
@@ -25,7 +25,7 @@ namespace Yubico.YubiKey.Oath.Commands
public class ListCommand : IYubiKeyCommand
{
private const byte ListInstruction = 0xa1;
-
+
///
/// Gets the YubiKeyApplication to which this command belongs.
///
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs
index fc055fa7..27d67609 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs
@@ -34,10 +34,7 @@ public abstract class OathChallengeResponseBaseCommand
///
protected static byte[] GenerateTotpChallenge(CredentialPeriod? period)
{
- if (period is null)
- {
- period = CredentialPeriod.Period30;
- }
+ period ??= CredentialPeriod.Period30;
ulong timePeriod = (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds() / (uint)period;
byte[] bytes = new byte[8];
@@ -61,7 +58,7 @@ protected static byte[] GenerateRandomChallenge()
byte[] randomBytes = new byte[8];
randomObject.GetBytes(randomBytes);
-
+
return randomBytes;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs
index 6bdf1406..f9cb88bd 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathResponse.cs
@@ -21,7 +21,7 @@ namespace Yubico.YubiKey.Oath.Commands
/// or one of its derived classes to retrieve the full response.
///
///
- public class OathResponse: YubiKeyResponse
+ public class OathResponse : YubiKeyResponse
{
public OathResponse(ResponseApdu responseApdu) :
base(responseApdu)
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs
index 708334c9..87380a49 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/RenameCommand.cs
@@ -113,7 +113,7 @@ public CommandApdu CreateCommandApdu()
var newCredential = new Credential
{
- Issuer = NewIssuer,
+ Issuer = NewIssuer,
AccountName = NewAccount,
Type = Credential.Type,
Period = Credential.Period
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs
index d2ca7c86..9a99d6ea 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateCommand.cs
@@ -96,9 +96,9 @@ public CommandApdu CreateCommandApdu()
return new CommandApdu
{
- Ins = ValidateInstruction,
+ Ins = ValidateInstruction,
Data = tlvWriter.Encode()
- };
+ };
}
///
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs
index a2776ec6..5d98a025 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs
@@ -24,7 +24,7 @@ namespace Yubico.YubiKey.Oath.Commands
public class ValidateResponse : OathResponse, IYubiKeyResponseWithData
{
private const byte ResponseTag = 0x75;
-
+
///
protected override ResponseStatusPair StatusCodeMap =>
StatusWord switch
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs
index 998248fe..b6823137 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
-using System.Web;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
+using System.Web;
using static System.Convert;
namespace Yubico.YubiKey.Oath
@@ -94,7 +94,7 @@ public HashAlgorithm? Algorithm
}
_algorithm = value;
- }
+ }
}
///
@@ -146,7 +146,8 @@ public string? Secret
get => _secret;
set
{
- if (value != null) {
+ if (value != null)
+ {
var regexSecret = new Regex(@"[A-Za-z2-7=]*");
@@ -156,7 +157,7 @@ public string? Secret
}
}
-
+
_secret = value;
}
}
@@ -457,7 +458,7 @@ internal static (CredentialPeriod period, string? issuer, string account) ParseL
string account = parsedAccount.Last();
- return (period, issuer, account);
+ return (period, issuer, account);
}
///
@@ -481,7 +482,7 @@ public static Credential ParseUri(Uri uri)
{
if (uri == null)
{
- throw new ArgumentNullException(nameof(uri));
+ throw new ArgumentNullException(nameof(uri));
}
if (!uri.IsAbsoluteUri || uriScheme != uri.Scheme)
@@ -502,7 +503,7 @@ public static Credential ParseUri(Uri uri)
}
NameValueCollection? parsedUri = HttpUtility.ParseQueryString(uriQuery);
-
+
string? defaultIssuer = parsedUri["issuer"];
(string? issuer, string account) = ParseUriPath(uriPath, defaultIssuer);
@@ -641,14 +642,14 @@ public bool Equals(Credential? credential)
return false;
}
- return (_issuer == credential._issuer)
- && (_accountName == credential._accountName)
- && (_secret == credential._secret)
- && (_digits == credential._digits)
- && (_counter == credential._counter)
- && (_type == credential._type)
- && (_period == credential._period)
- && (_algorithm == credential._algorithm);
+ return _issuer == credential._issuer
+ && _accountName == credential._accountName
+ && _secret == credential._secret
+ && _digits == credential._digits
+ && _counter == credential._counter
+ && _type == credential._type
+ && _period == credential._period
+ && _algorithm == credential._algorithm;
}
public static bool operator ==(Credential lhs, Credential rhs)
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs
index 4d38e8a0..78731677 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs
@@ -223,7 +223,7 @@ public void AddCredential(Credential credential)
throw new InvalidOperationException(ExceptionMessages.TouchNotSupported);
}
- if (credential.Algorithm == HashAlgorithm.Sha512 &&
+ if (credential.Algorithm == HashAlgorithm.Sha512 &&
!_yubiKeyDevice.HasFeature(YubiKeyFeature.OathSha512))
{
throw new InvalidOperationException(ExceptionMessages.SHA512NotSupported);
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs
index b33544a4..139948a9 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs
@@ -14,7 +14,6 @@
using System;
using System.Globalization;
-using System.Linq;
using System.Security;
using Yubico.Core.Iso7816;
using Yubico.YubiKey.Oath.Commands;
@@ -49,8 +48,8 @@ public bool TryVerifyPassword()
try
{
- if (KeyCollector!(keyEntryData) == true) {
-
+ if (KeyCollector!(keyEntryData))
+ {
ReadOnlyMemory password = keyEntryData.GetCurrentValue();
var validateCommand = new ValidateCommand(password, _oathData);
ValidateResponse verifyResponse = Connection.SendCommand(validateCommand);
@@ -140,8 +139,9 @@ public bool TryVerifyPassword(ReadOnlyMemory password)
{
return verifyResponse.GetData();
}
- if ((verifyResponse.StatusWord == SWConstants.InvalidCommandDataParameter)
- || (verifyResponse.StatusWord == SWConstants.ReferenceDataUnusable))
+
+ if (verifyResponse.StatusWord == SWConstants.InvalidCommandDataParameter
+ || verifyResponse.StatusWord == SWConstants.ReferenceDataUnusable)
{
return false;
}
@@ -184,7 +184,7 @@ public void SetPassword()
try
{
- if (KeyCollector!(keyEntryData) == true)
+ if (KeyCollector!(keyEntryData))
{
ReadOnlyMemory currentPassword = keyEntryData.GetCurrentValue();
ReadOnlyMemory newPassword = keyEntryData.GetNewValue();
@@ -379,7 +379,7 @@ public void UnsetPassword()
try
{
- if (KeyCollector!(keyEntryData) == true)
+ if (KeyCollector!(keyEntryData))
{
if (!TryUnsetPassword(keyEntryData.GetCurrentValue()))
{
@@ -472,6 +472,7 @@ public void UnsetPassword()
/// A boolean, true if the OATH application is unset, and
/// false otherwise.
///
- public bool TryUnsetPassword(ReadOnlyMemory password) => TrySetPassword(password, ReadOnlyMemory.Empty);
+ public bool TryUnsetPassword(ReadOnlyMemory password) =>
+ TrySetPassword(password, ReadOnlyMemory.Empty);
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs
index 5cab3ab9..5e07952d 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/ChallengeResponseAlgorithm.cs
@@ -23,7 +23,7 @@ public enum ChallengeResponseAlgorithm
/// The default value for the enumeration.
///
None = 0,
-
+
///
/// The Yubico OTP mode takes a 6 byte challenge and creates a
/// response using the Yubico OTP algorithm, where variable fields
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs
index e61ad480..7ad3a0b1 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureNdefCommand.cs
@@ -28,7 +28,7 @@ public class ConfigureNdefCommand : IYubiKeyCommand
private const int AccessCodeOffset = 56;
private readonly Slot _ndefSlot;
- private readonly byte[] _configurationBuffer;
+ private readonly byte[] _configurationBuffer;
///
/// The required size for the AccessCode buffer.
@@ -108,7 +108,7 @@ public ConfigureNdefCommand(Slot slot, ReadOnlySpan configuration, ReadOnl
public CommandApdu CreateCommandApdu() => new CommandApdu()
{
Ins = OtpConstants.RequestSlotInstruction,
- P1 =
+ P1 =
_ndefSlot == Slot.ShortPress
? OtpConstants.ProgramNDEFShortPress
: OtpConstants.ProgramNDEFLongPress,
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs
index f9843cfe..f07f2a02 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetDeviceInfoCommand.cs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.YubiKey.Management.Commands;
using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Management.Commands;
namespace Yubico.YubiKey.Otp.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs
index 3e7a8a5f..8405c469 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/SetLegacyDeviceConfigCommand.cs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.YubiKey.Management.Commands;
using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Management.Commands;
namespace Yubico.YubiKey.Otp.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs
index 5a75c48c..0ae137ee 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs
@@ -73,7 +73,7 @@ public NdefDataReader(ReadOnlySpan responseData)
byte typeLength = responseData[TypeLengthOffset];
byte dataLength = responseData[DataLengthOffset];
const int validTypeLength = 1;
-
+
if (typeLength != validTypeLength)
{
throw new NotSupportedException(ExceptionMessages.BadNdefRecordType);
@@ -215,7 +215,7 @@ private static (Encoding encoding, bool bomPresent) DetectCorrectUtf16Encoding(R
}
// RFC 2781 does say to give preference to big endian, so I guess that'll be the tie-breaker.
- return (score[0] >= score[1]) ? (Encoding.BigEndianUnicode, false) : (Encoding.Unicode, false);
+ return score[0] >= score[1] ? (Encoding.BigEndianUnicode, false) : (Encoding.Unicode, false);
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs
index 418a8b08..a4d9120c 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/OperationBase.cs
@@ -31,7 +31,8 @@ public abstract class OperationBase where T : OperationBase
///
/// The six-byte access code currently set to protect the OTP slot.
///
- protected Span CurrentAccessCode {
+ protected Span CurrentAccessCode
+ {
get => _currentAccessCode.Span;
set => _currentAccessCode = value.ToArray();
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs
index 7fb98118..1b0eede9 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.ExtendedFlags.cs
@@ -16,7 +16,7 @@
namespace Yubico.YubiKey.Otp
{
- public partial class OtpSettings where T: OperationBase
+ public partial class OtpSettings where T : OperationBase
{
///
/// Allows the serial number to be retrieved by holding down the touch button while inserting
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs
index d297a8d3..901b9e84 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs
@@ -90,10 +90,10 @@ public ResponseApdu Invoke(CommandApdu commandApdu, Type commandType, Type respo
ResponseApdu responseApdu =
responseByte switch
{
- Ctap1Message => new ResponseApdu(responseData),
- CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData),
- CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData),
- _ => new ResponseApdu(responseData, SWConstants.Success),
+ Ctap1Message => new ResponseApdu(responseData),
+ CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData),
+ CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData),
+ _ => new ResponseApdu(responseData, SWConstants.Success),
};
return responseApdu;
@@ -137,14 +137,14 @@ private static byte GetPacketCmd(byte[] packet) =>
(byte)(packet[4] & ~0x80);
private static int GetPacketBcnt(byte[] packet) =>
- (packet[5] << 8) | (packet[6]);
+ (packet[5] << 8) | packet[6];
private byte[] TransmitCommand(uint channelId, byte commandByte, byte[] data, out byte responseByte)
{
SendRequest(channelId, commandByte, data);
byte cmdByte = commandByte;
- if ((data.Length > 0) && (commandByte == CtapConstants.CtapHidCbor))
+ if (data.Length > 0 && commandByte == CtapConstants.CtapHidCbor)
{
cmdByte = data[0];
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs
index bbb95698..0f0542cc 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs
@@ -13,13 +13,13 @@
// limitations under the License.
using System;
+using System.Diagnostics;
using System.Globalization;
using System.Threading;
-using Yubico.YubiKey.Otp;
using Yubico.Core.Devices.Hid;
using Yubico.Core.Iso7816;
-using System.Diagnostics;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Otp;
namespace Yubico.YubiKey.Pipelines
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs
index b44db208..7723e7e4 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using Yubico.YubiKey.Otp.Commands;
using Yubico.Core.Iso7816;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Otp.Commands;
namespace Yubico.YubiKey.Pipelines
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs
index db08f300..8f372e8b 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs
@@ -14,10 +14,10 @@
using System;
using System.Security.Cryptography;
-using Yubico.YubiKey.Scp03.Commands;
-using Yubico.YubiKey.Scp03;
using Yubico.Core.Iso7816;
using Yubico.YubiKey.Cryptography;
+using Yubico.YubiKey.Scp03;
+using Yubico.YubiKey.Scp03.Commands;
namespace Yubico.YubiKey.Pipelines
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs
index 552aeac8..0188d1aa 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs
@@ -113,15 +113,15 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b
{
throw new ArgumentNullException(nameof(outputBuffer));
}
- if ((inputCount == 0) || ((inputCount & 7) != 0))
+ if (inputCount == 0 || (inputCount & 7) != 0)
{
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
ExceptionMessages.IncorrectPlaintextLength));
}
- if ((inputOffset < 0) || ((inputBuffer.Length - inputOffset) < inputCount) ||
- (outputOffset < 0) || (outputBuffer.Length - outputOffset < inputCount))
+ if (inputOffset < 0 || inputBuffer.Length - inputOffset < inputCount ||
+ outputOffset < 0 || outputBuffer.Length - outputOffset < inputCount)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs
index 73061e69..eb7221e7 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateDecryptCommand.cs
@@ -13,9 +13,9 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Globalization;
using System.Linq;
using Yubico.Core.Iso7816;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs
index 9eb890be..f08d1881 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateKeyAgreeCommand.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
+using System.Globalization;
using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Piv.Commands
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs
index 80fcff5c..2019d4e9 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateSignCommand.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Globalization;
-using System.Security.Cryptography;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
+using System.Security.Cryptography;
using Yubico.Core.Iso7816;
using Yubico.Core.Tlv;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs
index 7286ad5f..f371c294 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ChangeReferenceDataCommand.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
+using System.Globalization;
using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Piv.Commands
@@ -104,7 +104,7 @@ public byte SlotNumber
get => _slotNumber;
set
{
- if ((value != PivSlot.Pin) && (value != PivSlot.Puk))
+ if (value != PivSlot.Pin && value != PivSlot.Puk)
{
throw new ArgumentException(
string.Format(
@@ -170,8 +170,8 @@ public ChangeReferenceDataCommand(byte slotNumber, ReadOnlyMemory currentV
{
SlotNumber = slotNumber;
- if ((PivPinUtilities.IsValidPinLength(currentValue.Length) == false)
- || (PivPinUtilities.IsValidPinLength(newValue.Length) == false))
+ if (PivPinUtilities.IsValidPinLength(currentValue.Length) == false
+ || PivPinUtilities.IsValidPinLength(newValue.Length) == false)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs
index f2a1b057..2ae7dc98 100755
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs
@@ -15,9 +15,9 @@
using System;
using System.Globalization;
using System.Security.Cryptography;
-using Yubico.YubiKey.Cryptography;
using Yubico.Core.Iso7816;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Piv.Commands
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs
index 4c2d3197..3629b632 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using Yubico.Core.Iso7816;
@@ -296,13 +296,13 @@ private byte[] BuildGenerateKeyPairApduData()
int length = data.Length;
int valueLength = algorithmCount + pinPolicyCount + touchPolicyCount;
- if ((PinPolicy == PivPinPolicy.Default) || (PinPolicy == PivPinPolicy.None))
+ if (PinPolicy == PivPinPolicy.Default || PinPolicy == PivPinPolicy.None)
{
Array.Copy(data, indexTouchPolicy, data, indexPinPolicy, touchPolicyCount);
length -= pinPolicyCount;
valueLength -= pinPolicyCount;
}
- if ((TouchPolicy == PivTouchPolicy.Default) || (TouchPolicy == PivTouchPolicy.None))
+ if (TouchPolicy == PivTouchPolicy.Default || TouchPolicy == PivTouchPolicy.None)
{
length -= touchPolicyCount;
valueLength -= touchPolicyCount;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs
index 4a7d393e..94308f30 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GetDataCommand.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Collections.Generic;
using System.Buffers.Binary;
-using System.Linq;
+using System.Collections.Generic;
using System.Globalization;
+using System.Linq;
using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Piv.Commands
@@ -148,9 +148,9 @@ public int DataTag
get => _tag;
set
{
- if ((value < MinimumVendorTag) || (value > MaximumVendorTag))
+ if (value < MinimumVendorTag || value > MaximumVendorTag)
{
- if ((value != DiscoveryTag) && (value != BiometricGroupTemplateTag))
+ if (value != DiscoveryTag && value != BiometricGroupTemplateTag)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs
index 1b9d023c..d5cc536c 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ImportAsymmetricKeyCommand.cs
@@ -324,12 +324,12 @@ private byte[] BuildImportAsymmetricApduData()
_privateKey.EncodedPrivateKey.CopyTo(apduData);
Array.Copy(_policy, 0, apduData, offset, maximumPolicyLength);
- if ((PinPolicy == PivPinPolicy.Default) || (PinPolicy == PivPinPolicy.None))
+ if (PinPolicy == PivPinPolicy.Default || PinPolicy == PivPinPolicy.None)
{
Array.Copy(_policy, pinPolicyCount, apduData, offset, touchPolicyCount);
length -= pinPolicyCount;
}
- if ((TouchPolicy == PivTouchPolicy.Default) || (TouchPolicy == PivTouchPolicy.None))
+ if (TouchPolicy == PivTouchPolicy.Default || TouchPolicy == PivTouchPolicy.None)
{
length -= touchPolicyCount;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs
index bc5065ec..f8073dce 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs
@@ -117,7 +117,7 @@ public InitializeAuthenticateManagementKeyResponse(ResponseApdu responseApdu, Pi
int authTag = authReader.PeekTag();
ReadOnlyMemory value = authReader.ReadValue(authTag);
- if ((nestedTag != NestedTag) || ((authTag != MutualAuthTag) && (authTag != SingleAuthTag)))
+ if (nestedTag != NestedTag || (authTag != MutualAuthTag && authTag != SingleAuthTag))
{
throw new MalformedYubiKeyResponseException()
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs
index a5e4391f..a55adfff 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/PutDataCommand.cs
@@ -215,7 +215,7 @@ public int DataTag
get => _tag;
set
{
- if ((value < MinimumVendorTag) || (value > MaximumVendorTag))
+ if (value < MinimumVendorTag || value > MaximumVendorTag)
{
if (value != BiometricGroupTemplateTag)
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs
index 01f8be18..0fdcb788 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/ResetRetryCommand.cs
@@ -14,7 +14,6 @@
using System;
using System.Globalization;
-using System.Collections.Generic;
using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Piv.Commands
@@ -91,23 +90,15 @@ public sealed class ResetRetryCommand : IYubiKeyCommand
{
private const byte PivResetRetryInstruction = 0x2C;
- ///
- /// Gets the YubiKeyApplication to which this command belongs. For this
- /// command it's PIV.
- ///
- ///
- /// YubiKeyApplication.Piv
- ///
- public YubiKeyApplication Application => YubiKeyApplication.Piv;
+ private readonly ReadOnlyMemory _newPin;
private readonly ReadOnlyMemory _puk;
- private readonly ReadOnlyMemory _newPin;
-
// The default constructor explicitly defined. We don't want it to be
// used.
// Note that there is no object-initializer constructor. All the
// constructor args are secret byte arrays.
+ // ReSharper disable once UnusedMember.Local
private ResetRetryCommand()
{
throw new NotImplementedException();
@@ -149,8 +140,8 @@ private ResetRetryCommand()
///
public ResetRetryCommand(ReadOnlyMemory puk, ReadOnlyMemory newPin)
{
- if ((PivPinUtilities.IsValidPinLength(puk.Length) == false)
- || (PivPinUtilities.IsValidPinLength(newPin.Length) == false))
+ if (PivPinUtilities.IsValidPinLength(puk.Length) == false
+ || PivPinUtilities.IsValidPinLength(newPin.Length) == false)
{
throw new ArgumentException(
string.Format(
@@ -162,16 +153,26 @@ public ResetRetryCommand(ReadOnlyMemory puk, ReadOnlyMemory newPin)
_newPin = newPin;
}
+ ///
+ /// Gets the YubiKeyApplication to which this command belongs. For this
+ /// command it's PIV.
+ ///
+ ///
+ /// YubiKeyApplication.Piv
+ ///
+ public YubiKeyApplication Application => YubiKeyApplication.Piv;
+
///
- public CommandApdu CreateCommandApdu() => new CommandApdu
- {
- Ins = PivResetRetryInstruction,
- P2 = PivSlot.Pin,
- Data = PivPinUtilities.CopyTwoPinsWithPadding(_puk, _newPin),
- };
+ public CommandApdu CreateCommandApdu() =>
+ new CommandApdu
+ {
+ Ins = PivResetRetryInstruction,
+ P2 = PivSlot.Pin,
+ Data = PivPinUtilities.CopyTwoPinsWithPadding(_puk, _newPin),
+ };
///
public ResetRetryResponse CreateResponseForApdu(ResponseApdu responseApdu) =>
- new ResetRetryResponse(responseApdu);
+ new ResetRetryResponse(responseApdu);
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs
index d7143f12..9300984d 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/SetManagementKeyCommand.cs
@@ -191,7 +191,7 @@ private SetManagementKeyCommand()
/// The bytes that make up the new management key.
///
public SetManagementKeyCommand(ReadOnlyMemory newKey)
- : this (newKey, PivTouchPolicy.Default, PivAlgorithm.TripleDes)
+ : this(newKey, PivTouchPolicy.Default, PivAlgorithm.TripleDes)
{
}
@@ -221,7 +221,7 @@ public SetManagementKeyCommand(ReadOnlyMemory newKey)
/// The touch policy for the management key.
///
public SetManagementKeyCommand(ReadOnlyMemory newKey, PivTouchPolicy touchPolicy)
- : this (newKey, touchPolicy, PivAlgorithm.TripleDes)
+ : this(newKey, touchPolicy, PivAlgorithm.TripleDes)
{
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs
index 1d92207f..88ca6f8a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs
@@ -102,9 +102,9 @@ internal sealed class TripleDesForManagementKey : ISymmetricForManagementKey
// Byte length of the key data
private const int ValidTripleDesKeyLength = 24;
private const int ValidDesKeyLength = 8;
- private const int KeyOffsetFirst = 0;
+ private const int KeyOffsetFirst = 0;
private const int KeyOffsetSecond = 8;
- private const int KeyOffsetThird = 16;
+ private const int KeyOffsetThird = 16;
private const int TripleDesBlockSize = 8;
@@ -206,15 +206,15 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b
{
throw new ArgumentNullException(nameof(outputBuffer));
}
- if ((inputCount == 0) || ((inputCount & 7) != 0))
+ if (inputCount == 0 || (inputCount & 7) != 0)
{
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
ExceptionMessages.IncorrectPlaintextLength));
}
- if ((inputOffset < 0) || ((inputBuffer.Length - inputOffset) < inputCount) ||
- (outputOffset < 0) || (outputBuffer.Length - outputOffset < inputCount))
+ if (inputOffset < 0 || inputBuffer.Length - inputOffset < inputCount ||
+ outputOffset < 0 || outputBuffer.Length - outputOffset < inputCount)
{
throw new ArgumentException(
string.Format(
@@ -225,7 +225,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b
_ = _cryptoTransform.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- if ((!(_cryptoTransformA is null)) && (!(_cryptoTransformB is null)))
+ if (!(_cryptoTransformA is null) && !(_cryptoTransformB is null))
{
_ = _cryptoTransformB.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset);
_ = _cryptoTransformA.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset);
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs
index 915de6b2..a6c28d0e 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VerifyPinCommand.cs
@@ -13,8 +13,8 @@
// limitations under the License.
using System;
-using System.Globalization;
using System.Collections.Generic;
+using System.Globalization;
using Yubico.Core.Iso7816;
namespace Yubico.YubiKey.Piv.Commands
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs
index 7d0f8962..13463261 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
-using System.Globalization;
using System.Buffers.Binary;
-using Yubico.Core.Tlv;
+using System.Globalization;
+using System.Security.Cryptography;
using Yubico.Core.Logging;
+using Yubico.Core.Tlv;
namespace Yubico.YubiKey.Piv.Objects
{
@@ -464,9 +464,9 @@ private bool ReadDate(TlvReader tlvReader, ref byte elementsRead)
// property to be null. It was set to null when we called Clear
// before decoding.
bool isValid = tlvReader.TryReadValue(out ReadOnlyMemory theTime, DateTag);
- isValid = isValid && (theTime.Length <= 8);
+ isValid = isValid && theTime.Length <= 8;
- if (isValid && (theTime.Length > 0))
+ if (isValid && theTime.Length > 0)
{
var cpyObj = new Memory(new byte[8]);
theTime.CopyTo(cpyObj);
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs
index 26de8638..bc065823 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
using System.Globalization;
-using Yubico.YubiKey.Cryptography;
-using Yubico.Core.Tlv;
+using System.Security.Cryptography;
using Yubico.Core.Logging;
+using Yubico.Core.Tlv;
+using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Piv.Objects
{
@@ -352,7 +352,7 @@ private bool TryReadUniqueId(bool isValid, TlvReader tlvReader)
_log.LogInformation("Decode data into CardCapabilityContainer: UniqueId.");
if (tlvReader.TryReadValue(out ReadOnlyMemory encodedUniqueId, UniqueCardIdTag))
{
- if ((encodedUniqueId.Length == UniqueCardIdLength) &&
+ if (encodedUniqueId.Length == UniqueCardIdLength &&
MemoryExtensions.SequenceEqual(encodedUniqueId.Slice(AidOffset, AidLength).Span, ApplicationIdentifier.Span))
{
var dest = new Memory(_uniqueCardIdentifier);
@@ -384,17 +384,17 @@ private bool TryReadFixedValues(bool isValid, TlvReader tlvReader)
Tuple[] elementList = GetFixedTupleArray();
int index = 0;
- while (returnValue && (index < elementList.Length))
+ while (returnValue && index < elementList.Length)
{
if (elementList[index].Item2 == 0)
{
returnValue = tlvReader.TryReadValue(out ReadOnlyMemory currentValue, elementList[index].Item1) &&
- (currentValue.Length == elementList[index].Item2);
+ currentValue.Length == elementList[index].Item2;
}
else
{
returnValue = tlvReader.TryReadByte(out byte currentValue, elementList[index].Item1) &&
- (currentValue == elementList[index].Item3);
+ currentValue == elementList[index].Item3;
}
index++;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs
index f2ebd1c8..f232c378 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
using System.Globalization;
-using Yubico.YubiKey.Cryptography;
-using Yubico.Core.Tlv;
+using System.Security.Cryptography;
using Yubico.Core.Logging;
+using Yubico.Core.Tlv;
+using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Piv.Objects
{
@@ -340,9 +340,9 @@ private bool TryReadTrailingElements(bool isValid, TlvReader tlvReader)
_log.LogInformation("Decode data into CardholderUniqueId: TrailingElements.");
if (tlvReader.TryReadValue(out ReadOnlyMemory signature, SignatureTag))
{
- if ((signature.Length == 0) && tlvReader.TryReadValue(out ReadOnlyMemory lrc, LrcTag))
+ if (signature.Length == 0 && tlvReader.TryReadValue(out ReadOnlyMemory lrc, LrcTag))
{
- if ((lrc.Length == 0) && !tlvReader.HasData)
+ if (lrc.Length == 0 && !tlvReader.HasData)
{
return true;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs
index 1d7bcb04..baedf576 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Text;
using System.Globalization;
-using Yubico.Core.Tlv;
+using System.Text;
using Yubico.Core.Logging;
+using Yubico.Core.Tlv;
namespace Yubico.YubiKey.Piv.Objects
{
@@ -189,7 +189,7 @@ public override byte[] Encode()
return new byte[] { 0x53, 0x00 };
}
- if ((_onCardCerts == 0) && (_offCardCerts == 0) && (!(OffCardCertificateUrl is null)))
+ if (_onCardCerts == 0 && _offCardCerts == 0 && !(OffCardCertificateUrl is null))
{
throw new InvalidOperationException(
string.Format(
@@ -314,7 +314,7 @@ private void SetOffCardCertUrl(Uri? urlValue)
// the URL to null. Otherwise, leave it alone.
private void SetOffCardUrlNullIfZeroCerts()
{
- if ((_onCardCerts == 0) &&(_offCardCerts == 0))
+ if (_onCardCerts == 0 && _offCardCerts == 0)
{
_offCardCertUrl = null;
_urlBytes = null;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs
index 99cb3b0a..6c0fb8dc 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
-using System.Security.Cryptography;
using System.Globalization;
-using Yubico.Core.Tlv;
+using System.Security.Cryptography;
using Yubico.Core.Logging;
+using Yubico.Core.Tlv;
namespace Yubico.YubiKey.Piv.Objects
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs
index 5a0a49d4..a4c4ae8f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PivDataObject.cs
@@ -154,9 +154,9 @@ protected virtual bool IsValidAlternateTag(int dataTag)
{
if (dataTag != GetDefinedDataTag())
{
- if ((dataTag < MinVendorDataTag) || (dataTag > MaxVendorDataTag)
- || ((dataTag >= MinPivDataTag) && (dataTag <= MaxPivDataTag))
- || ((dataTag >= MinYubicoDataTag) && (dataTag <= MaxYubicoDataTag)))
+ if (dataTag < MinVendorDataTag || dataTag > MaxVendorDataTag
+ || (dataTag >= MinPivDataTag && dataTag <= MaxPivDataTag)
+ || (dataTag >= MinYubicoDataTag && dataTag <= MaxYubicoDataTag))
{
return false;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs
index 52639792..17cc9f79 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs
@@ -34,13 +34,14 @@ public static class PivDataTagExtensions
/// A boolean, true if the tag is allowed to be used in PUT DATA, and
/// false otherwise.
///
- public static bool IsValidTagForPut(this PivDataTag tag) => tag switch
- {
- PivDataTag.Printed => false,
- PivDataTag.Discovery => false,
- PivDataTag.BiometricGroupTemplate => false,
- _ => true,
- };
+ public static bool IsValidTagForPut(this PivDataTag tag) =>
+ tag switch
+ {
+ PivDataTag.Printed => false,
+ PivDataTag.Discovery => false,
+ PivDataTag.BiometricGroupTemplate => false,
+ _ => true,
+ };
///
/// Is the given encoding valid for PUT DATA using the specified tag.
@@ -63,6 +64,7 @@ public static class PivDataTagExtensions
public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory encoding)
{
TlvReader? tlvReader = GetTlvReader(tag, encoding);
+
if (tlvReader is null)
{
return false;
@@ -70,6 +72,7 @@ public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory encoding)
{
int expectedTag = PivPutDataTag;
- if ((tag == PivDataTag.Discovery) || (tag == PivDataTag.BiometricGroupTemplate))
+
+ if (tag == PivDataTag.Discovery || tag == PivDataTag.BiometricGroupTemplate)
{
expectedTag = (int)tag;
}
@@ -309,7 +334,8 @@ public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory value = tlvReader.ReadValue(expectedFormat[index]);
- returnValue = expectedFormat[index + 1] != 0 ?
- value.Length <= expectedFormat[index + 1] : value.Length == expectedFormat[index + 2];
+
+ returnValue = expectedFormat[index + 1] != 0
+ ? value.Length <= expectedFormat[index + 1]
+ : value.Length == expectedFormat[index + 2];
index += 3;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs
index e89f939f..89655331 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs
@@ -101,7 +101,7 @@ public static PivEccPrivateKey CreateEccPrivateKey(ReadOnlyMemory encodedP
{
var tlvReader = new TlvReader(encodedPrivateKey);
- if ((tlvReader.HasData == false) || (tlvReader.PeekTag() != EccTag))
+ if (tlvReader.HasData == false || tlvReader.PeekTag() != EccTag)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs
index 04dad78e..d3ba079f 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPublicKey.cs
@@ -56,11 +56,6 @@ public sealed class PivEccPublicKey : PivPublicKey
private Memory _publicPoint;
- ///
- /// Contains the public point: 04 || x-coordinate || y-coordinate.
- ///
- public ReadOnlySpan PublicPoint => _publicPoint.Span;
-
// The default constructor. We don't want it to be used by anyone outside
// this class.
private PivEccPublicKey()
@@ -99,6 +94,11 @@ public PivEccPublicKey(ReadOnlySpan publicPoint)
}
}
+ ///
+ /// Contains the public point: 04 || x-coordinate || y-coordinate.
+ ///
+ public ReadOnlySpan PublicPoint => _publicPoint.Span;
+
///
/// Try to create a new instance of an ECC public key object based on the
/// encoding.
@@ -119,9 +119,8 @@ public PivEccPublicKey(ReadOnlySpan publicPoint)
/// True if the method was able to create a new RSA public key object,
/// false otherwise.
///
- internal static bool TryCreate(
- out PivPublicKey publicKeyObject,
- ReadOnlyMemory encodedPublicKey)
+ internal static bool TryCreate(out PivPublicKey publicKeyObject,
+ ReadOnlyMemory encodedPublicKey)
{
var returnValue = new PivEccPublicKey();
publicKeyObject = returnValue;
@@ -130,15 +129,18 @@ internal static bool TryCreate(
{
var tlvReader = new TlvReader(encodedPublicKey);
int tag = tlvReader.PeekTag(2);
+
if (tag == PublicKeyTag)
{
tlvReader = tlvReader.ReadNestedTlv(tag);
}
ReadOnlyMemory value = null;
- while (tlvReader.HasData == true)
+
+ while (tlvReader.HasData)
{
tag = tlvReader.PeekTag();
+
if (tag != EccTag)
{
return false;
@@ -171,10 +173,12 @@ private bool LoadEccPublicKey(ReadOnlySpan publicPoint)
{
case EccP256PublicKeySize:
Algorithm = PivAlgorithm.EccP256;
+
break;
case EccP384PublicKeySize:
Algorithm = PivAlgorithm.EccP384;
+
break;
default:
@@ -187,10 +191,12 @@ private bool LoadEccPublicKey(ReadOnlySpan publicPoint)
}
var tlvWriter = new TlvWriter();
+
using (tlvWriter.WriteNestedTlv(PublicKeyTag))
{
tlvWriter.WriteValue(EccTag, publicPoint);
}
+
PivEncodedKey = tlvWriter.Encode();
// The Metadate encoded key is the contents of the nested. So set
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs
index 512e4a83..acd280a2 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs
@@ -13,10 +13,8 @@
// limitations under the License.
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
-using System.Linq;
using Yubico.Core.Tlv;
namespace Yubico.YubiKey.Piv
@@ -140,56 +138,6 @@ public class PivMetadata
private const int RetriesTag = 6;
- ///
- /// The slot for the metadata listed in this instance.
- ///
- public int Slot { get; private set; }
-
- ///
- /// The algorithm of the key in the specified slot.
- /// Note that if a slot is empty, the Algorithm will be
- /// PivAlgorithm.None.
- ///
- public PivAlgorithm Algorithm { get; private set; }
-
- ///
- /// If the key is PIN, PUK, or management, is it the default value?
- /// If the key is asymmetric, is it the imported or generated?
- /// If the slot is empty, the status will be Unknown.
- ///
- public PivKeyStatus KeyStatus { get; private set; }
-
- ///
- /// The policy for requiring the PIN before operations using the key in
- /// the given slot.
- ///
- public PivPinPolicy PinPolicy { get; private set; }
-
- ///
- /// The policy for requiring touch before operations using the key in
- /// the given slot.
- ///
- public PivTouchPolicy TouchPolicy { get; private set; }
-
- ///
- /// The public key associated with the private key in the given slot.
- ///
- public PivPublicKey PublicKey { get; private set; }
-
- ///
- /// The total number of wrong PINs or PUKs that can be entered before the
- /// PIN or PUK will be locked. If the slot is not PIN or PUK, this value
- /// will be -1, indicating the count is unknown.
- ///
- public int RetryCount { get; private set; }
-
- ///
- /// How many PIN or PUK retries remain before the PIN or PUK will be
- /// locked. If the slot is not PIN or PUK, this value will be -1,
- /// indicating the count is unknown.
- ///
- public int RetriesRemaining { get; private set; }
-
///
/// The constructor that takes in the metadata encoding returned by the
/// YubiKey in response to the Get metadata command, along with the slot.
@@ -224,7 +172,7 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber)
var tlvReader = new TlvReader(responseData);
- while (tlvReader.HasData == true)
+ while (tlvReader.HasData)
{
int tag = tlvReader.PeekTag();
ReadOnlyMemory value = tlvReader.ReadValue(tag);
@@ -241,36 +189,41 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber)
// Algorithm
// One byte, no more, no less.
ThrowIfNotLength(value, 1);
- Debug.Assert((value.Span[0] == 0xFF) || (value.Span[0] == 0x03)
- || (value.Span[0] == 0x08) || (value.Span[0] == 0x0A) || (value.Span[0] == 0x0C)
- || (value.Span[0] == 0x06) || (value.Span[0] == 0x07)
- || (value.Span[0] == 0x11) || (value.Span[0] == 0x14));
+
+ Debug.Assert(value.Span[0] == 0xFF || value.Span[0] == 0x03
+ || value.Span[0] == 0x08 || value.Span[0] == 0x0A || value.Span[0] == 0x0C
+ || value.Span[0] == 0x06 || value.Span[0] == 0x07
+ || value.Span[0] == 0x11 || value.Span[0] == 0x14);
Algorithm = (PivAlgorithm)value.Span[0];
+
break;
case PolicyTag:
// Policy: PIN and touch policy
// Two bytes, no more, no less.
ThrowIfNotLength(value, 2);
- Debug.Assert((value.Span[0] >= 0) && (value.Span[0] <= 3));
- Debug.Assert((value.Span[1] >= 0) && (value.Span[1] <= 3));
+ Debug.Assert(value.Span[0] >= 0 && value.Span[0] <= 3);
+ Debug.Assert(value.Span[1] >= 0 && value.Span[1] <= 3);
// If the value is 0, that means Default. Otherwise, the
// value should be 1, 2, or 3 for Never, Once, and
// Always with PIN policy, and 1, 2, or 3 for Never,
// Always, and Cached with touch policy.
PinPolicy = PivPinPolicy.Default;
+
if (value.Span[0] != 0)
{
PinPolicy = (PivPinPolicy)value.Span[0];
}
TouchPolicy = PivTouchPolicy.Default;
+
if (value.Span[1] != 0)
{
TouchPolicy = (PivTouchPolicy)value.Span[1];
}
+
break;
case OriginTag:
@@ -278,14 +231,16 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber)
// One byte, no more, no less.
// 1 means generated, 2 means imported.
ThrowIfNotLength(value, 1);
- Debug.Assert((value.Span[0] == 1) || (value.Span[0] == 2));
+ Debug.Assert(value.Span[0] == 1 || value.Span[0] == 2);
KeyStatus = (PivKeyStatus)value.Span[0];
+
break;
case PublicTag:
// Public: public key partner to the private key in the
// slot
PublicKey = PivPublicKey.Create(value);
+
break;
case DefaultTag:
@@ -295,10 +250,12 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber)
ThrowIfNotLength(value, 1);
KeyStatus = PivKeyStatus.Default;
+
if (value.Span[0] == 0)
{
KeyStatus = PivKeyStatus.NotDefault;
}
+
break;
case RetriesTag:
@@ -309,11 +266,62 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber)
RetryCount = (int)value.Span[0];
RetriesRemaining = (int)value.Span[1];
+
break;
}
}
}
+ ///
+ /// The slot for the metadata listed in this instance.
+ ///
+ public int Slot { get; private set; }
+
+ ///
+ /// The algorithm of the key in the specified slot.
+ /// Note that if a slot is empty, the Algorithm will be
+ /// PivAlgorithm.None.
+ ///
+ public PivAlgorithm Algorithm { get; private set; }
+
+ ///
+ /// If the key is PIN, PUK, or management, is it the default value?
+ /// If the key is asymmetric, is it the imported or generated?
+ /// If the slot is empty, the status will be Unknown.
+ ///
+ public PivKeyStatus KeyStatus { get; private set; }
+
+ ///
+ /// The policy for requiring the PIN before operations using the key in
+ /// the given slot.
+ ///
+ public PivPinPolicy PinPolicy { get; private set; }
+
+ ///
+ /// The policy for requiring touch before operations using the key in
+ /// the given slot.
+ ///
+ public PivTouchPolicy TouchPolicy { get; private set; }
+
+ ///
+ /// The public key associated with the private key in the given slot.
+ ///
+ public PivPublicKey PublicKey { get; private set; }
+
+ ///
+ /// The total number of wrong PINs or PUKs that can be entered before the
+ /// PIN or PUK will be locked. If the slot is not PIN or PUK, this value
+ /// will be -1, indicating the count is unknown.
+ ///
+ public int RetryCount { get; private set; }
+
+ ///
+ /// How many PIN or PUK retries remain before the PIN or PUK will be
+ /// locked. If the slot is not PIN or PUK, this value will be -1,
+ /// indicating the count is unknown.
+ ///
+ public int RetriesRemaining { get; private set; }
+
private static void ThrowIfNotLength(ReadOnlyMemory value, int length)
{
if (value.Length != length)
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs
index ac9881c7..080f4b39 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPinUtilities.cs
@@ -93,7 +93,7 @@ internal static class PivPinUtilities
/// True if pinLength is a valid PIV PIN length, or False otherwise.
///
public static bool IsValidPinLength(int pinLength) =>
- (pinLength >= MinimumPinLength) && (pinLength <= MaximumPinLength);
+ pinLength >= MinimumPinLength && pinLength <= MaximumPinLength;
///
/// Determine, based on the , what the
@@ -201,8 +201,8 @@ public static byte[] CopySinglePinWithPadding(ReadOnlyMemory pin)
///
public static byte[] CopyTwoPinsWithPadding(ReadOnlyMemory firstPin, ReadOnlyMemory secondPin)
{
- if ((IsValidPinLength(firstPin.Length) == false)
- || (IsValidPinLength(secondPin.Length) == false))
+ if (IsValidPinLength(firstPin.Length) == false
+ || IsValidPinLength(secondPin.Length) == false)
{
throw new ArgumentException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs
index 46d77c87..e294c230 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPrivateKey.cs
@@ -118,7 +118,7 @@ public static PivPrivateKey Create(ReadOnlyMemory encodedPrivateKey)
tag = encodedPrivateKey.Span[0];
}
- switch(tag)
+ switch (tag)
{
default:
throw new ArgumentException(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs
index 5ced69cb..2e680dc4 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs
@@ -144,8 +144,8 @@ public PivRsaPrivateKey(
ExceptionMessages.InvalidPrivateKeyData)),
};
- if ((primeQ.Length != primeP.Length) || (exponentP.Length != primeP.Length)
- || (exponentQ.Length != primeP.Length) || (coefficient.Length != primeP.Length))
+ if (primeQ.Length != primeP.Length || exponentP.Length != primeP.Length
+ || exponentQ.Length != primeP.Length || coefficient.Length != primeP.Length)
{
throw new ArgumentException(
string.Format(
@@ -200,7 +200,7 @@ public static PivRsaPrivateKey CreateRsaPrivateKey(ReadOnlyMemory encodedP
int tag = tlvReader.PeekTag();
ReadOnlyMemory temp = tlvReader.ReadValue(tag);
- if ((tag <= 0) || (tag > CrtComponentCount))
+ if (tag <= 0 || tag > CrtComponentCount)
{
continue;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs
index b422cc32..958b1087 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPublicKey.cs
@@ -76,18 +76,8 @@ public sealed class PivRsaPublicKey : PivPublicKey
private Memory _modulus;
- ///
- /// Contains the modulus portion of the RSA public key.
- ///
- public ReadOnlySpan Modulus => _modulus.Span;
-
private Memory _publicExponent;
- ///
- /// Contains the public exponent portion of the RSA public key.
- ///
- public ReadOnlySpan PublicExponent => _publicExponent.Span;
-
// The default constructor. We don't want it to be used by anyone outside
// this class.
private PivRsaPublicKey()
@@ -120,6 +110,16 @@ public PivRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExpo
}
}
+ ///
+ /// Contains the modulus portion of the RSA public key.
+ ///
+ public ReadOnlySpan Modulus => _modulus.Span;
+
+ ///
+ /// Contains the public exponent portion of the RSA public key.
+ ///
+ public ReadOnlySpan PublicExponent => _publicExponent.Span;
+
///
/// Try to create a new instance of an RSA public key object based on the
/// encoding.
@@ -140,9 +140,8 @@ public PivRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExpo
/// True if the method was able to create a new RSA public key object,
/// false otherwise.
///
- internal static bool TryCreate(
- out PivPublicKey publicKeyObject,
- ReadOnlyMemory encodedPublicKey)
+ internal static bool TryCreate(out PivPublicKey publicKeyObject,
+ ReadOnlyMemory encodedPublicKey)
{
var returnValue = new PivRsaPublicKey();
publicKeyObject = returnValue;
@@ -151,6 +150,7 @@ internal static bool TryCreate(
{
var tlvReader = new TlvReader(encodedPublicKey);
int tag = tlvReader.PeekTag(2);
+
if (tag == PublicKeyTag)
{
tlvReader = tlvReader.ReadNestedTlv(tag);
@@ -158,18 +158,21 @@ internal static bool TryCreate(
var valueArray = new ReadOnlyMemory[PublicComponentCount];
- while (tlvReader.HasData == true)
+ while (tlvReader.HasData)
{
int valueIndex;
tag = tlvReader.PeekTag();
+
switch (tag)
{
case ModulusTag:
valueIndex = ModulusIndex;
+
break;
case ExponentTag:
valueIndex = ExponentIndex;
+
break;
default:
@@ -201,15 +204,18 @@ internal static bool TryCreate(
private bool LoadRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan publicExponent)
{
int sliceIndex = SliceIndex1024;
+
switch (modulus.Length)
{
case Rsa1024BlockSize:
Algorithm = PivAlgorithm.Rsa1024;
+
break;
case Rsa2048BlockSize:
Algorithm = PivAlgorithm.Rsa2048;
sliceIndex = SliceIndex2048;
+
break;
default:
@@ -229,11 +235,13 @@ private bool LoadRsaPublicKey(ReadOnlySpan modulus, ReadOnlySpan pub
}
var tlvWriter = new TlvWriter();
+
using (tlvWriter.WriteNestedTlv(PublicKeyTag))
{
tlvWriter.WriteValue(ModulusTag, modulus);
tlvWriter.WriteValue(ExponentTag, _exponentF4);
}
+
PivEncodedKey = tlvWriter.Encode();
// The Metadate encoded key is the contents of the nested. So set
@@ -256,12 +264,14 @@ private bool IsExponentF4(ReadOnlySpan exponent)
}
int index = 0;
+
while (exponent.Length - index > ValidExponentLength)
{
if (exponent[index] != 0)
{
return false;
}
+
index++;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs
index 493f81af..426ad163 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs
@@ -17,9 +17,9 @@
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
-using Yubico.YubiKey.Piv.Commands;
-using Yubico.YubiKey.Cryptography;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Cryptography;
+using Yubico.YubiKey.Piv.Commands;
namespace Yubico.YubiKey.Piv
{
@@ -436,7 +436,7 @@ private static bool IsCert(X509Certificate2 certificate, out byte[] certDer)
}
}
- return (certDer.Length > 0) && (certDer.Length < MaximumCertDerLength);
+ return certDer.Length > 0 && certDer.Length < MaximumCertDerLength;
}
// Does the cert in the object share the algorithm and key size?
@@ -511,8 +511,8 @@ private static bool IsCertNameAndValidity(bool isValidCert, byte[] certDer)
if (index >= tags.Length)
{
- returnValue = (value[4].Length < MaximumValidityValueLength) &&
- (value[5].Length < MaximumNameValueLength);
+ returnValue = value[4].Length < MaximumValidityValueLength &&
+ value[5].Length < MaximumNameValueLength;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs
index da62eb55..4a2ea8c4 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs
@@ -24,7 +24,6 @@ namespace Yubico.YubiKey.Piv
// agree.
public sealed partial class PivSession : IDisposable
{
-
///
/// Create a digital signature using the key in the given slot.
///
@@ -363,6 +362,7 @@ public byte[] KeyAgree(byte slotNumber, PivPublicKey correspondentPublicKey)
{
throw new ArgumentNullException(nameof(correspondentPublicKey));
}
+
if (!correspondentPublicKey.Algorithm.IsEcc())
{
throw new ArgumentException(
@@ -389,11 +389,10 @@ public byte[] KeyAgree(byte slotNumber, PivPublicKey correspondentPublicKey)
// Common code, this performs either Signing, Decryption, or Key
// Agreement. Just pass in the actual command to run, along with some
// other information.
- private byte[] PerformPrivateKeyOperation(
- byte slotNumber,
- IYubiKeyCommand> command,
- PivAlgorithm algorithm,
- string algorithmExceptionMessage)
+ private byte[] PerformPrivateKeyOperation(byte slotNumber,
+ IYubiKeyCommand> command,
+ PivAlgorithm algorithm,
+ string algorithmExceptionMessage)
{
bool pinRequired = true;
@@ -428,8 +427,8 @@ private byte[] PerformPrivateKeyOperation(
// PIN is not required.
// The only other case is Always which means we set the
// pinRequired to true, but we init that variable to true.
- if ((metadata.PinPolicy == PivPinPolicy.Never) ||
- ((metadata.PinPolicy == PivPinPolicy.Once) && PinVerified))
+ if (metadata.PinPolicy == PivPinPolicy.Never ||
+ (metadata.PinPolicy == PivPinPolicy.Once && PinVerified))
{
pinRequired = false;
}
@@ -466,7 +465,7 @@ private byte[] PerformPrivateKeyOperation(
}
}
- if (pinRequired == true)
+ if (pinRequired)
{
// This is the verify method that will throw an exception if the
// user cancels.
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs
index 0b8643d7..f59231b0 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs
@@ -16,8 +16,8 @@
using System.Globalization;
using System.Security;
using System.Security.Cryptography.X509Certificates;
-using Yubico.YubiKey.Piv.Commands;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Piv.Commands;
namespace Yubico.YubiKey.Piv
{
@@ -124,11 +124,10 @@ public sealed partial class PivSession : IDisposable
/// Mutual authentication was performed and the YubiKey was not
/// authenticated.
///
- public PivPublicKey GenerateKeyPair(
- byte slotNumber,
- PivAlgorithm algorithm,
- PivPinPolicy pinPolicy = PivPinPolicy.Default,
- PivTouchPolicy touchPolicy = PivTouchPolicy.Default)
+ public PivPublicKey GenerateKeyPair(byte slotNumber,
+ PivAlgorithm algorithm,
+ PivPinPolicy pinPolicy = PivPinPolicy.Default,
+ PivTouchPolicy touchPolicy = PivTouchPolicy.Default)
{
if (ManagementKeyAuthenticated == false)
{
@@ -137,6 +136,7 @@ public PivPublicKey GenerateKeyPair(
var generateCommand = new GenerateKeyPairCommand(slotNumber, algorithm, pinPolicy, touchPolicy);
GenerateKeyPairResponse generateResponse = Connection.SendCommand(generateCommand);
+
return generateResponse.GetData();
}
@@ -229,11 +229,10 @@ public PivPublicKey GenerateKeyPair(
/// Mutual authentication was performed and the YubiKey was not
/// authenticated.
///
- public void ImportPrivateKey(
- byte slotNumber,
- PivPrivateKey privateKey,
- PivPinPolicy pinPolicy = PivPinPolicy.Default,
- PivTouchPolicy touchPolicy = PivTouchPolicy.Default)
+ public void ImportPrivateKey(byte slotNumber,
+ PivPrivateKey privateKey,
+ PivPinPolicy pinPolicy = PivPinPolicy.Default,
+ PivTouchPolicy touchPolicy = PivTouchPolicy.Default)
{
if (ManagementKeyAuthenticated == false)
{
@@ -242,6 +241,7 @@ public void ImportPrivateKey(
var importCommand = new ImportAsymmetricKeyCommand(privateKey, slotNumber, pinPolicy, touchPolicy);
ImportAsymmetricKeyResponse importResponse = Connection.SendCommand(importCommand);
+
if (importResponse.Status != ResponseStatus.Success)
{
throw new InvalidOperationException(importResponse.StatusMessage);
@@ -332,16 +332,19 @@ public void ImportCertificate(byte slotNumber, X509Certificate2 certificate)
byte[] certDer = certificate.GetRawCertData();
var tlvWriter = new TlvWriter();
+
using (tlvWriter.WriteNestedTlv(PivEncodingTag))
{
tlvWriter.WriteValue(PivCertTag, certDer);
tlvWriter.WriteByte(PivCompressionTag, 0);
tlvWriter.WriteValue(PivLrcTag, null);
}
+
byte[] encodedCert = tlvWriter.Encode();
var putCommand = new PutDataCommand((int)dataTag, encodedCert);
PutDataResponse putResponse = Connection.SendCommand(putCommand);
+
if (putResponse.Status != ResponseStatus.Success)
{
throw new InvalidOperationException(putResponse.StatusMessage);
@@ -395,10 +398,12 @@ public X509Certificate2 GetCertificate(byte slotNumber)
var tlvReader = new TlvReader(encodedCertData);
bool isValid = tlvReader.TryReadNestedTlv(out TlvReader nestedReader, PivEncodingTag);
- if (isValid == true)
+
+ if (isValid)
{
isValid = nestedReader.TryReadValue(out ReadOnlyMemory certData, PivCertTag);
- if (isValid == true)
+
+ if (isValid)
{
return new X509Certificate2(certData.ToArray());
}
@@ -415,7 +420,7 @@ public X509Certificate2 GetCertificate(byte slotNumber)
// will map the slot number to the appropriate DataTag.
private static PivDataTag GetCertDataTagFromSlotNumber(byte slotNumber)
{
- if ((slotNumber >= PivSlot.Retired1) && (slotNumber <= PivSlot.Retired20))
+ if (slotNumber >= PivSlot.Retired1 && slotNumber <= PivSlot.Retired20)
{
return PivDataTag.Retired1 + (slotNumber - PivSlot.Retired1);
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs
index af91b192..2059325a 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs
@@ -13,11 +13,10 @@
// limitations under the License.
using System;
-using System.Security;
using System.Globalization;
-using Yubico.YubiKey.Piv.Commands;
-using Yubico.YubiKey.Piv.Objects;
+using System.Security;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Piv.Commands;
namespace Yubico.YubiKey.Piv
{
@@ -239,9 +238,11 @@ public sealed partial class PivSession : IDisposable
///
public bool TryAuthenticateManagementKey(bool mutualAuthentication = true)
{
- _log.LogInformation($"Try to authenticate the management key: {(mutualAuthentication == true ? "mutual" : "single")} auth.");
+ _log.LogInformation(
+ $"Try to authenticate the management key: {(mutualAuthentication ? "mutual" : "single")} auth.");
PivPinOnlyMode currentMode = TryAuthenticatePinOnly(true);
+
if (currentMode.HasFlag(PivPinOnlyMode.PinProtected) || currentMode.HasFlag(PivPinOnlyMode.PinDerived))
{
return true;
@@ -309,7 +310,9 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication)
///
public void AuthenticateManagementKey(bool mutualAuthentication = true)
{
- _log.LogInformation($"Authenticate the management key: {(mutualAuthentication == true ? "mutual" : "single")} auth.");
+ _log.LogInformation(
+ $"Authenticate the management key: {(mutualAuthentication ? "mutual" : "single")} auth.");
+
if (TryAuthenticateManagementKey(mutualAuthentication) == false)
{
throw new OperationCanceledException(
@@ -671,6 +674,7 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK
if (setResponse.Status == ResponseStatus.Success)
{
ManagementKeyAlgorithm = newKeyAlgorithm;
+
return true;
}
@@ -685,6 +689,7 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK
keyEntryData.Clear();
keyEntryData.Request = KeyEntryRequest.Release;
+
if (!(KeyCollector is null))
{
_ = KeyCollector(keyEntryData);
@@ -820,10 +825,9 @@ public void ChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newKeyA
/// Mutual authentication was performed and the YubiKey was not
/// authenticated.
///
- public bool TryChangeManagementKey(
- ReadOnlyMemory currentKey,
- ReadOnlyMemory newKey,
- PivTouchPolicy touchPolicy = PivTouchPolicy.Default) =>
+ public bool TryChangeManagementKey(ReadOnlyMemory currentKey,
+ ReadOnlyMemory newKey,
+ PivTouchPolicy touchPolicy = PivTouchPolicy.Default) =>
TryChangeManagementKey(currentKey, newKey, touchPolicy, PivAlgorithm.TripleDes);
///
@@ -883,11 +887,10 @@ public bool TryChangeManagementKey(
/// Mutual authentication was performed and the YubiKey was not
/// authenticated.
///
- public bool TryChangeManagementKey(
- ReadOnlyMemory currentKey,
- ReadOnlyMemory newKey,
- PivTouchPolicy touchPolicy,
- PivAlgorithm newKeyAlgorithm)
+ public bool TryChangeManagementKey(ReadOnlyMemory currentKey,
+ ReadOnlyMemory newKey,
+ PivTouchPolicy touchPolicy,
+ PivAlgorithm newKeyAlgorithm)
{
CheckManagementKeyAlgorithm(newKeyAlgorithm, true);
@@ -896,11 +899,10 @@ public bool TryChangeManagementKey(
// Try to change the management key, even if the YubiKey is set to
// PIN-derived.
- private bool TryForcedChangeManagementKey(
- ReadOnlyMemory currentKey,
- ReadOnlyMemory newKey,
- PivTouchPolicy touchPolicy,
- PivAlgorithm newKeyAlgorithm)
+ private bool TryForcedChangeManagementKey(ReadOnlyMemory currentKey,
+ ReadOnlyMemory newKey,
+ PivTouchPolicy touchPolicy,
+ PivAlgorithm newKeyAlgorithm)
{
if (TryAuthenticateManagementKey(currentKey, true))
{
@@ -910,6 +912,7 @@ private bool TryForcedChangeManagementKey(
if (setResponse.Status == ResponseStatus.Success)
{
ManagementKeyAlgorithm = newKeyAlgorithm;
+
return true;
}
}
@@ -934,6 +937,7 @@ private void CheckManagementKeyAlgorithm(PivAlgorithm algorithm, bool checkMode)
if (checkMode)
{
PivPinOnlyMode mode = GetPinOnlyMode();
+
if (mode.HasFlag(PivPinOnlyMode.PinProtected) || mode.HasFlag(PivPinOnlyMode.PinDerived))
{
throw new InvalidOperationException(
@@ -944,16 +948,19 @@ private void CheckManagementKeyAlgorithm(PivAlgorithm algorithm, bool checkMode)
}
bool isValid = false;
+
switch (algorithm)
{
case PivAlgorithm.TripleDes:
isValid = true;
+
break;
case PivAlgorithm.Aes128:
case PivAlgorithm.Aes192:
case PivAlgorithm.Aes256:
isValid = _yubiKeyDevice.HasFeature(YubiKeyFeature.PivAesManagementKey);
+
break;
default:
@@ -996,10 +1003,10 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication, KeyEntry
ManagementKeyAuthenticationResult = AuthenticateManagementKeyResult.Unauthenticated;
ManagementKeyAuthenticated = false;
- while (KeyCollector(keyEntryData) == true)
+ while (KeyCollector(keyEntryData))
{
if (ManagementKeyAuthenticated = TryAuthenticateManagementKey(
- mutualAuthentication, keyEntryData.GetCurrentValue().Span, ManagementKeyAlgorithm))
+ mutualAuthentication, keyEntryData.GetCurrentValue().Span, ManagementKeyAlgorithm))
{
return true;
}
@@ -1017,10 +1024,9 @@ private bool TryAuthenticateWithKeyCollector(bool mutualAuthentication, KeyEntry
// if the auth succeeds.
// If auth works, return true, otherwise, return false.
// Throw an exception if the YubiKey fails to auth.
- private bool TryAuthenticateManagementKey(
- bool mutualAuthentication,
- ReadOnlySpan mgmtKey,
- PivAlgorithm algorithm)
+ private bool TryAuthenticateManagementKey(bool mutualAuthentication,
+ ReadOnlySpan mgmtKey,
+ PivAlgorithm algorithm)
{
var initCommand = new InitializeAuthenticateManagementKeyCommand(mutualAuthentication, algorithm);
InitializeAuthenticateManagementKeyResponse initResponse = Connection.SendCommand(initCommand);
@@ -1029,6 +1035,7 @@ private bool TryAuthenticateManagementKey(
CompleteAuthenticateManagementKeyResponse completeResponse = Connection.SendCommand(completeCommand);
ManagementKeyAuthenticationResult = completeResponse.GetData();
+
if (completeResponse.Status == ResponseStatus.Success)
{
// If Success, there are three possibilities, (1) this is
@@ -1037,7 +1044,8 @@ private bool TryAuthenticateManagementKey(
// off-card app authenticated, but the YubiKey itself did
// not.
// If case (3), throw an exception.
- if (ManagementKeyAuthenticationResult == AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed)
+ if (ManagementKeyAuthenticationResult ==
+ AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed)
{
throw new SecurityException(
string.Format(
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs
index 82c05bf2..aa373749 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs
@@ -13,11 +13,11 @@
// limitations under the License.
using System;
-using System.Security;
-using System.IO;
using System.Globalization;
-using Yubico.YubiKey.Piv.Commands;
+using System.IO;
+using System.Security;
using Yubico.Core.Tlv;
+using Yubico.YubiKey.Piv.Commands;
namespace Yubico.YubiKey.Piv
{
@@ -329,7 +329,7 @@ private int CheckWriteLength(string contentsName, long length)
{
maxLength = NewMaximumObjectLength;
}
- if (length > (maxLength * MsrootsObjectCount))
+ if (length > maxLength * MsrootsObjectCount)
{
throw new ArgumentOutOfRangeException(
contentsName, length,
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs
index 7017301a..204b581e 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs
@@ -15,9 +15,9 @@
using System;
using System.Globalization;
using System.Security.Cryptography;
+using Microsoft.Extensions.Logging;
using Yubico.YubiKey.Piv.Commands;
using Yubico.YubiKey.Piv.Objects;
-using Microsoft.Extensions.Logging;
namespace Yubico.YubiKey.Piv
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs
index 48d85024..4f384073 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs
@@ -13,12 +13,11 @@
// limitations under the License.
using System;
-using System.Security;
using System.Globalization;
-using System.Security.Cryptography;
+using System.Security;
+using Yubico.Core.Logging;
using Yubico.YubiKey.Piv.Commands;
using Yubico.YubiKey.Piv.Objects;
-using Yubico.Core.Logging;
namespace Yubico.YubiKey.Piv
{
@@ -121,6 +120,7 @@ public sealed partial class PivSession : IDisposable
public bool TryVerifyPin()
{
_log.LogInformation("Try to verify the PIV PIN with KeyCollector.");
+
if (KeyCollector is null)
{
throw new InvalidOperationException(
@@ -138,7 +138,7 @@ public bool TryVerifyPin()
try
{
- while (KeyCollector(keyEntryData) == true)
+ while (KeyCollector(keyEntryData))
{
if (TryVerifyPin(keyEntryData.GetCurrentValue(), out int? retriesRemaining))
{
@@ -185,6 +185,7 @@ public bool TryVerifyPin()
public void VerifyPin()
{
_log.LogInformation("Verify the PIV PIN.");
+
if (TryVerifyPin() == false)
{
throw new OperationCanceledException(
@@ -402,7 +403,8 @@ public bool TryVerifyPin(ReadOnlyMemory pin, out int? retriesRemaining)
///
public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCountPuk)
{
- _log.LogInformation("Change the PIV PIN and PUK retry counts: {PinCount}, {PukCount}.", newRetryCountPin, newRetryCountPuk);
+ _log.LogInformation("Change the PIV PIN and PUK retry counts: {PinCount}, {PukCount}.", newRetryCountPin,
+ newRetryCountPuk);
// This will validate the input.
var setRetriesCommand = new SetPinRetriesCommand(newRetryCountPin, newRetryCountPuk);
@@ -431,12 +433,14 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount
{
AuthenticateManagementKey();
}
+
if (!PinVerified)
{
VerifyPin();
}
SetPinRetriesResponse setRetriesResponse = Connection.SendCommand(setRetriesCommand);
+
if (setRetriesResponse.Status != ResponseStatus.Success)
{
throw new InvalidOperationException(setRetriesResponse.StatusMessage);
@@ -447,6 +451,7 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount
// By passing Empty, this method will use the default PIN.
SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _);
}
+
UpdateAdminData();
}
@@ -514,14 +519,15 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount
///
/// The remaining retries count indicates the PIN is blocked.
///
- public bool TryChangePinAndPukRetryCounts(
- ReadOnlyMemory managementKey,
- ReadOnlyMemory pin,
- byte newRetryCountPin,
- byte newRetryCountPuk,
- out int? retriesRemaining)
+ public bool TryChangePinAndPukRetryCounts(ReadOnlyMemory managementKey,
+ ReadOnlyMemory pin,
+ byte newRetryCountPin,
+ byte newRetryCountPuk,
+ out int? retriesRemaining)
{
- _log.LogInformation("Try to change the PIV PIN and PUK retry counts: {PinCount}, {PukCount} with supplied mgmt key and PIN.", newRetryCountPin, newRetryCountPuk);
+ _log.LogInformation(
+ "Try to change the PIV PIN and PUK retry counts: {PinCount}, {PukCount} with supplied mgmt key and PIN.",
+ newRetryCountPin, newRetryCountPuk);
// This will validate the input.
var setRetriesCommand = new SetPinRetriesCommand(newRetryCountPin, newRetryCountPuk);
@@ -549,6 +555,7 @@ public bool TryChangePinAndPukRetryCounts(
// By passing Empty, this method will use the default PIN.
SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _);
}
+
UpdateAdminData();
return true;
@@ -660,6 +667,7 @@ public bool TryChangePinAndPukRetryCounts(
public bool TryChangePin()
{
_log.LogInformation("Try to change the PIV PIN with KeyCollector.");
+
if (TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _))
{
return TryChangeReference(KeyEntryRequest.ChangePivPin, ChangePinOrPuk, mode);
@@ -693,6 +701,7 @@ public bool TryChangePin()
public void ChangePin()
{
_log.LogInformation("Change the PIV PIN.");
+
if (!TryChangePin())
{
throw new OperationCanceledException(
@@ -768,9 +777,11 @@ public void ChangePin()
///
/// The remaining retries count indicates the PIN is blocked.
///
- public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory newPin, out int? retriesRemaining)
+ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory newPin,
+ out int? retriesRemaining)
{
_log.LogInformation("Try to change the PIV PIN with supplied PINs.");
+
if (TryGetChangePinMode(currentPin, out PivPinOnlyMode mode, out retriesRemaining))
{
var changeCommand = new ChangeReferenceDataCommand(PivSlot.Pin, currentPin, newPin);
@@ -782,6 +793,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n
{
SetPinOnlyMode(newPin, mode, out retriesRemaining);
}
+
UpdateAdminData();
return true;
@@ -886,6 +898,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n
public bool TryChangePuk()
{
_log.LogInformation("Try to change the PIV PUK with KeyCollector.");
+
return TryChangeReference(KeyEntryRequest.ChangePivPuk, ChangePinOrPuk, PivPinOnlyMode.None);
}
@@ -914,6 +927,7 @@ public bool TryChangePuk()
public void ChangePuk()
{
_log.LogInformation("Change the PIV PUK.");
+
if (TryChangeReference(KeyEntryRequest.ChangePivPuk, ChangePinOrPuk, PivPinOnlyMode.None) == false)
{
throw new OperationCanceledException(
@@ -965,7 +979,8 @@ public void ChangePuk()
///
/// The remaining retries count indicates the PUK is blocked.
///
- public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory newPuk, out int? retriesRemaining)
+ public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory newPuk,
+ out int? retriesRemaining)
{
_log.LogInformation("Try to change the PIV PUK with supplied PUKs.");
var changeCommand = new ChangeReferenceDataCommand(PivSlot.Puk, currentPuk, newPuk);
@@ -1083,6 +1098,7 @@ public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory n
public bool TryResetPin()
{
_log.LogInformation("Try to reset the PIV PIN using the PIV PUK with KeyCollector.");
+
if (TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _))
{
return TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, mode);
@@ -1121,6 +1137,7 @@ public bool TryResetPin()
public void ResetPin()
{
_log.LogInformation("Reset the PIV PIN using the PIV PUK.");
+
if (TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, PivPinOnlyMode.None) == false)
{
throw new OperationCanceledException(
@@ -1216,11 +1233,9 @@ public bool TryResetPin(ReadOnlyMemory puk, ReadOnlyMemory newPin, o
// The delegate is a callback will perform the appropriate
// Command/Response operations (Change or Reset).
// If the mode is not None, then set the YubiKey to that mode.
- private bool TryChangeReference(
- KeyEntryRequest request,
- Func CommandResponse,
- PivPinOnlyMode mode
- )
+ private bool TryChangeReference(KeyEntryRequest request,
+ Func CommandResponse,
+ PivPinOnlyMode mode)
{
if (KeyCollector is null)
{
@@ -1237,7 +1252,7 @@ PivPinOnlyMode mode
try
{
- while (KeyCollector(keyEntryData) == true)
+ while (KeyCollector(keyEntryData))
{
ResponseStatus status = CommandResponse(keyEntryData);
@@ -1247,6 +1262,7 @@ PivPinOnlyMode mode
{
SetPinOnlyMode(keyEntryData.GetNewValue(), mode, out _);
}
+
if (request == KeyEntryRequest.ChangePivPin)
{
UpdateAdminData();
@@ -1282,6 +1298,7 @@ PivPinOnlyMode mode
private ResponseStatus ChangePinOrPuk(KeyEntryData keyEntryData)
{
byte slotNumber = PivSlot.Puk;
+
if (keyEntryData.Request == KeyEntryRequest.ChangePivPin)
{
slotNumber = PivSlot.Pin;
@@ -1289,6 +1306,7 @@ private ResponseStatus ChangePinOrPuk(KeyEntryData keyEntryData)
var changeCommand = new ChangeReferenceDataCommand(
slotNumber, keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue());
+
ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand);
// If success, GetData returns null.
@@ -1305,6 +1323,7 @@ private ResponseStatus ResetPin(KeyEntryData keyEntryData)
{
var resetCommand = new ResetRetryCommand(
keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue());
+
ResetRetryResponse resetResponse = Connection.SendCommand(resetCommand);
// If success, GetData returns null.
@@ -1333,13 +1352,15 @@ private void UpdateAdminData()
if (ManagementKeyAuthenticated)
{
bool isValid = TryReadObject(out AdminData adminData);
+
using (adminData)
{
if (!isValid || adminData.IsEmpty)
{
return;
}
- if (!adminData.PinProtected && (adminData.Salt is null))
+
+ if (!adminData.PinProtected && adminData.Salt is null)
{
return;
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs
index 78d14a52..32d43fc8 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs
@@ -16,10 +16,10 @@
using System.Globalization;
using System.Security;
using System.Security.Cryptography;
+using Yubico.Core.Logging;
+using Yubico.YubiKey.Cryptography;
using Yubico.YubiKey.Piv.Commands;
using Yubico.YubiKey.Piv.Objects;
-using Yubico.YubiKey.Cryptography;
-using Yubico.Core.Logging;
namespace Yubico.YubiKey.Piv
{
@@ -89,13 +89,16 @@ public PivPinOnlyMode GetPinOnlyMode()
_log.LogInformation("Get the PIV PIN-only mode of a YubiKey based on AdminData.");
PivPinOnlyMode returnValue = PivPinOnlyMode.PinProtectedUnavailable | PivPinOnlyMode.PinDerivedUnavailable;
+
if (TryReadObject(out AdminData adminData))
{
returnValue = PivPinOnlyMode.None;
+
if (adminData.PinProtected)
{
returnValue |= PivPinOnlyMode.PinProtected;
}
+
if (!(adminData.Salt is null))
{
returnValue |= PivPinOnlyMode.PinDerived;
@@ -211,11 +214,13 @@ public PivPinOnlyMode TryRecoverPinOnlyMode()
// to set the PukBlocked field in adminData to true, so make sure
// it is indeed true.
_ = BlockPinOrPuk(PivSlot.Puk);
+
using var adminData = new AdminData
{
PukBlocked = true,
PinProtected = true
};
+
WriteObject(adminData);
return PivPinOnlyMode.PinProtected;
@@ -240,6 +245,7 @@ public PivPinOnlyMode TryRecoverPinOnlyMode()
WriteObject(pinProtect);
PivPinOnlyMode protectMode = PivPinOnlyMode.None;
+
if (adminData.PinProtected)
{
SetPinOnlyMode(PivPinOnlyMode.PinProtected, ManagementKeyAlgorithm);
@@ -273,12 +279,15 @@ public PivPinOnlyMode TryRecoverPinOnlyMode()
// "correct, we want to leave it as is, except make sure the
// PinProtected property is false and the Salt is null.
// If that bit is set, then we want to clear ADMIN DATA.
- using AdminData adminData = returnValue.HasFlag(PivPinOnlyMode.PinDerivedUnavailable) ?
- new AdminData() : ReadObject();
+ using AdminData adminData = returnValue.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)
+ ? new AdminData()
+ : ReadObject();
+
if (!adminData.IsEmpty)
{
adminData.PinProtected = false;
}
+
adminData.SetSalt(ReadOnlyMemory.Empty);
WriteObject(adminData);
@@ -331,6 +340,7 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData)
bool tryPinDerived = true;
PivPinOnlyMode returnValue = PivPinOnlyMode.None;
+
if (trustAdminData)
{
returnValue = GetPinOnlyMode();
@@ -345,6 +355,7 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData)
try
{
KeyCollector = specialKeyCollector.KeyCollectorSpecial;
+
if (tryPinProtected)
{
returnValue = GetPrintedPinProtectedStatus(specialKeyCollector, UserKeyCollector);
@@ -358,8 +369,10 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData)
if (tryPinDerived)
{
using var adminData = new AdminData();
+
returnValue |= GetPinDerivedStatus(
- adminData, returnValue.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, UserKeyCollector);
+ adminData, returnValue.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector,
+ UserKeyCollector);
}
return returnValue;
@@ -379,9 +392,8 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData)
// authenticates, return PinProtected. If not, return Unavailable.
// If there is data but it is not PinProtectedData, the pinProtect object
// will be empty and return Unavailable.
- private PivPinOnlyMode GetPrintedPinProtectedStatus(
- SpecialKeyCollector specialKeyCollector,
- Func? UserKeyCollector)
+ private PivPinOnlyMode GetPrintedPinProtectedStatus(SpecialKeyCollector specialKeyCollector,
+ Func? UserKeyCollector)
{
// We could call the ReadObject method, but if the PIN is not
// verified, ReadObject won't collect and save it.
@@ -404,6 +416,7 @@ private PivPinOnlyMode GetPrintedPinProtectedStatus(
if (getDataResponse.Status == ResponseStatus.Success)
{
using var pinProtect = new PinProtectedData();
+
if (pinProtect.TryDecode(getDataResponse.GetData()))
{
if (pinProtect.ManagementKey is null)
@@ -442,11 +455,10 @@ private PivPinOnlyMode GetPrintedPinProtectedStatus(
// This will update the adminData object passed in with the contents of
// the ADMIN DATA storage location. This method expects the adminData to
// be empty.
- private PivPinOnlyMode GetPinDerivedStatus(
- AdminData adminData,
- bool isPinProtected,
- SpecialKeyCollector specialKeyCollector,
- Func? UserKeyCollector)
+ private PivPinOnlyMode GetPinDerivedStatus(AdminData adminData,
+ bool isPinProtected,
+ SpecialKeyCollector specialKeyCollector,
+ Func? UserKeyCollector)
{
// We could use the TryReadObject to get the admin data, but that
// returns a new object. We need to fill the incoming object with the
@@ -471,17 +483,19 @@ private PivPinOnlyMode GetPinDerivedStatus(
// If we have already collected the PIN, this call will do
// nothing (it won't collect it again).
specialKeyCollector.VerifyPinAndSave(this, UserKeyCollector);
+
// If we're already PIN-protected, then the current mgmt key
// is the PIN-protected value. So put the derived key into
// the new buffer and compare.
// If not, put it into the current buffer and authenticate.
_ = specialKeyCollector.DeriveKeyData(
(ReadOnlyMemory)adminData.Salt, ManagementKeyAlgorithm, isPinProtected);
+
if (isPinProtected)
{
if (MemoryExtensions.SequenceEqual(
- specialKeyCollector.GetCurrentMgmtKey().Span,
- specialKeyCollector.GetNewMgmtKey().Span))
+ specialKeyCollector.GetCurrentMgmtKey().Span,
+ specialKeyCollector.GetNewMgmtKey().Span))
{
return PivPinOnlyMode.PinDerived;
}
@@ -758,6 +772,7 @@ public void SetPinOnlyMode(PivPinOnlyMode pinOnlyMode, PivAlgorithm mgmtKeyAlgor
private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode, out int? retriesRemaining)
{
ReadOnlyMemory pinToUse = pin;
+
if (pin.Length == 0)
{
pinToUse = new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 });
@@ -769,6 +784,7 @@ private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode
try
{
KeyCollector = specialKeyCollector.KeyCollectorSpecial;
+
if (specialKeyCollector.TrySetPin(this, pinToUse, out retriesRemaining))
{
SetPinOnlyMode(specialKeyCollector, UserKeyCollector, pinOnlyMode, ManagementKeyAlgorithm);
@@ -786,11 +802,10 @@ private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode
// KeyCollector to obtain it.
// This method assumes that the caller has set this PivSession's
// KeyCollector to the special, and will reset it to the User's when done.
- private void SetPinOnlyMode(
- SpecialKeyCollector specialKeyCollector,
- Func? UserKeyCollector,
- PivPinOnlyMode pinOnlyMode,
- PivAlgorithm mgmtKeyAlgorithm)
+ private void SetPinOnlyMode(SpecialKeyCollector specialKeyCollector,
+ Func? UserKeyCollector,
+ PivPinOnlyMode pinOnlyMode,
+ PivAlgorithm mgmtKeyAlgorithm)
{
if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtectedUnavailable)
|| pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable))
@@ -811,7 +826,7 @@ private void SetPinOnlyMode(
// If the caller wants a Mode of None, we're going to ignore the
// mgmtKeyAlgorithm arg, and we're going to want to clear the
// YubiKey, so say it is a new algorithm.
- bool newAlgorithm = (mgmtKeyAlgorithm != ManagementKeyAlgorithm) || (pinOnlyMode == PivPinOnlyMode.None);
+ bool newAlgorithm = mgmtKeyAlgorithm != ManagementKeyAlgorithm || pinOnlyMode == PivPinOnlyMode.None;
// We're creating this variable so that we know which mode to set.
// We might need to set a mode because the caller requests it and it
@@ -828,6 +843,7 @@ private void SetPinOnlyMode(
newAlgorithm, ref newMode);
using var adminData = new AdminData();
+
if (pinOnlyCheck == PinOnlyCheck.CanContinue)
{
currentMode |= GetPinDerivedStatus(
@@ -857,7 +873,7 @@ private void SetPinOnlyMode(
// If the mgmt key has not yet been authenticated, then get it
// using the KeyCollector.
- if ((!currentMode.HasFlag(PivPinOnlyMode.PinProtected)) && (!currentMode.HasFlag(PivPinOnlyMode.PinDerived)))
+ if (!currentMode.HasFlag(PivPinOnlyMode.PinProtected) && !currentMode.HasFlag(PivPinOnlyMode.PinDerived))
{
// Actually, before we do that, check to see if the requested is
// None. It's possible that one or both of the modes is
@@ -936,24 +952,16 @@ private void SetPinOnlyMode(
}
}
- private enum PinOnlyCheck
- {
- Unavailable = 0,
- Complete = 1,
- CanContinue = 2,
- }
-
// Check the currentMode against pinOnlyMode, newAlgorithm, tested, and
// testedUnavailable.
// Set newMode and return a value based on the results of the comparison
// The tested arg is what we're testing for, PinProtected or PinDerived.
- private static PinOnlyCheck CheckPinOnlyStatus(
- PivPinOnlyMode currentMode,
- PivPinOnlyMode pinOnlyMode,
- PivPinOnlyMode tested,
- PivPinOnlyMode testedUnavailable,
- bool newAlgorithm,
- ref PivPinOnlyMode newMode)
+ private static PinOnlyCheck CheckPinOnlyStatus(PivPinOnlyMode currentMode,
+ PivPinOnlyMode pinOnlyMode,
+ PivPinOnlyMode tested,
+ PivPinOnlyMode testedUnavailable,
+ bool newAlgorithm,
+ ref PivPinOnlyMode newMode)
{
// Look at PinProtected.
// At this point, if the requested mode is PinProtected, and the
@@ -1023,6 +1031,7 @@ private void ClearPinOnly(PivPinOnlyMode currentMode, SpecialKeyCollector specia
specialKeyCollector.SetKeyData(
SpecialKeyCollector.SetKeyDataDefault, ReadOnlyMemory.Empty, true, PivAlgorithm.TripleDes);
+
specialKeyCollector.ChangeManagementKey(this, PivAlgorithm.TripleDes);
}
@@ -1032,6 +1041,7 @@ private void PutEmptyData(int dataTag)
var putCmd = new PutDataCommand(dataTag, emptyObject);
PutDataResponse putRsp = Connection.SendCommand(putCmd);
+
if (putRsp.Status != ResponseStatus.Success)
{
throw new InvalidOperationException(putRsp.StatusMessage);
@@ -1048,13 +1058,12 @@ private void PutEmptyData(int dataTag)
// PIN-protected. If that's the case, authMode will be set to
// PinProtected. Set the ref arg setPinProtected to true in this case.
// Otherwise, leave that arg alone.
- private void SetYubiKeyPinDerived(
- AdminData adminData,
- PivPinOnlyMode currentMode,
- PivAlgorithm mgmtKeyAlgorithm,
- SpecialKeyCollector specialKeyCollector,
- Func? UserKeyCollector,
- ref PivPinOnlyMode newMode)
+ private void SetYubiKeyPinDerived(AdminData adminData,
+ PivPinOnlyMode currentMode,
+ PivAlgorithm mgmtKeyAlgorithm,
+ SpecialKeyCollector specialKeyCollector,
+ Func? UserKeyCollector,
+ ref PivPinOnlyMode newMode)
{
// We need the actual PIN in order to derive the mgmt key, so even if
// the PIN has already been verified, collect it.
@@ -1090,15 +1099,15 @@ private void SetYubiKeyPinDerived(
// If the current key in specialKeyCollector is not the default, use that
// key data. That data is either the "pre-existing" mgmt key data, or it
// is the PIN-derived data.
- private void SetYubiKeyPinProtected(
- AdminData adminData,
- PivAlgorithm mgmtKeyAlgorithm,
- SpecialKeyCollector specialKeyCollector)
+ private void SetYubiKeyPinProtected(AdminData adminData,
+ PivAlgorithm mgmtKeyAlgorithm,
+ SpecialKeyCollector specialKeyCollector)
{
if (specialKeyCollector.IsCurrentKeyDefault())
{
specialKeyCollector.SetKeyData(
SpecialKeyCollector.SetKeyDataRandom, ReadOnlyMemory.Empty, true, mgmtKeyAlgorithm);
+
specialKeyCollector.ChangeManagementKey(this, mgmtKeyAlgorithm);
}
@@ -1132,8 +1141,7 @@ private void SetYubiKeyPinProtected(
// really is not PIN-derived.
// The only way to get a false return is if the PIN does not verify, and
// even then, only if the ADMIN DATA says the mgmt key is PinDerived.
- private bool TryGetChangePinMode(
- ReadOnlyMemorypin, out PivPinOnlyMode mode, out int? retriesRemaining)
+ private bool TryGetChangePinMode(ReadOnlyMemory pin, out PivPinOnlyMode mode, out int? retriesRemaining)
{
retriesRemaining = null;
@@ -1146,7 +1154,7 @@ private bool TryGetChangePinMode(
try
{
- if (!isValid || (adminData.Salt is null))
+ if (!isValid || adminData.Salt is null)
{
return true;
}
@@ -1168,16 +1176,17 @@ private bool TryGetChangePinMode(
var salt = (ReadOnlyMemory)adminData.Salt;
_ = specialKeyCollector.DeriveKeyData(salt, ManagementKeyAlgorithm, false);
+
specialKeyCollector.SetKeyData(
SpecialKeyCollector.SetKeyDataDefault, ReadOnlyMemory.Empty, true, PivAlgorithm.TripleDes);
// If this fails, then the mgmt key is not PIN-derived from the
// PIN and salt, so we'll say it is not PIN-derived.
if (!TryForcedChangeManagementKey(
- specialKeyCollector.GetCurrentMgmtKey(),
- specialKeyCollector.GetNewMgmtKey(),
- PivTouchPolicy.Never,
- PivAlgorithm.TripleDes))
+ specialKeyCollector.GetCurrentMgmtKey(),
+ specialKeyCollector.GetNewMgmtKey(),
+ PivTouchPolicy.Never,
+ PivAlgorithm.TripleDes))
{
return true;
}
@@ -1190,14 +1199,16 @@ private bool TryGetChangePinMode(
// If there is data in PRINTED, and it contains the same mgmt key
// that was derived from the PIN and Salt, then yes.
isValid = TryReadObject(out PinProtectedData pinProtect);
+
using (pinProtect)
{
- if (isValid && (!(pinProtect.ManagementKey is null)))
+ if (isValid && !(pinProtect.ManagementKey is null))
{
var mgmtKey = (ReadOnlyMemory)pinProtect.ManagementKey;
+
if (MemoryExtensions.SequenceEqual(
- specialKeyCollector.GetCurrentMgmtKey().Span,
- mgmtKey.Span))
+ specialKeyCollector.GetCurrentMgmtKey().Span,
+ mgmtKey.Span))
{
mode |= PivPinOnlyMode.PinProtected;
}
@@ -1224,12 +1235,16 @@ private bool TryGetChangePinMode(
return true;
}
+ private enum PinOnlyCheck
+ {
+ Unavailable = 0,
+ Complete = 1,
+ CanContinue = 2,
+ }
+
// This class keeps track of the key data and its length.
private sealed class MgmtKeyHolder : IDisposable
{
- // This property will be the key data, of the appropriate length.
- public Memory KeyData { get; private set; }
-
private const int PinDerivedSaltLength = 16;
private const int MaxKeyLength = 32;
private readonly byte[] _keyBuffer = new byte[MaxKeyLength];
@@ -1245,6 +1260,20 @@ public MgmtKeyHolder()
_disposed = false;
}
+ // This property will be the key data, of the appropriate length.
+ public Memory KeyData { get; private set; }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ CryptographicOperations.ZeroMemory(_keyData.Span);
+ _disposed = true;
+ }
+
// Copy the newData into the local buffer.
// Set the KeyData property to the actual key data. That is, if the
// newData is smaller than the internal buffer, then KeyData will be
@@ -1271,7 +1300,8 @@ public void SetKeyData(ReadOnlyMemory newData, PivAlgorithm algorithm)
do
{
randomObject.GetBytes(_keyBuffer, 0, newLength);
- } while (IsKeyDataWeak(algorithm));
+ }
+ while (IsKeyDataWeak(algorithm));
}
KeyData = _keyData.Slice(0, newLength);
@@ -1282,8 +1312,8 @@ public void SetKeyData(ReadOnlyMemory newData, PivAlgorithm algorithm)
// Return the salt.
// It is the responsibility of the caller to make sure the pin is the
// correct length.
- public ReadOnlyMemory DeriveKeyData(
- ReadOnlyMemory pin, ReadOnlyMemory salt, PivAlgorithm algorithm)
+ public ReadOnlyMemory DeriveKeyData(ReadOnlyMemory pin, ReadOnlyMemory salt,
+ PivAlgorithm algorithm)
{
ReadOnlyMemory returnValue = salt;
@@ -1297,7 +1327,8 @@ public ReadOnlyMemory DeriveKeyData(
{
randomObject.GetBytes(saltData, 0, PinDerivedSaltLength);
PerformKeyDerive(pin, saltData, algorithm);
- } while (IsKeyDataWeak(algorithm));
+ }
+ while (IsKeyDataWeak(algorithm));
}
else
{
@@ -1321,6 +1352,7 @@ public void PerformKeyDerive(ReadOnlyMemory pin, byte[] saltData, PivAlgor
byte[] result = Array.Empty();
byte[] pinData = pin.ToArray();
+
try
{
// This will use PBKDF2, with the PRF of HMAC with SHA-1.
@@ -1356,17 +1388,6 @@ public bool IsKeyDataWeak(PivAlgorithm algorithm)
return false;
}
-
- public void Dispose()
- {
- if (_disposed)
- {
- return;
- }
-
- CryptographicOperations.ZeroMemory(_keyData.Span);
- _disposed = true;
- }
}
private sealed class SpecialKeyCollector : IDisposable
@@ -1374,26 +1395,26 @@ private sealed class SpecialKeyCollector : IDisposable
public const int SetKeyDataBuffer = 1;
public const int SetKeyDataRandom = 2;
public const int SetKeyDataDefault = 4;
- private readonly Memory _defaultKey;
- private readonly MgmtKeyHolder _currentKey;
- private readonly MgmtKeyHolder _newKey;
private const int MaxPinLength = 8;
- private int _pinLength;
- private readonly Memory _pinMemory;
+ private readonly MgmtKeyHolder _currentKey;
+ private readonly Memory _defaultKey;
+ private readonly MgmtKeyHolder _newKey;
private readonly byte[] _pinData = new byte[MaxPinLength];
+ private readonly Memory _pinMemory;
private bool _disposed;
-
- public bool PinCollected { get; private set; }
+ private int _pinLength;
public SpecialKeyCollector()
{
- _defaultKey = new Memory(new byte[] {
+ _defaultKey = new Memory(new byte[]
+ {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
+
_currentKey = new MgmtKeyHolder();
_newKey = new MgmtKeyHolder();
@@ -1407,6 +1428,28 @@ public SpecialKeyCollector()
_disposed = false;
}
+ public bool PinCollected { get; private set; }
+
+ // Note that .NET recommends a Dispose method call Dispose(true) and
+ // GC.SuppressFinalize(this). The actual disposal is in the
+ // Dispose(bool) method.
+ //
+ // However, that does not apply to sealed classes.
+ // So the Dispose method will simply perform the
+ // "closing" process, no call to Dispose(bool) or GC.
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _currentKey.Dispose();
+ _newKey.Dispose();
+ CryptographicOperations.ZeroMemory(_pinMemory.Span);
+ _disposed = true;
+ }
+
// Check to see if the data is the default mgmt key.
public bool IsCurrentKeyDefault() =>
MemoryExtensions.SequenceEqual(_defaultKey.Span, _currentKey.KeyData.Span);
@@ -1435,12 +1478,14 @@ public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey,
if (setFlag == SetKeyDataBuffer)
{
dest.SetKeyData(keyData, algorithm);
+
return;
}
if (setFlag == SetKeyDataRandom)
{
dest.SetKeyData(ReadOnlyMemory.Empty, algorithm);
+
return;
}
@@ -1462,8 +1507,7 @@ public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey,
// will generate a new salt and try again.
// But this method will generate whatever key (weak or not) is the
// result if a salt is given.
- public ReadOnlyMemory DeriveKeyData(
- ReadOnlyMemory salt, PivAlgorithm algorithm, bool isNewKey)
+ public ReadOnlyMemory DeriveKeyData(ReadOnlyMemory salt, PivAlgorithm algorithm, bool isNewKey)
{
MgmtKeyHolder dest = isNewKey ? _newKey : _currentKey;
@@ -1494,9 +1538,8 @@ public void ChangeManagementKey(PivSession pivSession, PivAlgorithm algorithm)
// exception.
// Upon completion of this method, the correct mgmt key is in the current
// key.
- public void AuthMgmtKeyAndSave(
- PivSession pivSession,
- Func? UserKeyCollector)
+ public void AuthMgmtKeyAndSave(PivSession pivSession,
+ Func? UserKeyCollector)
{
// First, try the default key. If it works, we're done.
// If we reach this point, the special key collector has just been
@@ -1523,9 +1566,11 @@ public void AuthMgmtKeyAndSave(
try
{
- while (UserKeyCollector(keyEntryData) == true)
+ while (UserKeyCollector(keyEntryData))
{
- SetKeyData(SetKeyDataBuffer, keyEntryData.GetCurrentValue(), false, pivSession.ManagementKeyAlgorithm);
+ SetKeyData(SetKeyDataBuffer, keyEntryData.GetCurrentValue(), false,
+ pivSession.ManagementKeyAlgorithm);
+
if (pivSession.TryAuthenticateWithKeyCollector(true))
{
return;
@@ -1560,9 +1605,8 @@ public void AuthMgmtKeyAndSave(
// property.
// If the If the user cancels (the UserKeyCollector returns false),
// this method will throw an exception.
- public void VerifyPinAndSave(
- PivSession pivSession,
- Func? UserKeyCollector)
+ public void VerifyPinAndSave(PivSession pivSession,
+ Func? UserKeyCollector)
{
if (!TryVerifyPinAndSave(pivSession, UserKeyCollector, out _))
{
@@ -1576,10 +1620,9 @@ public void VerifyPinAndSave(
// Verify the PIN and save it in this.
// If the user cancels, return false.
- public bool TryVerifyPinAndSave(
- PivSession pivSession,
- Func? UserKeyCollector,
- out int? retriesRemaining)
+ public bool TryVerifyPinAndSave(PivSession pivSession,
+ Func? UserKeyCollector,
+ out int? retriesRemaining)
{
retriesRemaining = null;
@@ -1603,7 +1646,7 @@ public bool TryVerifyPinAndSave(
try
{
- while (UserKeyCollector(keyEntryData) == true)
+ while (UserKeyCollector(keyEntryData))
{
if (TrySetPin(pivSession, keyEntryData.GetCurrentValue(), out retriesRemaining))
{
@@ -1646,7 +1689,7 @@ public bool KeyCollectorSpecial(KeyEntryData keyEntryData)
return false;
}
- if (keyEntryData.IsRetry == true)
+ if (keyEntryData.IsRetry)
{
return false;
}
@@ -1661,36 +1704,19 @@ public bool KeyCollectorSpecial(KeyEntryData keyEntryData)
case KeyEntryRequest.AuthenticatePivManagementKey:
keyEntryData.SubmitValue(_currentKey.KeyData.Span);
+
return true;
case KeyEntryRequest.ChangePivManagementKey:
keyEntryData.SubmitValues(_currentKey.KeyData.Span, _newKey.KeyData.Span);
+
return true;
case KeyEntryRequest.VerifyPivPin:
keyEntryData.SubmitValue(_pinMemory.Slice(0, _pinLength).Span);
- return true;
- }
- }
- // Note that .NET recommends a Dispose method call Dispose(true) and
- // GC.SuppressFinalize(this). The actual disposal is in the
- // Dispose(bool) method.
- //
- // However, that does not apply to sealed classes.
- // So the Dispose method will simply perform the
- // "closing" process, no call to Dispose(bool) or GC.
- public void Dispose()
- {
- if (_disposed)
- {
- return;
+ return true;
}
-
- _currentKey.Dispose();
- _newKey.Dispose();
- CryptographicOperations.ZeroMemory(_pinMemory.Span);
- _disposed = true;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs
index 6ee0eff2..ebb62292 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs
@@ -13,13 +13,13 @@
// limitations under the License.
using System;
-using System.Security;
using System.Globalization;
-using Yubico.YubiKey.Piv.Commands;
+using System.Security;
+using Yubico.Core.Logging;
using Yubico.YubiKey.Cryptography;
-using Yubico.YubiKey.Scp03;
using Yubico.YubiKey.InterIndustry.Commands;
-using Yubico.Core.Logging;
+using Yubico.YubiKey.Piv.Commands;
+using Yubico.YubiKey.Scp03;
namespace Yubico.YubiKey.Piv
{
@@ -143,39 +143,9 @@ namespace Yubico.YubiKey.Piv
///
public sealed partial class PivSession : IDisposable
{
- private bool _disposed;
private readonly Logger _log = Log.GetLogger();
private readonly IYubiKeyDevice _yubiKeyDevice;
-
- ///
- /// The object that represents the connection to the YubiKey. Most
- /// applications will ignore this, but it can be used to call Commands
- /// directly.
- ///
- public IYubiKeyConnection Connection { get; private set; }
-
- ///
- /// The Delegate this class will call when it needs a PIN, PUK, or
- /// management key.
- ///
- ///
- /// The delegate provided will read the KeyEntryData which
- /// contains the information needed to determine what to collect and
- /// methods to submit what was collected. The delegate will return
- /// true for success or false for "cancel". A cancel will
- /// usually happen when the user has clicked a "Cancel" button. That is
- /// often the case when the user has entered the wrong value a number of
- /// times, the remaining tries count is getting low, and they would like
- /// to stop trying before the YubiKey is blocked.
- ///
- /// Note that the SDK will call the KeyCollector with a
- /// Request of Release when the process completes. In this
- /// case, the KeyCollector MUST NOT throw an exception. The
- /// Release is called from inside a finally block, and it
- /// is a bad idea to throw exceptions from inside finally.
- ///
- ///
- public Func? KeyCollector { get; set; }
+ private bool _disposed;
// The default constructor explicitly defined. We don't want it to be
// used.
@@ -253,16 +223,20 @@ public PivSession(IYubiKeyDevice yubiKey, StaticKeys scp03Keys)
private PivSession(StaticKeys? scp03Keys, IYubiKeyDevice yubiKey)
{
_log.LogInformation("Create a new instance of PivSession" + (scp03Keys is null ? "." : " over SCP03"));
+
if (yubiKey is null)
{
throw new ArgumentNullException(nameof(yubiKey));
}
- Connection = scp03Keys is null ?
- yubiKey.Connect(YubiKeyApplication.Piv) : yubiKey.ConnectScp03(YubiKeyApplication.Piv, scp03Keys);
+ Connection = scp03Keys is null
+ ? yubiKey.Connect(YubiKeyApplication.Piv)
+ : yubiKey.ConnectScp03(YubiKeyApplication.Piv, scp03Keys);
+
ResetAuthenticationStatus();
ManagementKeyAlgorithm = PivAlgorithm.TripleDes;
+
if (yubiKey.HasFeature(YubiKeyFeature.PivAesManagementKey))
{
var getMetadataCmd = new GetMetadataCommand(PivSlot.Management);
@@ -279,6 +253,68 @@ private PivSession(StaticKeys? scp03Keys, IYubiKeyDevice yubiKey)
_disposed = false;
}
+ ///
+ /// The object that represents the connection to the YubiKey. Most
+ /// applications will ignore this, but it can be used to call Commands
+ /// directly.
+ ///
+ public IYubiKeyConnection Connection { get; private set; }
+
+ ///
+ /// The Delegate this class will call when it needs a PIN, PUK, or
+ /// management key.
+ ///
+ ///
+ /// The delegate provided will read the KeyEntryData which
+ /// contains the information needed to determine what to collect and
+ /// methods to submit what was collected. The delegate will return
+ /// true for success or false for "cancel". A cancel will
+ /// usually happen when the user has clicked a "Cancel" button. That is
+ /// often the case when the user has entered the wrong value a number of
+ /// times, the remaining tries count is getting low, and they would like
+ /// to stop trying before the YubiKey is blocked.
+ ///
+ /// Note that the SDK will call the KeyCollector with a
+ /// Request of Release when the process completes. In this
+ /// case, the KeyCollector MUST NOT throw an exception. The
+ /// Release is called from inside a finally block, and it
+ /// is a bad idea to throw exceptions from inside finally.
+ ///
+ ///
+ public Func? KeyCollector { get; set; }
+
+ ///
+ /// When the PivSession object goes out of scope, this method is called.
+ /// It will close the session. The most important function of closing a
+ /// session is to "un-authenticate" the management key and "un-verify"
+ /// the PIN.
+ ///
+
+ // Note that .NET recommends a Dispose method call Dispose(true) and
+ // GC.SuppressFinalize(this). The actual disposal is in the
+ // Dispose(bool) method.
+ //
+ // However, that does not apply to sealed classes.
+ // So the Dispose method will simply perform the
+ // "closing" process, no call to Dispose(bool) or GC.
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ // At the moment, there is no "close session" method. So for now,
+ // just connect to the management application.
+ _ = Connection.SendCommand(new SelectApplicationCommand(YubiKeyApplication.Management));
+ KeyCollector = null;
+ ResetAuthenticationStatus();
+
+ Connection.Dispose();
+
+ _disposed = true;
+ }
+
// Reset any fields and properties related to authentication or
// verification to the initial state: not authenticated, verified, etc.
private void ResetAuthenticationStatus()
@@ -333,6 +369,7 @@ private void ResetAuthenticationStatus()
public PivMetadata GetMetadata(byte slotNumber)
{
_log.LogInformation("GetMetadata for slot number {0:X2}.", slotNumber);
+
if (_yubiKeyDevice.HasFeature(YubiKeyFeature.PivMetadata))
{
var metadataCommand = new GetMetadataCommand(slotNumber);
@@ -388,10 +425,11 @@ public PivMetadata GetMetadata(byte slotNumber)
public void ResetApplication()
{
_log.LogInformation("Reset the PIV application.");
+
// To reset, both the PIN and PUK must be blocked.
- if (BlockPinOrPuk(PivSlot.Pin) == true)
+ if (BlockPinOrPuk(PivSlot.Pin))
{
- if (BlockPinOrPuk(PivSlot.Puk) == true)
+ if (BlockPinOrPuk(PivSlot.Puk))
{
var resetCommand = new ResetPivCommand();
ResetPivResponse resetResponse = Connection.SendCommand(resetCommand);
@@ -399,6 +437,7 @@ public void ResetApplication()
if (resetResponse.Status == ResponseStatus.Success)
{
ResetAuthenticationStatus();
+
return;
}
}
@@ -425,14 +464,19 @@ private bool BlockPinOrPuk(byte slotNumber)
{
_log.LogInformation($"Block the {(slotNumber == 0x80 ? "PIN" : "PUK")}.");
int retriesRemaining;
+
do
{
- byte[] currentValue = new byte[] {
+ byte[] currentValue = new byte[]
+ {
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01
};
- byte[] newValue = new byte[] {
+
+ byte[] newValue = new byte[]
+ {
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
};
+
var changeCommand = new ChangeReferenceDataCommand(slotNumber, currentValue, newValue);
ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand);
@@ -442,41 +486,10 @@ private bool BlockPinOrPuk(byte slotNumber)
}
retriesRemaining = changeResponse.GetData() ?? 1;
-
- } while (retriesRemaining > 0);
-
- return true;
- }
-
- ///
- /// When the PivSession object goes out of scope, this method is called.
- /// It will close the session. The most important function of closing a
- /// session is to "un-authenticate" the management key and "un-verify"
- /// the PIN.
- ///
- // Note that .NET recommends a Dispose method call Dispose(true) and
- // GC.SuppressFinalize(this). The actual disposal is in the
- // Dispose(bool) method.
- //
- // However, that does not apply to sealed classes.
- // So the Dispose method will simply perform the
- // "closing" process, no call to Dispose(bool) or GC.
- public void Dispose()
- {
- if (_disposed)
- {
- return;
}
+ while (retriesRemaining > 0);
- // At the moment, there is no "close session" method. So for now,
- // just connect to the management application.
- _ = Connection.SendCommand(new SelectApplicationCommand(YubiKeyApplication.Management));
- KeyCollector = null;
- ResetAuthenticationStatus();
-
- Connection.Dispose();
-
- _disposed = true;
+ return true;
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs
index 1ce6850d..24d7e0e8 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSlot.cs
@@ -329,9 +329,9 @@ public static bool IsValidSlotNumber(byte slotNumber)
// something that is only dependent on some private const values, but
// the slots are almost certainly never going to change. If they do
// change, this code will need to be revisited.
- return (((slotNumber >= Pin) && (slotNumber <= Retired20))
- || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication))
- || (slotNumber == Attestation));
+ return (slotNumber >= Pin && slotNumber <= Retired20)
+ || (slotNumber >= Authentication && slotNumber <= CardAuthentication)
+ || slotNumber == Attestation;
}
///
@@ -370,10 +370,10 @@ public static bool IsValidSlotNumber(byte slotNumber)
///
public static bool IsValidSlotNumberForGenerate(byte slotNumber)
{
- return ((slotNumber != Management)
- && (((slotNumber >= Retired1) && (slotNumber <= Retired20))
- || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication))
- || (slotNumber == Attestation)));
+ return slotNumber != Management
+ && ((slotNumber >= Retired1 && slotNumber <= Retired20)
+ || (slotNumber >= Authentication && slotNumber <= CardAuthentication)
+ || slotNumber == Attestation);
}
///
@@ -415,9 +415,9 @@ public static bool IsValidSlotNumberForSigning(byte slotNumber)
// something that is only dependent on some private const values, but
// the slots are almost certainly never going to change. If they do
// change, this code will need to be revisited.
- return ((slotNumber != Management)
- && (((slotNumber >= Retired1) && (slotNumber <= Retired20))
- || ((slotNumber >= Authentication) && (slotNumber <= CardAuthentication))));
+ return slotNumber != Management
+ && ((slotNumber >= Retired1 && slotNumber <= Retired20)
+ || (slotNumber >= Authentication && slotNumber <= CardAuthentication));
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs
index ca454c04..975f27ce 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs
@@ -16,9 +16,9 @@
using System.IO;
using System.Linq;
using System.Security.Cryptography;
-using Yubico.YubiKey.Cryptography;
-using Yubico.Core.Iso7816;
using Yubico.Core.Cryptography;
+using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Scp03
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs
index f8d4f696..00b3b224 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/PutKeyResponse.cs
@@ -22,7 +22,7 @@ namespace Yubico.YubiKey.Scp03.Commands
///
internal class PutKeyResponse : Scp03Response, IYubiKeyResponseWithData>
{
- private byte[] _checksum;
+ private readonly byte[] _checksum;
public PutKeyResponse(ResponseApdu responseApdu)
: base(responseApdu)
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs
index 4f160ed4..e6073e18 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/Scp03Response.cs
@@ -40,7 +40,7 @@ public virtual void ThrowIfFailed()
Debug.Assert(Status == ResponseStatus.Success);
return;
default:
- throw new Exception();
+ throw new Exception();
}
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs
index 276592e6..d14cda86 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs
@@ -14,8 +14,8 @@
using System;
using System.Security.Cryptography;
-using Yubico.PlatformInterop;
using Yubico.Core.Cryptography;
+using Yubico.PlatformInterop;
using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.Scp03
@@ -40,11 +40,11 @@ public static byte[] Derive(
byte[] hostChallenge,
byte[] cardChallenge)
{
- if ((outputLenBits != 0x40) && (outputLenBits != 0x80))
+ if (outputLenBits != 0x40 && outputLenBits != 0x80)
{
throw new SecureChannelException(ExceptionMessages.IncorrectDerivationLength);
}
- if ((hostChallenge.Length != 8) || (cardChallenge.Length != 8))
+ if (hostChallenge.Length != 8 || cardChallenge.Length != 8)
{
throw new SecureChannelException(ExceptionMessages.InvalidChallengeLength);
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs
index 61b7e649..fbb352bf 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03CcidConnection.cs
@@ -13,10 +13,10 @@
// limitations under the License.
using System;
+using System.Linq;
+using Yubico.Core.Devices.SmartCard;
using Yubico.YubiKey.Pipelines;
using Yubico.YubiKey.Scp03;
-using Yubico.Core.Devices.SmartCard;
-using System.Linq;
namespace Yubico.YubiKey
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs
index a1ec3bff..50f8c5b4 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs
@@ -15,8 +15,8 @@
using System;
using System.Globalization;
using System.Security.Cryptography;
-using Yubico.YubiKey.Scp03.Commands;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Scp03.Commands;
namespace Yubico.YubiKey.Scp03
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs
index 88088b81..24647697 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Session.cs
@@ -15,8 +15,8 @@
using System;
using System.Linq;
using System.Security.Cryptography;
-using Yubico.YubiKey.Scp03.Commands;
using Yubico.Core.Iso7816;
+using Yubico.YubiKey.Scp03.Commands;
namespace Yubico.YubiKey.Scp03
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs
index 7e6fd70d..5f4f9cbe 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/StaticKeys.cs
@@ -86,7 +86,7 @@ public byte KeyVersionNumber
set
{
- if ((value != DefaultKvnValue) && ((value < MinimumKvnValue) || (value > MaximumKvnValue)))
+ if (value != DefaultKvnValue && (value < MinimumKvnValue || value > MaximumKvnValue))
{
throw new ArgumentException(ExceptionMessages.InvalidScp03Kvn);
}
@@ -201,7 +201,7 @@ public bool AreKeysSame(StaticKeys compareKeys)
&& ChannelMacKey.Span.SequenceEqual(compareKeys.ChannelMacKey.Span)
&& DataEncryptionKey.Span.SequenceEqual(compareKeys.DataEncryptionKey.Span))
{
- return true;
+ return true;
}
}
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs
index 2d372397..0461cce9 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs
@@ -12,11 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-using Yubico.Core.Devices.SmartCard;
-using Yubico.YubiKey.DeviceExtensions;
-using System.Diagnostics.CodeAnalysis;
using System;
+using System.Diagnostics.CodeAnalysis;
+using Yubico.Core.Devices.SmartCard;
using Yubico.Core.Logging;
+using Yubico.YubiKey.DeviceExtensions;
namespace Yubico.YubiKey
{
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs
index 21e3a0fc..b683d860 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs
@@ -134,7 +134,7 @@ public bool IsCanceled(byte commandByte)
{
if (commandByte == _commandByte)
{
- if(_notifyTask.Status == TaskStatus.Created)
+ if (_notifyTask.Status == TaskStatus.Created)
{
_notifyTask.Start();
}
@@ -154,10 +154,10 @@ public bool IsCanceled(byte commandByte)
// Any other value entered will be considered Release.
public void SdkUpdate(KeyEntryData keyEntryData)
{
- KeyEntryRequest request = (keyEntryData.Request == KeyEntryRequest.EnrollFingerprint)
+ KeyEntryRequest request = keyEntryData.Request == KeyEntryRequest.EnrollFingerprint
? KeyEntryRequest.EnrollFingerprint : KeyEntryRequest.Release;
- lock(_updateLock)
+ lock (_updateLock)
{
_isSdkUpdate = true;
_keyEntryData = new KeyEntryData(UserCancel)
@@ -169,7 +169,7 @@ public void SdkUpdate(KeyEntryData keyEntryData)
};
}
- if ((request == KeyEntryRequest.Release) && !(_connection is null))
+ if (request == KeyEntryRequest.Release && !(_connection is null))
{
_ = _connection.LoadQueryCancel(null);
}
@@ -184,7 +184,7 @@ private void RunKeyCollectorTask(Func keyCollector)
KeyEntryData keyEntryData;
do
{
- lock(_updateLock)
+ lock (_updateLock)
{
makeCall = _isSdkUpdate;
keyEntryData = _keyEntryData;
diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs
index 0561e930..c0ea4a60 100644
--- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs
+++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/AuthenticationData.cs
@@ -15,8 +15,8 @@
using System;
using System.Buffers.Binary;
using System.Globalization;
-using Yubico.YubiKey.Cryptography;
using Yubico.Core.Logging;
+using Yubico.YubiKey.Cryptography;
namespace Yubico.YubiKey.U2f
{
@@ -77,8 +77,8 @@ public AuthenticationData(ReadOnlyMemory