From a6e1b42aeb399e0def8d001407c01544566f81d8 Mon Sep 17 00:00:00 2001 From: Dennis Dyall Date: Wed, 14 Aug 2024 18:28:32 +0200 Subject: [PATCH] Use var instead of explicit type everywhere but Core --- .../Yubico/Core/Devices/Hid/MacOSHidDevice.cs | 3 +- .../src/Contrib.Bcl.Ranges/Range.cs | 4 +- .../Fido2SampleCode/Run/Fido2SampleGui.cs | 2 +- .../Run/Fido2SampleRun.Operations.cs | 102 +++++------ .../YubiKeyOperations/Fido2Protocol.cs | 12 +- .../YubiKeyOperations/Fido2Reset.cs | 4 +- .../Run/OathSampleRun.Operations.cs | 14 +- .../YubiKeyOperations/AddCredential.cs | 22 +-- .../YubiKeyOperations/CalculateCredentials.cs | 28 +-- .../YubiKeyOperations/ChooseCredential.cs | 2 +- .../YubiKeyOperations/GetCredentials.cs | 4 +- .../YubiKeyOperations/RenameCredential.cs | 8 +- .../SampleCertificateOperations.cs | 58 +++--- .../CertificateOperations/X500NameBuilder.cs | 2 +- .../YubiKeySignatureGenerator.cs | 4 +- .../Converters/DsaSignatureConverter.cs | 2 +- .../Converters/KeyConverter.Asymmetric.cs | 2 +- .../Converters/KeyConverter.Pem.cs | 6 +- .../Converters/SignatureAlgIdConverter.cs | 4 +- .../DotNetOperations/PublicKeyOperations.cs | 4 +- .../Run/PivSampleRun.Operations.cs | 58 +++--- .../YubiKeyOperations/KeyPairs.cs | 2 +- .../YubiKeyOperations/ChooseYubiKey.cs | 3 +- .../YubiKeyOperations/ListYubiKeys.cs | 4 +- .../Run/U2fSampleRun.Operations.cs | 8 +- .../YubiKeyOperations/U2fFips.cs | 2 +- .../YubiKeyOperations/U2fReset.cs | 8 +- .../YubiKey/Cryptography/AesUtilities.cs | 12 +- .../YubiKey/Cryptography/EcdsaVerify.cs | 19 +- .../Yubico/YubiKey/Cryptography/RsaFormat.cs | 78 ++++---- .../Yubico/YubiKey/Fido2/AuthenticatorInfo.cs | 14 +- .../Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs | 8 +- .../src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs | 14 +- .../Fido2/Commands/BioEnrollBeginResponse.cs | 14 +- .../Commands/BioEnrollEnumerateResponse.cs | 7 +- .../Commands/BioEnrollNextSampleResponse.cs | 11 +- .../Fido2/Commands/BioEnrollmentData.cs | 6 +- .../Fido2/Commands/ChangePinCommand.cs | 2 +- .../EnumerateCredentialsBeginResponse.cs | 24 +-- .../EnumerateCredentialsGetNextResponse.cs | 20 +-- .../Commands/EnumerateRpsBeginResponse.cs | 12 +- .../Commands/EnumerateRpsGetNextResponse.cs | 11 +- .../Fido2/Commands/GetBioModalityResponse.cs | 7 +- .../Commands/GetCredentialMetadataResponse.cs | 8 +- .../GetFingerprintSensorInfoResponse.cs | 14 +- .../Fido2/Commands/GetKeyAgreementResponse.cs | 5 +- .../Fido2/Commands/GetPinRetriesResponse.cs | 7 +- .../Fido2/Commands/GetPinTokenCommand.cs | 4 +- .../Commands/GetPinUvAuthTokenResponse.cs | 7 +- .../GetPinUvAuthTokenUsingPinCommand.cs | 2 +- .../Fido2/Commands/GetUvRetriesResponse.cs | 7 +- .../YubiKey/Fido2/Commands/VersionResponse.cs | 10 +- .../src/Yubico/YubiKey/Fido2/CredentialId.cs | 4 +- .../Fido2/Fido2Session.BioEnrollment.cs | 38 ++-- .../YubiKey/Fido2/Fido2Session.Config.cs | 42 ++--- .../YubiKey/Fido2/Fido2Session.CredMgmt.cs | 95 +++++----- .../Fido2/Fido2Session.GetAssertion.cs | 19 +- .../YubiKey/Fido2/Fido2Session.LargeBlobs.cs | 9 +- .../Fido2/Fido2Session.MakeCredential.cs | 20 ++- .../Yubico/YubiKey/Fido2/Fido2Session.Pin.cs | 71 ++++---- .../src/Yubico/YubiKey/Fido2/Fido2Session.cs | 4 +- .../Yubico/YubiKey/Fido2/GetAssertionData.cs | 32 ++-- .../Yubico/YubiKey/Fido2/LargeBlobEntry.cs | 16 +- .../YubiKey/Fido2/MakeCredentialData.cs | 22 +-- .../Yubico/YubiKey/Fido2/ParameterHelpers.cs | 6 +- .../PinProtocols/PinUvAuthProtocolBase.cs | 4 +- .../PinProtocols/PinUvAuthProtocolOne.cs | 16 +- .../PinProtocols/PinUvAuthProtocolTwo.cs | 18 +- .../src/Yubico/YubiKey/Fido2/RelyingParty.cs | 6 +- .../YubiKey/Fido2/SerializedLargeBlobArray.cs | 22 +-- .../src/Yubico/YubiKey/FidoConnection.cs | 4 +- .../Yubico/YubiKey/FidoDeviceInfoFactory.cs | 23 ++- .../src/Yubico/YubiKey/GetDeviceInfoHelper.cs | 14 +- .../YubiKey/GetDeviceInfoResponseHelper.cs | 4 +- .../src/Yubico/YubiKey/KeyboardConnection.cs | 5 +- .../YubiKey/KeyboardDeviceInfoFactory.cs | 26 ++- .../Commands/GetDeviceInfoResponse.cs | 2 +- .../src/Yubico/YubiKey/Oath/Code.cs | 2 +- .../CalculateAllCredentialsResponse.cs | 14 +- .../Commands/CalculateCredentialResponse.cs | 8 +- .../YubiKey/Oath/Commands/ListResponse.cs | 8 +- .../OathChallengeResponseBaseCommand.cs | 2 +- .../Oath/Commands/SelectOathResponse.cs | 8 +- .../YubiKey/Oath/Commands/ValidateResponse.cs | 2 +- .../src/Yubico/YubiKey/Oath/Credential.cs | 20 +-- .../YubiKey/Oath/OathSession.Credential.cs | 68 +++---- .../YubiKey/Oath/OathSession.Password.cs | 37 ++-- .../src/Yubico/YubiKey/Oath/OathSession.cs | 11 +- .../Otp/Commands/ConfigureSlotCommand.cs | 2 +- .../Otp/Commands/GetDeviceInfoResponse.cs | 2 +- .../Otp/Commands/ReadStatusResponse.cs | 22 +-- .../src/Yubico/YubiKey/Otp/NdefConfig.cs | 2 +- .../src/Yubico/YubiKey/Otp/NdefDataReader.cs | 4 +- .../Operations/CalculateChallengeResponse.cs | 3 +- .../Operations/ConfigureChallengeResponse.cs | 8 +- .../YubiKey/Otp/Operations/ConfigureHotp.cs | 11 +- .../YubiKey/Otp/Operations/ConfigureNdef.cs | 2 +- .../Otp/Operations/ConfigureStaticPassword.cs | 15 +- .../Otp/Operations/ConfigureYubicoOtp.cs | 15 +- .../Otp/Operations/DeleteSlotConfiguration.cs | 2 +- .../YubiKey/Otp/Operations/UpdateSlot.cs | 13 +- .../src/Yubico/YubiKey/Otp/OtpSession.cs | 5 +- .../src/Yubico/YubiKey/Otp/OtpSettings.cs | 7 +- .../Pipelines/CommandChainingTransform.cs | 4 +- .../YubiKey/Pipelines/FidoErrorTransform.cs | 2 +- .../Yubico/YubiKey/Pipelines/FidoTransform.cs | 37 ++-- .../YubiKey/Pipelines/KeyboardTransform.cs | 4 +- .../YubiKey/Pipelines/OtpErrorTransform.cs | 8 +- .../Pipelines/ResponseChainingTransform.cs | 22 +-- .../YubiKey/Pipelines/Scp03ApduTransform.cs | 28 ++- .../Piv/Commands/AesForManagementKey.cs | 2 +- .../Piv/Commands/AuthenticateResponse.cs | 4 +- ...ompleteAuthenticateManagementKeyCommand.cs | 4 +- ...mpleteAuthenticateManagementKeyResponse.cs | 4 +- .../Piv/Commands/GenerateKeyPairCommand.cs | 5 +- ...ializeAuthenticateManagementKeyResponse.cs | 5 +- .../Piv/Commands/TripleDesForManagementKey.cs | 8 +- .../YubiKey/Piv/Commands/VersionResponse.cs | 8 +- .../Yubico/YubiKey/Piv/Objects/AdminData.cs | 16 +- .../Piv/Objects/CardCapabilityContainer.cs | 20 +-- .../YubiKey/Piv/Objects/CardholderUniqueId.cs | 16 +- .../Yubico/YubiKey/Piv/Objects/KeyHistory.cs | 4 +- .../YubiKey/Piv/Objects/PinProtectedData.cs | 12 +- .../src/Yubico/YubiKey/Piv/PivBioMetadata.cs | 2 +- .../YubiKey/Piv/PivDataTagExtensions.cs | 17 +- .../Yubico/YubiKey/Piv/PivEccPrivateKey.cs | 2 +- .../src/Yubico/YubiKey/Piv/PivMetadata.cs | 2 +- .../src/Yubico/YubiKey/Piv/PivPublicKey.cs | 5 +- .../Yubico/YubiKey/Piv/PivRsaPrivateKey.cs | 2 +- .../YubiKey/Piv/PivSession.Attestation.cs | 22 +-- .../Yubico/YubiKey/Piv/PivSession.Crypto.cs | 20 +-- .../Yubico/YubiKey/Piv/PivSession.KeyPairs.cs | 41 ++--- .../YubiKey/Piv/PivSession.ManagementKey.cs | 33 ++-- .../Yubico/YubiKey/Piv/PivSession.Msroots.cs | 25 +-- .../Yubico/YubiKey/Piv/PivSession.Objects.cs | 24 +-- .../src/Yubico/YubiKey/Piv/PivSession.Pin.cs | 97 +++++----- .../Yubico/YubiKey/Piv/PivSession.Pinonly.cs | 166 +++++++++--------- .../src/Yubico/YubiKey/Piv/PivSession.cs | 33 ++-- .../src/Yubico/YubiKey/Scp03/ChannelMac.cs | 10 +- .../Commands/InitializeUpdateResponse.cs | 2 +- .../src/Yubico/YubiKey/Scp03/Derivation.cs | 2 +- .../Yubico/YubiKey/Scp03/Scp03Connection.cs | 2 +- .../src/Yubico/YubiKey/Scp03/Scp03Session.cs | 23 +-- .../src/Yubico/YubiKey/SmartCardConnection.cs | 10 +- .../YubiKey/SmartCardDeviceInfoFactory.cs | 29 ++- .../Yubico/YubiKey/TouchFingerprintTask.cs | 5 +- .../U2f/Commands/GetDeviceInfoResponse.cs | 2 +- .../Commands/GetProtocolVersionResponse.cs | 2 +- .../Yubico/YubiKey/U2f/RegistrationData.cs | 12 +- .../src/Yubico/YubiKey/U2f/U2fSession.Pin.cs | 41 +++-- .../src/Yubico/YubiKey/U2f/U2fSession.cs | 34 ++-- .../Commands/AddCredentialCommand.cs | 6 +- .../Commands/ChangeManagementKeyCommand.cs | 6 +- .../Commands/DeleteCredentialCommand.cs | 6 +- .../Commands/GetAes128SessionKeysCommand.cs | 6 +- .../Commands/GetAes128SessionKeysResponse.cs | 2 +- .../Commands/GetApplicationVersionResponse.cs | 5 +- .../Commands/ListCredentialsResponse.cs | 13 +- .../YubiHsmAuthSession.Credential.cs | 35 ++-- .../YubiHsmAuthSession.ManagementKey.cs | 14 +- .../YubiHsmAuthSession.SessionKeys.cs | 52 +++--- .../YubiKey/YubiHsmAuth/YubiHsmAuthSession.cs | 9 +- .../YubiKey/YubiKeyCapabilitiesExtensions.cs | 14 +- .../Yubico/YubiKey/YubiKeyDevice.Instance.cs | 40 ++--- .../Yubico/YubiKey/YubiKeyDevice.Static.cs | 2 +- .../src/Yubico/YubiKey/YubiKeyDeviceInfo.cs | 6 +- .../Yubico/YubiKey/YubiKeyDeviceListener.cs | 13 +- .../Yubico/YubiKey/Oath/GetLargeData.cs | 2 +- .../YubiHsmAuth/SessionCredentialTests.cs | 4 +- .../SessionGetAes128SessionKeysTests.cs | 2 +- .../YubiHsmAuth/SessionManagementKeyTests.cs | 4 +- .../tests/sandbox/Plugins/DavidPlugin.cs | 42 ++--- .../sandbox/Plugins/HidCodeTablePlugin.cs | 2 +- .../sandbox/Plugins/YubiKeyFeaturePlugin.cs | 2 +- .../YubiKey/Fido2/LargeBlobArrayTests.cs | 2 +- .../YubiKey/Fido2/LargeBlobEntryTests.cs | 2 +- .../CalculateAllCredentialsCommandTests.cs | 4 +- .../CalculateCredentialCommandTests.cs | 4 +- .../Oath/Commands/SetPasswordCommandTests.cs | 4 +- .../Oath/Commands/ValidateCommandTests.cs | 6 +- .../Oath/Commands/ValidateResponseTests.cs | 6 +- .../Yubico/YubiKey/Oath/CredentialTests.cs | 46 ++--- .../tests/unit/Yubico/YubiKey/Piv/KeyTests.cs | 10 +- .../Aes128CredentialWithSecretsTests.cs | 4 +- .../Commands/AddCredentialCommandTests.cs | 66 +++---- .../Commands/AddCredentialResponseTests.cs | 16 +- .../Commands/BaseYubiHsmAuthResponseTests.cs | 6 +- ...BaseYubiHsmAuthResponseWithRetriesTests.cs | 10 +- .../ChangeManagementKeyCommandTests.cs | 6 +- .../Commands/DeleteCredentialCommandTests.cs | 32 ++-- .../GetAes128SessionKeysCommandTests.cs | 38 ++-- .../GetAes128SessionKeysResponseTests.cs | 20 +-- .../GetApplicationVersionCommandTests.cs | 12 +- .../GetApplicationVersionResponseTests.cs | 18 +- .../GetManagementKeyRetriesCommandTests.cs | 10 +- .../GetManagementKeyRetriesResponseTests.cs | 12 +- .../Commands/ListCredentialsCommandTests.cs | 14 +- .../Commands/ListCredentialsResponseTests.cs | 56 +++--- .../Commands/ResetApplicationCommandTests.cs | 14 +- .../YubiHsmAuth/CredentialRetryPairTests.cs | 4 +- .../YubiKey/YubiHsmAuth/CredentialTests.cs | 22 +-- 201 files changed, 1536 insertions(+), 1583 deletions(-) diff --git a/Yubico.Core/src/Yubico/Core/Devices/Hid/MacOSHidDevice.cs b/Yubico.Core/src/Yubico/Core/Devices/Hid/MacOSHidDevice.cs index 27a6ca09..eb2e6c12 100644 --- a/Yubico.Core/src/Yubico/Core/Devices/Hid/MacOSHidDevice.cs +++ b/Yubico.Core/src/Yubico/Core/Devices/Hid/MacOSHidDevice.cs @@ -17,9 +17,8 @@ using System.Globalization; using System.Linq; using Microsoft.Extensions.Logging; -using Yubico.PlatformInterop; using Yubico.Core.Logging; - +using Yubico.PlatformInterop; using static Yubico.PlatformInterop.NativeMethods; namespace Yubico.Core.Devices.Hid diff --git a/Yubico.DotNetPolyfills/src/Contrib.Bcl.Ranges/Range.cs b/Yubico.DotNetPolyfills/src/Contrib.Bcl.Ranges/Range.cs index bfdf280a..696af49d 100644 --- a/Yubico.DotNetPolyfills/src/Contrib.Bcl.Ranges/Range.cs +++ b/Yubico.DotNetPolyfills/src/Contrib.Bcl.Ranges/Range.cs @@ -77,7 +77,7 @@ value is Range r && public (int Offset, int Length) GetOffsetAndLength(int length) { int start; - Index startIndex = Start; + var startIndex = Start; if (startIndex.IsFromEnd) { start = length - startIndex.Value; @@ -88,7 +88,7 @@ value is Range r && } int end; - Index endIndex = End; + var endIndex = End; if (endIndex.IsFromEnd) { end = length - endIndex.Value; diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs index bdbd1b3e..75eac499 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleGui.cs @@ -231,7 +231,7 @@ public bool LaunchPinPopup(KeyEntryData keyEntryData) return false; } - DialogResult dResult = DialogResult.OK; + var dResult = DialogResult.OK; do { _pinPopupForm.UpdateMessage(dResult, keyEntryData); diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs index d28fbbad..d20e2ce1 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/Run/Fido2SampleRun.Operations.cs @@ -142,7 +142,7 @@ public bool RunReset() // EventHandler delegates must have access to the serial number. // So we're going to use a separate class to handle this. var fido2Reset = new Fido2Reset(_yubiKeyChosen.SerialNumber); - ResponseStatus status = fido2Reset.RunFido2Reset(_keyCollector.Fido2SampleKeyCollectorDelegate); + var status = fido2Reset.RunFido2Reset(_keyCollector.Fido2SampleKeyCollectorDelegate); if (status == ResponseStatus.Success) { SampleMenu.WriteMessage(MessageType.Title, 0, "\nFIDO2 application successfully reset.\n"); @@ -175,11 +175,11 @@ public bool RunChangePin() public bool RunVerifyPin() { - bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo); + bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); if (isValid) { isValid = GetVerifyArguments( - true, authenticatorInfo, out PinUvAuthTokenPermissions? permissions, out string relyingPartyId); + true, authenticatorInfo, out var permissions, out string relyingPartyId); if (isValid) { @@ -203,12 +203,12 @@ public bool RunVerifyPin() public bool RunVerifyUv() { - bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo); + bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); if (isValid) { isValid = GetVerifyArguments( - false, authenticatorInfo, out PinUvAuthTokenPermissions? permissions, out string relyingPartyId); + false, authenticatorInfo, out var permissions, out string relyingPartyId); if (isValid && !(permissions is null)) { @@ -258,19 +258,19 @@ public bool RunMakeCredential() SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the user DisplayName"); _ = SampleMenu.ReadResponse(out string userDisplayName); - RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + var randomObject = CryptographyProviders.RngCreator(); byte[] randomBytes = new byte[16]; randomObject.GetBytes(randomBytes); var userId = new ReadOnlyMemory(randomBytes); - ReadOnlyMemory clientDataHash = BuildFakeClientDataHash(relyingPartyId); + var clientDataHash = BuildFakeClientDataHash(relyingPartyId); - if (!Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo)) + if (!Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo)) { return false; } - CredProtectPolicy credProtectPolicy = CredProtectPolicy.None; + var credProtectPolicy = CredProtectPolicy.None; if (authenticatorInfo.Extensions.Contains("credProtect")) { string[] menuItems = new string[] { @@ -325,7 +325,7 @@ public bool RunMakeCredential() userName, userDisplayName, userId, credProtectPolicy, credBlobData, - out MakeCredentialData makeCredentialData); + out var makeCredentialData); if (!isValid) { @@ -360,10 +360,10 @@ public bool RunGetAssertions() SampleMenu.WriteMessage(MessageType.Title, 0, "Enter the relyingPartyId"); _ = SampleMenu.ReadResponse(out string relyingPartyId); - ReadOnlyMemory clientDataHash = BuildFakeClientDataHash(relyingPartyId); + var clientDataHash = BuildFakeClientDataHash(relyingPartyId); - ReadOnlyMemory salt = ReadOnlyMemory.Empty; - bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo); + var salt = ReadOnlyMemory.Empty; + bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); if (isValid) { if (authenticatorInfo.Extensions.Contains("hmac-secret")) @@ -378,7 +378,7 @@ public bool RunGetAssertions() "digest to the YubiKey as the salt.\n"); _ = SampleMenu.ReadResponse(out string dataToDigest); byte[] dataBytes = System.Text.Encoding.Unicode.GetBytes(dataToDigest); - SHA256 digester = CryptographyProviders.Sha256Creator(); + var digester = CryptographyProviders.Sha256Creator(); _ = digester.TransformFinalBlock(dataBytes, 0, dataBytes.Length); salt = new ReadOnlyMemory(digester.Hash); @@ -393,8 +393,8 @@ public bool RunGetAssertions() clientDataHash, relyingPartyId, salt, - out IReadOnlyList assertions, - out IReadOnlyList hmacSecrets)) + out var assertions, + out var hmacSecrets)) { return false; } @@ -421,7 +421,7 @@ public bool RunListCredentials() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } @@ -436,21 +436,21 @@ public bool RunUpdateCredentialUserInfo() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } ReportCredentials(credentialData, false, false, out int credentialCount); - CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); + var userInfo = SelectCredential(credentialData, credentialCount); if (userInfo is null) { return false; } - UserEntity updatedInfo = GetUpdatedInfo(userInfo.User); + var updatedInfo = GetUpdatedInfo(userInfo.User); return Fido2Protocol.RunUpdateUserInfo( _yubiKeyChosen, @@ -464,14 +464,14 @@ public bool RunDeleteCredential() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } ReportCredentials(credentialData, false, false, out int credentialCount); - CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); + var userInfo = SelectCredential(credentialData, credentialCount); if (userInfo is null) { @@ -497,7 +497,7 @@ public bool RunDeleteCredential() if (!Fido2Protocol.RunGetLargeBlobArray( _yubiKeyChosen, - out SerializedLargeBlobArray blobArray)) + out var blobArray)) { return true; } @@ -524,7 +524,7 @@ public bool RunRetrieveLargeBlobData() { if (!Fido2Protocol.RunGetLargeBlobArray( _yubiKeyChosen, - out SerializedLargeBlobArray blobArray)) + out var blobArray)) { return false; } @@ -565,7 +565,7 @@ public bool RunRetrieveLargeBlobData() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } @@ -577,7 +577,7 @@ public bool RunRetrieveLargeBlobData() "LargeBlob data is stored against a credential. Select a credential for which\n" + "you want to see the largeBlob data. It is possible to retrieve data only for\n" + "credentials that have an available Large Blob Key.\n"); - CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); + var userInfo = SelectCredential(credentialData, credentialCount); if (userInfo is null) { @@ -620,7 +620,7 @@ public bool RunStoreLargeBlobData() // data and "edit" it. if (!Fido2Protocol.RunGetLargeBlobArray( _yubiKeyChosen, - out SerializedLargeBlobArray blobArray)) + out var blobArray)) { return false; } @@ -628,7 +628,7 @@ public bool RunStoreLargeBlobData() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } @@ -642,7 +642,7 @@ public bool RunStoreLargeBlobData() "with the largeBlob option. Hence, you must choose a credential against which the\n" + "data will be stored, and that credential must have an available Large Blob Key.\n" + "Note that this sample code will store only one entry per credential.\n"); - CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); + var userInfo = SelectCredential(credentialData, credentialCount); if (userInfo is null) { @@ -696,7 +696,7 @@ public bool RunDeleteLargeBlobData() { if (!Fido2Protocol.RunGetLargeBlobArray( _yubiKeyChosen, - out SerializedLargeBlobArray blobArray)) + out var blobArray)) { return false; } @@ -704,7 +704,7 @@ public bool RunDeleteLargeBlobData() if (!Fido2Protocol.RunGetCredentialData( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out IReadOnlyList credentialData)) + out var credentialData)) { return false; } @@ -718,7 +718,7 @@ public bool RunDeleteLargeBlobData() "YubiKey, or if there is no largeBlob data stored, or nothing stored against\n" + "the selected credential, this sample code will do nothing.\n"); - CredentialUserInfo userInfo = SelectCredential(credentialData, credentialCount); + var userInfo = SelectCredential(credentialData, credentialCount); if (userInfo is null || userInfo.LargeBlobKey is null) { @@ -759,9 +759,9 @@ public bool RunGetBioInfo() if (!Fido2Protocol.RunGetBioInfo( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out BioModality modality, - out FingerprintSensorInfo sensorInfo, - out IReadOnlyList templates)) + out var modality, + out var sensorInfo, + out var templates)) { return false; } @@ -807,7 +807,7 @@ public bool RunEnrollFingerprint() try { - TemplateInfo templateInfo = Fido2Protocol.RunEnrollFingerprint( + var templateInfo = Fido2Protocol.RunEnrollFingerprint( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, friendlyName, @@ -834,9 +834,9 @@ public bool RunSetBioTemplateFriendlyName() if (!Fido2Protocol.RunGetBioInfo( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out BioModality modality, - out FingerprintSensorInfo sensorInfo, - out IReadOnlyList templates)) + out var modality, + out var sensorInfo, + out var templates)) { return false; } @@ -867,9 +867,9 @@ public bool RunRemoveBioEnrollment() if (!Fido2Protocol.RunGetBioInfo( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out BioModality modality, - out FingerprintSensorInfo sensorInfo, - out IReadOnlyList templates)) + out var modality, + out var sensorInfo, + out var templates)) { return false; } @@ -915,13 +915,13 @@ public bool RunEnableEnterpriseAttestation() public bool RunToggleAlwaysUv() { - bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo); + bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); if (!isValid) { return false; } - OptionValue optionValue = authenticatorInfo.GetOptionValue("alwaysUv"); + var optionValue = authenticatorInfo.GetOptionValue("alwaysUv"); string[] menuItems = new string[] { "Yes", @@ -961,7 +961,7 @@ public bool RunToggleAlwaysUv() isValid = Fido2Protocol.RunToggleAlwaysUv( _yubiKeyChosen, _keyCollector.Fido2SampleKeyCollectorDelegate, - out OptionValue newValue); + out var newValue); if (isValid) { @@ -975,13 +975,13 @@ public bool RunToggleAlwaysUv() public bool RunSetPinConfig() { - bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out AuthenticatorInfo authenticatorInfo); + bool isValid = Fido2Protocol.RunGetAuthenticatorInfo(_yubiKeyChosen, out var authenticatorInfo); if (!isValid) { return false; } - OptionValue setMinPinValue = authenticatorInfo.GetOptionValue(AuthenticatorOptions.setMinPINLength); + var setMinPinValue = authenticatorInfo.GetOptionValue(AuthenticatorOptions.setMinPINLength); if (setMinPinValue != OptionValue.True) { SampleMenu.WriteMessage( @@ -1207,11 +1207,11 @@ private static ReadOnlyMemory BuildFakeClientDataHash(string relyingPartyI byte[] idBytes = System.Text.Encoding.Unicode.GetBytes(relyingPartyId); // Generate a random value to represent the challenge. - RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + var randomObject = CryptographyProviders.RngCreator(); byte[] randomBytes = new byte[16]; randomObject.GetBytes(randomBytes); - SHA256 digester = CryptographyProviders.Sha256Creator(); + var digester = CryptographyProviders.Sha256Creator(); _ = digester.TransformBlock(randomBytes, 0, randomBytes.Length, null, 0); _ = digester.TransformFinalBlock(idBytes, 0, idBytes.Length); @@ -1302,7 +1302,7 @@ private static bool CheckPinUvAuthTokenOption(AuthenticatorInfo authenticatorInf private bool CollectPermissions(out PinUvAuthTokenPermissions? permissions) { permissions = null; - PinUvAuthTokenPermissions current = PinUvAuthTokenPermissions.None; + var current = PinUvAuthTokenPermissions.None; SampleMenu.WriteMessage( MessageType.Title, 0, @@ -1368,7 +1368,7 @@ private bool CollectPermissions(out PinUvAuthTokenPermissions? permissions) private bool CollectRelyingPartyId(PinUvAuthTokenPermissions? permissions, out string relyingPartyId) { relyingPartyId = ""; - PinUvAuthTokenPermissions current = PinUvAuthTokenPermissions.None; + var current = PinUvAuthTokenPermissions.None; if (!(permissions is null)) { current = permissions.Value; diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs index 653b3839..0761d177 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Protocol.cs @@ -147,7 +147,7 @@ public static bool RunGetAssertions( // verification needed. assertions = fido2Session.GetAssertions(getAssertionParameters); - foreach (GetAssertionData assertionData in assertions) + foreach (var assertionData in assertions) { byte[] hmacSecret = assertionData.AuthenticatorData.GetHmacSecretExtension(fido2Session.AuthProtocol); hmacSecretList.Add(hmacSecret); @@ -201,15 +201,15 @@ public static bool RunGetCredentialData( returnValue.Add(new Tuple(credCount, remainingCount)); - IReadOnlyList rpList = fido2Session.EnumerateRelyingParties(); - foreach (RelyingParty currentRp in rpList) + var rpList = fido2Session.EnumerateRelyingParties(); + foreach (var currentRp in rpList) { returnValue.Add(currentRp); - IReadOnlyList credentialList = + var credentialList = fido2Session.EnumerateCredentialsForRelyingParty(currentRp); - foreach (CredentialUserInfo currentCredential in credentialList) + foreach (var currentCredential in credentialList) { returnValue.Add(currentCredential); } @@ -288,7 +288,7 @@ public static string GetLargeBlobEntry( throw new ArgumentNullException(nameof(blobArray)); } - Memory plaintext = Memory.Empty; + var plaintext = Memory.Empty; byte[] plainArray = Array.Empty(); entryIndex = -1; try diff --git a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Reset.cs b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Reset.cs index e1bd1abc..b7160cd7 100644 --- a/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Reset.cs +++ b/Yubico.YubiKey/examples/Fido2SampleCode/YubiKeyOperations/Fido2Reset.cs @@ -70,7 +70,7 @@ public ResponseStatus RunFido2Reset(Func KeyCollector) { // The SDK comes with a listener that can tell when a YubiKey has // been removed or inserted. - YubiKeyDeviceListener yubiKeyDeviceListener = YubiKeyDeviceListener.Instance; + var yubiKeyDeviceListener = YubiKeyDeviceListener.Instance; yubiKeyDeviceListener.Arrived += YubiKeyInserted; yubiKeyDeviceListener.Removed += YubiKeyRemoved; @@ -153,7 +153,7 @@ public ResponseStatus RunFido2Reset(Func KeyCollector) touchMessageTask.Start(); var resetCmd = new ResetCommand(); - ResetResponse resetRsp = fido2Session.Connection.SendCommand(resetCmd); + var resetRsp = fido2Session.Connection.SendCommand(resetCmd); return resetRsp.Status; } diff --git a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs index 6caea741..8b62bae3 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/Run/OathSampleRun.Operations.cs @@ -121,13 +121,13 @@ private void RunDefaultCollectCredential() SampleMenu.WriteMessage(MessageType.Title, 0, "Enter account name"); _ = SampleMenu.ReadResponse(out string account); - _ = ChooseCredentialProperties.RunChooseTypeOption(_menuObject, out CredentialType? type); + _ = ChooseCredentialProperties.RunChooseTypeOption(_menuObject, out var type); - CredentialPeriod period = CredentialPeriod.Undefined; + var period = CredentialPeriod.Undefined; if (type == CredentialType.Totp) { - _ = ChooseCredentialProperties.RunChoosePeriodOption(_menuObject, out CredentialPeriod? credentialPeriod); + _ = ChooseCredentialProperties.RunChoosePeriodOption(_menuObject, out var credentialPeriod); period = (CredentialPeriod)credentialPeriod; } @@ -230,7 +230,7 @@ private bool RunRenameCredentialMenuItem(int? index) else { RunCollectCredential(_menuObject, - out Credential credential, + out var credential, out string newIssuer, out string newAccount); @@ -256,13 +256,13 @@ private static void RunCollectCredential( SampleMenu.WriteMessage(MessageType.Title, 0, "Enter current account name"); _ = SampleMenu.ReadResponse(out string currentAccount); - _ = ChooseCredentialProperties.RunChooseTypeOption(menuObject, out CredentialType? type); + _ = ChooseCredentialProperties.RunChooseTypeOption(menuObject, out var type); - CredentialPeriod period = CredentialPeriod.Undefined; + var period = CredentialPeriod.Undefined; if (type == CredentialType.Totp) { - _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out CredentialPeriod? credentialPeriod); + _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out var credentialPeriod); period = credentialPeriod.Value; } diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs index a449e443..99b4e8bd 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/AddCredential.cs @@ -52,7 +52,7 @@ public static bool RunAddTotpCredential( } else { - Credential credential = CollectTotpCredential(menuObject); + var credential = CollectTotpCredential(menuObject); oathSession.AddCredential(credential); ReportResult(credential); } @@ -93,7 +93,7 @@ public static bool RunAddHotpCredential( } else { - Credential credential = CollectHotpCredential(menuObject); + var credential = CollectHotpCredential(menuObject); oathSession.AddCredential(credential); ReportResult(credential); } @@ -116,12 +116,12 @@ public static bool RunAddDefaultTotpCredential( if (menuObject is null) { - Credential credential = oathSession.AddCredential("Yubico", "testDefaultTotp@example.com"); + var credential = oathSession.AddCredential("Yubico", "testDefaultTotp@example.com"); ReportResult(credential); } else { - Credential credential = CollectDefaultTotpCredential(); + var credential = CollectDefaultTotpCredential(); oathSession.AddCredential(credential); ReportResult(credential); } @@ -144,7 +144,7 @@ public static bool RunAddDefaultHotpCredential( if (menuObject is null) { - Credential credential = oathSession.AddCredential( + var credential = oathSession.AddCredential( "Yubico", "testDefaultHotp@example.com", CredentialType.Hotp, @@ -153,7 +153,7 @@ public static bool RunAddDefaultHotpCredential( } else { - Credential credential = CollectDefaultHotpCredential(); + var credential = CollectDefaultHotpCredential(); oathSession.AddCredential(credential); ReportResult(credential); } @@ -176,14 +176,14 @@ public static bool RunAddCredentialFromQR( if (menuObject is null) { - Credential credential = oathSession.AddCredential( + var credential = oathSession.AddCredential( "otpauth://totp/Yubico:testUri@example.com?secret=YY4KVNOUQ5IIUBAOGIDRYZ7FGY54VW54&issuer=Yubico&algorithm=SHA1&digits=6&period=30"); ReportResult(credential); } else { string stringFromUri = CollectStringFromUri(); - Credential credential = oathSession.AddCredential(stringFromUri); + var credential = oathSession.AddCredential(stringFromUri); ReportResult(credential); } } @@ -254,9 +254,9 @@ private static Credential CollectTotpCredential(SampleMenu menuObject) SampleMenu.WriteMessage(MessageType.Title, 0, "Enter account name"); _ = SampleMenu.ReadResponse(out string account); - _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out CredentialPeriod? period); + _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out var period); - _ = ChooseCredentialProperties.RunChooseAlgorithmOption(menuObject, out HashAlgorithm? algorithm); + _ = ChooseCredentialProperties.RunChooseAlgorithmOption(menuObject, out var algorithm); SampleMenu.WriteMessage(MessageType.Title, 0, "Enter secret"); _ = SampleMenu.ReadResponse(out string secret); @@ -290,7 +290,7 @@ private static Credential CollectHotpCredential(SampleMenu menuObject) SampleMenu.WriteMessage(MessageType.Title, 0, "Enter account name"); _ = SampleMenu.ReadResponse(out string account); - _ = ChooseCredentialProperties.RunChooseAlgorithmOption(menuObject, out HashAlgorithm? algorithm); + _ = ChooseCredentialProperties.RunChooseAlgorithmOption(menuObject, out var algorithm); SampleMenu.WriteMessage(MessageType.Title, 0, "Enter secret"); _ = SampleMenu.ReadResponse(out string secret); diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs index 4a15bda0..0b36c211 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/CalculateCredentials.cs @@ -28,8 +28,8 @@ public static bool RunCalculateCredentials(IYubiKeyDevice yubiKey, Func result = oathSession.CalculateAllCredentials(); - ReportAllResults(result); + var results = oathSession.CalculateAllCredentials(); + ReportAllResults(results); } return true; @@ -49,7 +49,7 @@ public static bool RunCalculateOneCredential( using var oathSession = new OathSession(yubiKey); { oathSession.KeyCollector = KeyCollectorDelegate; - Code code = oathSession.CalculateCredential(credential); + var code = oathSession.CalculateCredential(credential); ReportOneResult(credential, code); } @@ -64,18 +64,18 @@ private static void ReportAllResults(IDictionary credentials) { _ = outputList.AppendLine($"Number of credentials: {credentials.Count}"); _ = outputList.AppendLine(); - foreach (KeyValuePair pair in credentials) + foreach (var (credential, code) in credentials) { - _ = outputList.AppendLine($"Issuer : {pair.Key.Issuer}"); - _ = outputList.AppendLine($"Account : {pair.Key.AccountName}"); - _ = outputList.AppendLine($"Type : {pair.Key.Type}"); - _ = outputList.AppendLine($"Period : {(int?)pair.Key.Period}sec"); - _ = outputList.AppendLine($"Digits : {pair.Key.Digits}"); - _ = outputList.AppendLine($"Touch : {pair.Key.RequiresTouch}"); - _ = outputList.AppendLine($"OTP code : {pair.Value.Value}"); - _ = outputList.AppendLine($"ValidFrom : {pair.Value.ValidFrom}"); - _ = outputList.AppendLine($"ValidUntil: {pair.Value.ValidUntil}"); - _ = outputList.AppendLine($"Name : {pair.Key.Name}"); + _ = outputList.AppendLine($"Issuer : {credential.Issuer}"); + _ = outputList.AppendLine($"Account : {credential.AccountName}"); + _ = outputList.AppendLine($"Type : {credential.Type}"); + _ = outputList.AppendLine($"Period : {(int?)credential.Period}sec"); + _ = outputList.AppendLine($"Digits : {credential.Digits}"); + _ = outputList.AppendLine($"Touch : {credential.RequiresTouch}"); + _ = outputList.AppendLine($"OTP code : {code.Value}"); + _ = outputList.AppendLine($"ValidFrom : {code.ValidFrom}"); + _ = outputList.AppendLine($"ValidUntil: {code.ValidUntil}"); + _ = outputList.AppendLine($"Name : {credential.Name}"); _ = outputList.AppendLine(); } } diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs index ed01b25a..8c42a389 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/ChooseCredential.cs @@ -44,7 +44,7 @@ public static bool RunChooseCredential( using var oathSession = new OathSession(yubiKey); { - IList credentials = oathSession.GetCredentials(); + var credentials = oathSession.GetCredentials(); // Are there any? if (credentials.Count == 0) diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/GetCredentials.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/GetCredentials.cs index 300ad3bb..f22b1b03 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/GetCredentials.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/GetCredentials.cs @@ -28,7 +28,7 @@ public static bool RunGetCredentials(IYubiKeyDevice yubiKey, Func result = oathSession.GetCredentials(); + var result = oathSession.GetCredentials(); ReportResult(result); } @@ -42,7 +42,7 @@ private static void ReportResult(IList credentials) { _ = outputList.AppendLine($"Number of credentials: {credentials.Count}"); _ = outputList.AppendLine(); - foreach (Credential currentCredential in credentials) + foreach (var currentCredential in credentials) { _ = outputList.AppendLine($"Issuer : {currentCredential.Issuer}"); _ = outputList.AppendLine($"Account : {currentCredential.AccountName}"); diff --git a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/RenameCredential.cs b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/RenameCredential.cs index e7fd03d0..046dbf99 100644 --- a/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/RenameCredential.cs +++ b/Yubico.YubiKey/examples/OathSampleCode/YubiKeyOperations/RenameCredential.cs @@ -41,7 +41,7 @@ public static bool RunRenameCredential( { oathSession.KeyCollector = KeyCollectorDelegate; - Credential renamedCredential = oathSession.RenameCredential( + var renamedCredential = oathSession.RenameCredential( credential.Issuer, credential.AccountName, newIssuer, @@ -85,13 +85,13 @@ private static void RunCollectCredential( SampleMenu.WriteMessage(MessageType.Title, 0, "Enter current account name"); _ = SampleMenu.ReadResponse(out string currentAccount); - _ = ChooseCredentialProperties.RunChooseTypeOption(menuObject, out CredentialType? type); + _ = ChooseCredentialProperties.RunChooseTypeOption(menuObject, out var type); - CredentialPeriod period = CredentialPeriod.Undefined; + var period = CredentialPeriod.Undefined; if (type == CredentialType.Totp) { - _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out CredentialPeriod? credentialPeriod); + _ = ChooseCredentialProperties.RunChoosePeriodOption(menuObject, out var credentialPeriod); period = credentialPeriod.Value; } diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs index 240eb6be..ac543f1d 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/SampleCertificateOperations.cs @@ -41,7 +41,7 @@ public static void GetCertRequest( } // Build the AsymmetricAlgorithm object from the public key. - using AsymmetricAlgorithm dotNetPubKey = KeyConverter.GetDotNetFromPivPublicKey(slotContents.PublicKey); + using var dotNetPubKey = KeyConverter.GetDotNetFromPivPublicKey(slotContents.PublicKey); // Build a cert request object. // This sample code uses SHA-256 for all algorithms except ECC P-384. @@ -98,7 +98,7 @@ public static void GetSelfSignedCert( nameBuilder.AddNameElement(X500NameElement.Locality, "Palo Alto"); nameBuilder.AddNameElement(X500NameElement.Organization, "Fake"); nameBuilder.AddNameElement(X500NameElement.CommonName, "Fake Root"); - X500DistinguishedName sampleRootName = nameBuilder.GetDistinguishedName(); + var sampleRootName = nameBuilder.GetDistinguishedName(); GetCertRequest(yubiKey, KeyCollectorDelegate, sampleRootName, slotContents); @@ -108,8 +108,8 @@ public static void GetSelfSignedCert( slotContents.CertRequest.CertificateExtensions.Add(basicConstraints); slotContents.CertRequest.CertificateExtensions.Add(keyUsage); - DateTimeOffset notBefore = DateTimeOffset.Now; - DateTimeOffset notAfter = notBefore.AddDays(3650); + var notBefore = DateTimeOffset.Now; + var notAfter = notBefore.AddDays(3650); byte[] serialNumber = new byte[] { 0x01 }; using (var pivSession = new PivSession(yubiKey)) @@ -117,7 +117,7 @@ public static void GetSelfSignedCert( pivSession.KeyCollector = KeyCollectorDelegate; var signer = new YubiKeySignatureGenerator(pivSession, slotContents.SlotNumber, slotContents.PublicKey); - X509Certificate2 selfSignedCert = slotContents.CertRequest.Create( + var selfSignedCert = slotContents.CertRequest.Create( sampleRootName, signer, notBefore, @@ -219,7 +219,7 @@ public static bool GetSignedCert( } // Get a signed cert request. - X500DistinguishedName sampleCertName = nameBuilder.GetDistinguishedName(); + var sampleCertName = nameBuilder.GetDistinguishedName(); GetCertRequest(yubiKey, KeyCollectorDelegate, sampleCertName, requestorSlotContents); // In the real world, the cert request would be sent as a PEM @@ -263,7 +263,7 @@ public static bool GetSignedCert( // encoded key value. It will be // 04 // where each coordinate is exactly 48 bytes (384 bits) long. - HashAlgorithmName signerHash = HashAlgorithmName.SHA256; + var signerHash = HashAlgorithmName.SHA256; if (string.Equals(signerCert.PublicKey.Oid.FriendlyName, "ECC", StringComparison.Ordinal) && signerCert.PublicKey.EncodedKeyValue.RawData.Length == 97) { @@ -271,7 +271,7 @@ public static bool GetSignedCert( } byte[] requestDer = requestorSlotContents.GetCertRequestDer(); - CertificateRequest certRequest = BuildCertRequestFromDer(requestDer, signerHash); + var certRequest = BuildCertRequestFromDer(requestDer, signerHash); if (isCa) { @@ -282,7 +282,7 @@ public static bool GetSignedCert( certRequest.CertificateExtensions.Add(keyUsage); } - DateTimeOffset notBefore = DateTimeOffset.Now; + var notBefore = DateTimeOffset.Now; var notAfter = new DateTimeOffset(signerCert.NotAfter); byte[] serialNumber = new byte[] { 0x02 }; @@ -295,7 +295,7 @@ public static bool GetSignedCert( signerSlotContents.SlotNumber, signerSlotContents.PublicKey); - X509Certificate2 newCert = certRequest.Create( + var newCert = certRequest.Create( signerCert.SubjectName, signer, notBefore, @@ -327,11 +327,11 @@ public static bool GetSignedCert( // writing a lot more code, this sample always uses PSS. public static CertificateRequest BuildCertRequestFromDer(byte[] requestDer, HashAlgorithmName signerHash) { - using AsymmetricAlgorithm requestPublicKey = GetComponentsFromCertRequestDer( + using var requestPublicKey = GetComponentsFromCertRequestDer( requestDer, out byte[] _, - out SignatureAlgIdConverter _, - out X500DistinguishedName requestName, + out var _, + out var requestName, out byte[] _); if (requestPublicKey is ECDsa ecDsa) @@ -355,11 +355,11 @@ public static bool IsValidCertRequestSignature(char[] certRequestPem) { byte[] request = PemOperations.GetEncodingFromPem(certRequestPem, "CERTIFICATE REQUEST"); - using AsymmetricAlgorithm pubKey = GetComponentsFromCertRequestDer( + using var pubKey = GetComponentsFromCertRequestDer( request, out byte[] toBeSigned, - out SignatureAlgIdConverter sigAlgId, - out X500DistinguishedName _, + out var sigAlgId, + out var _, out byte[] signature); if (string.Equals(pubKey.SignatureAlgorithm, "RSA", StringComparison.Ordinal)) @@ -375,7 +375,7 @@ public static bool IsValidCertRequestSignature(char[] certRequestPem) // The YubiKey returns the signature in a format that virtually all // standards specify. However, that is not the format the C# // verification method needs. - PivAlgorithm algorithm = pubKey.KeySize switch + var algorithm = pubKey.KeySize switch { 256 => PivAlgorithm.EccP256, 384 => PivAlgorithm.EccP384, @@ -429,16 +429,16 @@ public static bool IsValidCertificateSignature( // signing algID, // signature (BIT STRING) var tlvReader = new TlvReader(certDer); - TlvReader seqReader = tlvReader.ReadNestedTlv(0x30); - ReadOnlyMemory toBeSigned = seqReader.ReadEncoded(0x30); - ReadOnlyMemory algId = seqReader.ReadEncoded(0x30); - ReadOnlyMemory signature = seqReader.ReadValue(0x03); + var seqReader = tlvReader.ReadNestedTlv(0x30); + var toBeSigned = seqReader.ReadEncoded(0x30); + var algId = seqReader.ReadEncoded(0x30); + var signature = seqReader.ReadValue(0x03); var sigAlgId = new SignatureAlgIdConverter(algId.ToArray()); // Get the public key of the verifying cert. We need it as an // AsymmetricAlgorithm object. - using AsymmetricAlgorithm pubKey = GetPublicKeyFromCertificate(issuerCert); + using var pubKey = GetPublicKeyFromCertificate(issuerCert); // The signature is a BIT FIELD so the first octet is the unused // bits. That's why in the following we use a Slice of the signature @@ -456,7 +456,7 @@ public static bool IsValidCertificateSignature( // The YubiKey returns the signature in a format that virtually all // standards specify. However, that is not the format the C# // verification method needs. - PivAlgorithm algorithm = pubKey.KeySize switch + var algorithm = pubKey.KeySize switch { 256 => PivAlgorithm.EccP256, 384 => PivAlgorithm.EccP384, @@ -527,10 +527,10 @@ public static AsymmetricAlgorithm GetComponentsFromCertRequestDer( // signing algID, // signature (BIT STRING) var tlvReader = new TlvReader(requestDer); - TlvReader seqReader = tlvReader.ReadNestedTlv(0x30); - ReadOnlyMemory toBeSignedMemory = seqReader.ReadEncoded(0x30); - ReadOnlyMemory algId = seqReader.ReadEncoded(0x30); - ReadOnlyMemory signatureMemory = seqReader.ReadValue(0x03); + var seqReader = tlvReader.ReadNestedTlv(0x30); + var toBeSignedMemory = seqReader.ReadEncoded(0x30); + var algId = seqReader.ReadEncoded(0x30); + var signatureMemory = seqReader.ReadValue(0x03); toBeSigned = toBeSignedMemory.ToArray(); sigAlgId = new SignatureAlgIdConverter(algId.ToArray()); @@ -549,8 +549,8 @@ public static AsymmetricAlgorithm GetComponentsFromCertRequestDer( tlvReader = new TlvReader(toBeSigned); seqReader = tlvReader.ReadNestedTlv(0x30); _ = seqReader.ReadValue(0x02); - ReadOnlyMemory subjectName = seqReader.ReadEncoded(0x30); - ReadOnlyMemory subjectPublicKeyInfo = seqReader.ReadEncoded(0x30); + var subjectName = seqReader.ReadEncoded(0x30); + var subjectPublicKeyInfo = seqReader.ReadEncoded(0x30); // Build an X500DistinguishedName from the encoded name. requestName = new X500DistinguishedName(subjectName.ToArray()); diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs index f3c675fd..21b543a8 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs @@ -91,7 +91,7 @@ public void AddNameElement(X500NameElement nameElement, string value) // If no elements had been added, this method will throw an exception. public byte[] GetEncodedName() { - Array enumValues = Enum.GetValues(typeof(X500NameElement)); + var enumValues = Enum.GetValues(typeof(X500NameElement)); // The DER encoding is simply the SEQUENCE of each element. // Get each encoding in order. That is, no matter what order they diff --git a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/YubiKeySignatureGenerator.cs b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/YubiKeySignatureGenerator.cs index c6d2adad..c6201dfc 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/YubiKeySignatureGenerator.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/YubiKeySignatureGenerator.cs @@ -74,11 +74,11 @@ public YubiKeySignatureGenerator( _algorithm = pivPublicKey.Algorithm; _rsaPaddingMode = rsaPaddingMode; - using AsymmetricAlgorithm dotNetPublicKey = KeyConverter.GetDotNetFromPivPublicKey(pivPublicKey); + using var dotNetPublicKey = KeyConverter.GetDotNetFromPivPublicKey(pivPublicKey); if (_algorithm.IsRsa()) { - RSASignaturePadding paddingScheme = rsaPaddingMode == RSASignaturePaddingMode.Pss ? + var paddingScheme = rsaPaddingMode == RSASignaturePaddingMode.Pss ? RSASignaturePadding.Pss : RSASignaturePadding.Pkcs1; _defaultGenerator = X509SignatureGenerator.CreateForRSA((RSA)dotNetPublicKey, paddingScheme); } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs index f703bce5..97b450ad 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/DsaSignatureConverter.cs @@ -90,7 +90,7 @@ public static byte[] GetNonStandardDsaFromStandard(byte[] signature, PivAlgorith int offsetR = 0; int offsetS = 0; bool isValid = false; - if (tlvReader.TryReadNestedTlv(out TlvReader seqReader, 0x30)) + if (tlvReader.TryReadNestedTlv(out var seqReader, 0x30)) { if (seqReader.TryReadValue(out rValue, 0x02)) { diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Asymmetric.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Asymmetric.cs index 6aec6347..e4b6a9a4 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Asymmetric.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Asymmetric.cs @@ -36,7 +36,7 @@ public static PivPublicKey GetPivPublicKeyFromDotNet(AsymmetricAlgorithm dotNetO // cast the input to RSA. if (string.Equals(dotNetObject.SignatureAlgorithm, AlgorithmRsa, StringComparison.Ordinal)) { - RSAParameters rsaParams = ((RSA)dotNetObject).ExportParameters(false); + var rsaParams = ((RSA)dotNetObject).ExportParameters(false); // This constructor will validate the modulus and exponent. var rsaPubKey = new PivRsaPublicKey(rsaParams.Modulus, rsaParams.Exponent); return (PivPublicKey)rsaPubKey; diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs index af1dc20e..5476a90b 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/KeyConverter.Pem.cs @@ -35,7 +35,7 @@ public static partial class KeyConverter // -----END PRIVATE KEY----- public static PivPublicKey GetPivPublicKeyFromPem(char[] pemKeyString) { - using AsymmetricAlgorithm dotNetObject = GetDotNetFromPem(pemKeyString, false); + using var dotNetObject = GetDotNetFromPem(pemKeyString, false); return GetPivPublicKeyFromDotNet(dotNetObject); } @@ -46,7 +46,7 @@ public static PivPublicKey GetPivPublicKeyFromPem(char[] pemKeyString) // -----END PUBLIC KEY----- public static char[] GetPemFromPivPublicKey(PivPublicKey pivPublicKey) { - using AsymmetricAlgorithm dotNetObject = GetDotNetFromPivPublicKey(pivPublicKey); + using var dotNetObject = GetDotNetFromPivPublicKey(pivPublicKey); return GetPemFromDotNet(dotNetObject, false); } @@ -57,7 +57,7 @@ public static char[] GetPemFromPivPublicKey(PivPublicKey pivPublicKey) // -----END PRIVATE KEY----- public static PivPrivateKey GetPivPrivateKeyFromPem(char[] pemKeyString) { - using AsymmetricAlgorithm dotNetObject = GetDotNetFromPem(pemKeyString, true); + using var dotNetObject = GetDotNetFromPem(pemKeyString, true); return GetPivPrivateKeyFromDotNet(dotNetObject); } diff --git a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs index c882196d..99ce8e97 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Converters/SignatureAlgIdConverter.cs @@ -99,8 +99,8 @@ public SignatureAlgIdConverter(byte[] algIdDer) PssSaltLength = 0; PssTrailerField = 0; var tlvReader = new TlvReader(algIdDer); - TlvReader seqReader = tlvReader.ReadNestedTlv(0x30); - ReadOnlyMemory oid = seqReader.ReadValue(0x06); + var seqReader = tlvReader.ReadNestedTlv(0x30); + var oid = seqReader.ReadValue(0x06); if (SetFromOid(oid)) { diff --git a/Yubico.YubiKey/examples/PivSampleCode/DotNetOperations/PublicKeyOperations.cs b/Yubico.YubiKey/examples/PivSampleCode/DotNetOperations/PublicKeyOperations.cs index 7785361c..1c33d0d5 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/DotNetOperations/PublicKeyOperations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/DotNetOperations/PublicKeyOperations.cs @@ -48,7 +48,7 @@ public static bool SampleVerifySignature( throw new ArgumentNullException(nameof(publicKey)); } - using AsymmetricAlgorithm asymObject = KeyConverter.GetDotNetFromPivPublicKey(publicKey); + using var asymObject = KeyConverter.GetDotNetFromPivPublicKey(publicKey); // The algorithm is either RSA or ECC, otherwise the KeyConverter // call would have thrown an exception. @@ -139,7 +139,7 @@ public static bool SampleKeyAgreeEcc( // ECDH object from the EC parameters. So get the ECDsa object, then // get the parameters. using var ecDsaObject = (ECDsa)KeyConverter.GetDotNetFromPivPublicKey(publicKey); - ECParameters ecParams = ecDsaObject.ExportParameters(false); + var ecParams = ecDsaObject.ExportParameters(false); // This is the .NET version of the public key associated with the // private key on the YubiKey. The correspondent will combine this diff --git a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs index 32dd7c64..c89fb245 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/Run/PivSampleRun.Operations.cs @@ -104,7 +104,7 @@ public bool RunChangeRetryCount() public bool RunGetPinOnlyMode() { - if (PinOnlyMode.RunGetPivPinOnlyMode(_yubiKeyChosen, out PivPinOnlyMode mode)) + if (PinOnlyMode.RunGetPivPinOnlyMode(_yubiKeyChosen, out var mode)) { SampleMenu.WriteMessage(MessageType.Title, 0, "PIN-only mode: " + mode.ToString() + "\n"); return true; @@ -115,7 +115,7 @@ public bool RunGetPinOnlyMode() public bool RunSetPinOnlyMode() { - if (!GetRequestedPinOnlyMode(out PivPinOnlyMode mode)) + if (!GetRequestedPinOnlyMode(out var mode)) { return RunInvalidEntry(); } @@ -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 var mode)) { SampleMenu.WriteMessage(MessageType.Title, 0, "PIN-only mode: " + mode.ToString() + "\n"); return true; @@ -194,17 +194,17 @@ public bool RunGenerateKeyPair() return RunInvalidEntry(); } - if (!GetAsymmetricAlgorithm(out PivAlgorithm algorithm)) + if (!GetAsymmetricAlgorithm(out var algorithm)) { return RunInvalidEntry(); } - if (!GetPinPolicy(out PivPinPolicy pinPolicy)) + if (!GetPinPolicy(out var pinPolicy)) { return RunInvalidEntry(); } - if (!GetTouchPolicy(out PivTouchPolicy touchPolicy)) + if (!GetTouchPolicy(out var touchPolicy)) { return RunInvalidEntry(); } @@ -216,7 +216,7 @@ public bool RunGenerateKeyPair() algorithm, pinPolicy, touchPolicy, - out SamplePivSlotContents newSlotContents)) + out var newSlotContents)) { newSlotContents.PrintPublicKeyPem(); AddSlotContents(newSlotContents); @@ -233,17 +233,17 @@ public bool RunImportPrivateKey() return RunInvalidEntry(); } - if (!GetAsymmetricAlgorithm(out PivAlgorithm algorithm)) + if (!GetAsymmetricAlgorithm(out var algorithm)) { return RunInvalidEntry(); } - if (!GetPinPolicy(out PivPinPolicy pinPolicy)) + if (!GetPinPolicy(out var pinPolicy)) { return RunInvalidEntry(); } - if (!GetTouchPolicy(out PivTouchPolicy touchPolicy)) + if (!GetTouchPolicy(out var touchPolicy)) { return RunInvalidEntry(); } @@ -253,8 +253,8 @@ public bool RunImportPrivateKey() return false; } - PivPrivateKey pivPrivateKey = KeyConverter.GetPivPrivateKeyFromPem(pemKey.ToCharArray()); - PivPublicKey pivPublicKey = KeyConverter.GetPivPublicKeyFromPem(pemKey.ToCharArray()); + var pivPrivateKey = KeyConverter.GetPivPrivateKeyFromPem(pemKey.ToCharArray()); + var pivPublicKey = KeyConverter.GetPivPublicKeyFromPem(pemKey.ToCharArray()); if (KeyPairs.RunImportPrivateKey( _yubiKeyChosen, @@ -264,7 +264,7 @@ public bool RunImportPrivateKey() slotNumber, pinPolicy, touchPolicy, - out SamplePivSlotContents newSlotContents)) + out var newSlotContents)) { newSlotContents.PrintPublicKeyPem(); AddSlotContents(newSlotContents); @@ -294,7 +294,7 @@ public bool RunSignData() // the code needs to know if the key's algorithm is RSA. If // so, it will need to pad the digest. // Hence, get the algorithm. - SamplePivSlotContents signSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); + var signSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); if (signSlotContents is null) { return RunInvalidEntry(); @@ -302,7 +302,7 @@ public bool RunSignData() // This sample code will use SHA-384 for EccP384, and SHA-256 // for all other algorithms. - HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA384; + var hashAlgorithm = HashAlgorithmName.SHA384; if (signSlotContents.Algorithm != PivAlgorithm.EccP384) { hashAlgorithm = HashAlgorithmName.SHA256; @@ -312,7 +312,7 @@ public bool RunSignData() // This sample code will always use PSS for the RSA padding // scheme. - RSASignaturePadding signPaddingScheme = RSASignaturePadding.Pss; + var signPaddingScheme = RSASignaturePadding.Pss; if (!PrivateKeyOperations.RunSignData( _yubiKeyChosen, @@ -359,7 +359,7 @@ public bool RunDecryptData() } // It is possible to decrypt only if the key is RSA. - SamplePivSlotContents decryptSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); + var decryptSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); if (decryptSlotContents is null) { return RunInvalidEntry(); @@ -380,7 +380,7 @@ public bool RunDecryptData() // This sample uses OAEP with SHA-256 as the padding scheme // for all RSA key sizes. - RSAEncryptionPadding encryptPaddingScheme = RSAEncryptionPadding.OaepSHA256; + var encryptPaddingScheme = RSAEncryptionPadding.OaepSHA256; if (!PublicKeyOperations.SampleEncryptRsa( decryptSlotContents.PublicKey, @@ -424,7 +424,7 @@ public bool RunKeyAgree() } // It is possible to perform Key Agreement only if the key is ECC. - SamplePivSlotContents keyAgreeSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); + var keyAgreeSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); if (keyAgreeSlotContents is null) { return RunInvalidEntry(); @@ -447,7 +447,7 @@ public bool RunKeyAgree() // send the shared secret, but for this sample, we're // returning it as well so that we can compare the two // results to make sure they match. - HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; + var hashAlgorithm = HashAlgorithmName.SHA256; if (keyAgreeSlotContents.Algorithm == PivAlgorithm.EccP384) { hashAlgorithm = HashAlgorithmName.SHA384; @@ -462,7 +462,7 @@ public bool RunKeyAgree() return false; } - PivPublicKey correspondentKey = KeyConverter.GetPivPublicKeyFromPem(correspondentPublicKey); + var correspondentKey = KeyConverter.GetPivPublicKeyFromPem(correspondentPublicKey); if (!PrivateKeyOperations.RunKeyAgree( _yubiKeyChosen, @@ -499,7 +499,7 @@ public bool RunGetCertRequest() return RunInvalidEntry(); } - SamplePivSlotContents requestSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); + var requestSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); if (requestSlotContents is null) { return RunInvalidEntry(); @@ -511,7 +511,7 @@ public bool RunGetCertRequest() nameBuilder.AddNameElement(X500NameElement.Locality, "Palo Alto"); nameBuilder.AddNameElement(X500NameElement.Organization, "Fake"); nameBuilder.AddNameElement(X500NameElement.CommonName, "Fake Cert"); - X500DistinguishedName sampleCertName = nameBuilder.GetDistinguishedName(); + var sampleCertName = nameBuilder.GetDistinguishedName(); SampleCertificateOperations.GetCertRequest( _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, @@ -531,7 +531,7 @@ public bool RunBuildSelfSignedCert() return RunInvalidEntry(); } - SamplePivSlotContents selfSignedSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); + var selfSignedSlotContents = _slotContentsList.Find(x => x.SlotNumber == slotNumber); if (selfSignedSlotContents is null) { return RunInvalidEntry(); @@ -557,7 +557,7 @@ public bool RunBuildCert() return RunInvalidEntry(); } - SamplePivSlotContents requestorSlotContents = _slotContentsList.Find(x => x.SlotNumber == requestorSlotNumber); + var requestorSlotContents = _slotContentsList.Find(x => x.SlotNumber == requestorSlotNumber); if (requestorSlotContents is null) { return RunInvalidEntry(); @@ -569,7 +569,7 @@ public bool RunBuildCert() return RunInvalidEntry(); } - SamplePivSlotContents signerSlotContents = _slotContentsList.Find(x => x.SlotNumber == signerSlotNumber); + var signerSlotContents = _slotContentsList.Find(x => x.SlotNumber == signerSlotNumber); if (signerSlotContents is null) { return RunInvalidEntry(); @@ -602,7 +602,7 @@ public bool RunRetrieveCert() _yubiKeyChosen, _keyCollector.SampleKeyCollectorDelegate, slotNumber, - out X509Certificate2 certificate); + out var certificate); byte[] certDer = certificate.Export(X509ContentType.Cert); char[] certPem = PemOperations.BuildPem("CERTIFICATE", certDer); @@ -620,7 +620,7 @@ public bool RunCreateAttestationStatement() KeyPairs.RunCreateAttestationStatement( _yubiKeyChosen, slotNumber, - out X509Certificate2 certificate); + out var certificate); byte[] certDer = certificate.Export(X509ContentType.Cert); char[] certPem = PemOperations.BuildPem("CERTIFICATE", certDer); @@ -630,7 +630,7 @@ public bool RunCreateAttestationStatement() public bool RunGetAttestationCert() { - KeyPairs.RunGetAttestationCert(_yubiKeyChosen, out X509Certificate2 certificate); + KeyPairs.RunGetAttestationCert(_yubiKeyChosen, out var certificate); byte[] certDer = certificate.Export(X509ContentType.Cert); char[] certPem = PemOperations.BuildPem("CERTIFICATE", certDer); diff --git a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs index cc04d5a1..4e3a8f39 100644 --- a/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs +++ b/Yubico.YubiKey/examples/PivSampleCode/YubiKeyOperations/KeyPairs.cs @@ -33,7 +33,7 @@ public static bool RunGenerateKeyPair( { pivSession.KeyCollector = KeyCollectorDelegate; - PivPublicKey pivPublicKey = pivSession.GenerateKeyPair(slotNumber, algorithm, pinPolicy, touchPolicy); + var pivPublicKey = pivSession.GenerateKeyPair(slotNumber, algorithm, pinPolicy, touchPolicy); // At this point you will likely want to save the public key and // other information. For this sample, we're simply going to diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs index 669dcd35..514443b0 100644 --- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs +++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ChooseYubiKey.cs @@ -56,8 +56,7 @@ public static bool RunChooseYubiKey( } // Find all currently connected YubiKeys. - IEnumerable yubiKeyEnumerable = YubiKeyDevice.FindByTransport(transport); - IYubiKeyDevice[] yubiKeyArray = yubiKeyEnumerable.ToArray(); + var yubiKeyArray = YubiKeyDevice.FindByTransport(transport).ToArray(); // Are there any? if (yubiKeyArray.Length == 0) diff --git a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs index 008b26d2..5fe3cf9f 100644 --- a/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs +++ b/Yubico.YubiKey/examples/SharedSampleCode/YubiKeyOperations/ListYubiKeys.cs @@ -26,7 +26,7 @@ public static class ListYubiKeys // none available is a successful completion of its task. public static bool RunListYubiKeys(Transport transport) { - IEnumerable yubiKeyEnumerable = YubiKeyDevice.FindByTransport(transport); + var yubiKeyEnumerable = YubiKeyDevice.FindByTransport(transport); ReportResult(yubiKeyEnumerable); @@ -42,7 +42,7 @@ private static void ReportResult(IEnumerable yubiKeyEnumerable) if (yubiKeyDevices.Any()) { outputList = "\n YubiKeys:"; - foreach (IYubiKeyDevice current in yubiKeyDevices) + foreach (var current in yubiKeyDevices) { int serial = 0; if (!(current.SerialNumber is null)) diff --git a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs index 6f483c54..0d990d32 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/Run/U2fSampleRun.Operations.cs @@ -184,7 +184,7 @@ public bool RunRegisterCredential() _keyCollector.Operation = U2fKeyCollectorOperation.Register; if (!U2fProtocol.Register( _yubiKeyChosen, _keyCollector.U2fSampleKeyCollectorDelegate, - applicationId, clientDataHash, out RegistrationData registrationData)) + applicationId, clientDataHash, out var registrationData)) { return false; } @@ -226,7 +226,7 @@ public bool RunAuthenticateCredential() } int response = _menuObject.RunMenu("Which credential is to be authenticated?", nameList); - RegistrationData regData = _credentials[nameList[response]]; + var regData = _credentials[nameList[response]]; // There are a number of ways a credential can be unauthenticated. // One way is if the keyHandle is invalid. If that is the case, we @@ -259,7 +259,7 @@ public bool RunAuthenticateCredential() if (!U2fProtocol.Authenticate( _yubiKeyChosen, _keyCollector.U2fSampleKeyCollectorDelegate, regData.ApplicationId, regData.ClientDataHash, regData.KeyHandle, - out AuthenticationData authenticationData)) + out var authenticationData)) { return false; } @@ -395,7 +395,7 @@ private static string GetRelyingPartyChallenge() SampleMenu.WriteMessage(MessageType.Title, 0, "For this sample code, the challenge is a random value base-64 encoded\n"); byte[] randomBytes = new byte[9]; - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); randomObject.GetBytes(randomBytes, 0, randomBytes.Length); string challenge = Convert.ToBase64String(randomBytes); SampleMenu.WriteMessage(MessageType.Title, 0, "challenge = " + challenge); diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs index 317bbc1c..47349fe9 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fFips.cs @@ -34,7 +34,7 @@ public static bool GetFipsMode(IYubiKeyDevice yubiKey, out bool isFipsMode) using (var u2fSession = new U2fSession(yubiKey)) { var fipsModeCommand = new VerifyFipsModeCommand(); - VerifyFipsModeResponse fipsModeResponse = u2fSession.Connection.SendCommand(fipsModeCommand); + var fipsModeResponse = u2fSession.Connection.SendCommand(fipsModeCommand); isFipsMode = fipsModeResponse.GetData(); return true; diff --git a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs index ab9af48e..3d46f19e 100644 --- a/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs +++ b/Yubico.YubiKey/examples/U2fSampleCode/YubiKeyOperations/U2fReset.cs @@ -61,10 +61,10 @@ public bool RunU2fReset(Func KeyCollector) _yubiKeyDevice = null; var keyEntryData = new KeyEntryData(); - KeyEntryRequest keyEntryRequest = KeyEntryRequest.TouchRequest; + var keyEntryRequest = KeyEntryRequest.TouchRequest; Task? touchMessageTask = null; - YubiKeyDeviceListener yubiKeyDeviceListener = YubiKeyDeviceListener.Instance; + var yubiKeyDeviceListener = YubiKeyDeviceListener.Instance; yubiKeyDeviceListener.Arrived += YubiKeyInserted; yubiKeyDeviceListener.Removed += YubiKeyRemoved; @@ -87,9 +87,9 @@ public bool RunU2fReset(Func KeyCollector) // The YubiKey has been rebooted, so we need to quickly reset. try { - using IYubiKeyConnection connection = reinsert.Result.Connect(YubiKeyApplication.FidoU2f); + using var connection = reinsert.Result.Connect(YubiKeyApplication.FidoU2f); var resetCmd = new ResetCommand(); - ResetResponse resetRsp = connection.SendCommand(resetCmd); + var resetRsp = connection.SendCommand(resetCmd); while (resetRsp.Status == ResponseStatus.ConditionsNotSatisfied) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/AesUtilities.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/AesUtilities.cs index 9d4086e6..a4750999 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/AesUtilities.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/AesUtilities.cs @@ -51,7 +51,7 @@ public static byte[] BlockCipher(byte[] key, ReadOnlySpan plaintext) byte[] ciphertext; - using (Aes aesObj = CryptographyProviders.AesCreator()) + using (var aesObj = CryptographyProviders.AesCreator()) { #pragma warning disable CA5358 // Allow the usage of cipher mode 'ECB' aesObj.Mode = CipherMode.ECB; @@ -63,7 +63,7 @@ public static byte[] BlockCipher(byte[] key, ReadOnlySpan plaintext) aesObj.Padding = PaddingMode.None; #pragma warning disable CA5401 // Justification: Allow the symmetric encryption to use // a non-default initialization vector - ICryptoTransform encryptor = aesObj.CreateEncryptor(); + var encryptor = aesObj.CreateEncryptor(); #pragma warning restore CA5401 using (var msEncrypt = new MemoryStream()) { @@ -117,7 +117,7 @@ public static byte[] AesCbcEncrypt(byte[] key, byte[] iv, ReadOnlySpan pla byte[] ciphertext; - using (Aes aesObj = CryptographyProviders.AesCreator()) + using (var aesObj = CryptographyProviders.AesCreator()) { aesObj.Mode = CipherMode.CBC; aesObj.KeySize = BlockSizeBits; @@ -127,7 +127,7 @@ public static byte[] AesCbcEncrypt(byte[] key, byte[] iv, ReadOnlySpan pla aesObj.Padding = PaddingMode.None; #pragma warning disable CA5401 // Justification: Allow the symmetric encryption to use // a non-default initialization vector - ICryptoTransform encryptor = aesObj.CreateEncryptor(); + var encryptor = aesObj.CreateEncryptor(); #pragma warning restore CA5401 using (var msEncrypt = new MemoryStream()) { @@ -181,7 +181,7 @@ public static byte[] AesCbcDecrypt(byte[] key, byte[] iv, ReadOnlySpan cip byte[] plaintext; - using (Aes aesObj = CryptographyProviders.AesCreator()) + using (var aesObj = CryptographyProviders.AesCreator()) { aesObj.Mode = CipherMode.CBC; aesObj.KeySize = BlockSizeBits; @@ -190,7 +190,7 @@ public static byte[] AesCbcDecrypt(byte[] key, byte[] iv, ReadOnlySpan cip aesObj.IV = iv; aesObj.Padding = PaddingMode.None; - ICryptoTransform decryptor = aesObj.CreateDecryptor(); + var decryptor = aesObj.CreateDecryptor(); using (var msDecrypt = new MemoryStream()) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs index 2f2423f0..4a19c0b5 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/EcdsaVerify.cs @@ -182,10 +182,11 @@ public EcdsaVerify(PivPublicKey pivPublicKey) throw new ArgumentNullException(nameof(pivPublicKey)); } - ReadOnlySpan pubPoint = pivPublicKey is PivEccPublicKey eccKey - ? eccKey.PublicPoint : ReadOnlySpan.Empty; + var publicPointSpan = pivPublicKey is PivEccPublicKey eccKey + ? eccKey.PublicPoint + : ReadOnlySpan.Empty; - ECDsa = ConvertPublicKey(pubPoint.ToArray()); + ECDsa = ConvertPublicKey(publicPointSpan.ToArray()); } /// @@ -387,7 +388,7 @@ private static ECDsa ConvertPublicKey(string oid, byte[] xCoordinate, byte[] yCo var eccCurve = ECCurve.CreateFromValue(oid); var eccParams = new ECParameters { - Curve = (ECCurve)eccCurve + Curve = eccCurve }; eccParams.Q.X = xCoordinate; @@ -401,18 +402,18 @@ private static ECDsa ConvertPublicKey(string oid, byte[] xCoordinate, byte[] yCo private static ECDsa CheckECDsa(ECDsa toCheck) { - ECParameters eccParams = toCheck.ExportParameters(false); + var ecParameters = toCheck.ExportParameters(false); - int coordinateLength = eccParams.Curve.Oid.Value switch + int coordinateLength = ecParameters.Curve.Oid.Value switch { OidP256 => (P256EncodedPointLength - 1) / 2, OidP384 => (P384EncodedPointLength - 1) / 2, _ => -1, }; - if (eccParams.Q.X.Length > 0 && eccParams.Q.X.Length <= coordinateLength) + if (ecParameters.Q.X.Length > 0 && ecParameters.Q.X.Length <= coordinateLength) { - if (eccParams.Q.Y.Length > 0 && eccParams.Q.Y.Length <= coordinateLength) + if (ecParameters.Q.Y.Length > 0 && ecParameters.Q.Y.Length <= coordinateLength) { return toCheck; } @@ -455,7 +456,7 @@ private static byte[] ConvertSignature(byte[] signature, int publicKeyBitSize) // If the number of non-zero bytes is > CoordinateLength, return false. private static bool TryCopyNextInteger(TlvReader tlvReader, Memory signatureValue, int coordinateLength) { - if (tlvReader.TryReadValue(out ReadOnlyMemory rsValue, IntegerTag)) + if (tlvReader.TryReadValue(out var rsValue, IntegerTag)) { // strip any leading 00 bytes. int length = rsValue.Length; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs index 8a44f19f..02d55b59 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/RsaFormat.cs @@ -327,22 +327,22 @@ public static bool TryParsePkcs1Verify(ReadOnlySpan formattedSignature, var tlvReader = new TlvReader(digestInfo); isValid = TryReadDer( - true, ReadNestedNoMoreData, SequenceTag, tlvReader, out TlvReader infoReader, + true, ReadNestedNoMoreData, SequenceTag, tlvReader, out var infoReader, out _); - isValid = TryReadDer(isValid, ReadNested, SequenceTag, infoReader, out TlvReader oidReader, out _); - isValid = TryReadDer(isValid, ReadValue, OidTag, oidReader, out _, out ReadOnlyMemory oid); + isValid = TryReadDer(isValid, ReadNested, SequenceTag, infoReader, out var oidReader, out _); + isValid = TryReadDer(isValid, ReadValue, OidTag, oidReader, out _, out var oid); isValid = TryReadDer( isValid, ReadValueNoMoreData, NullTag, oidReader, out _, - out ReadOnlyMemory oidParams); + out var oidParamsBytes); isValid = TryReadDer( isValid, ReadValueNoMoreData, OctetTag, infoReader, out _, - out ReadOnlyMemory digestData); + out var digestDataBytes); - isValid = TryParseOid(isValid, oid, oidParams, digestData, out digestAlgorithm); - digest = digestData.ToArray(); + isValid = TryParseOid(isValid, oid, oidParamsBytes, digestDataBytes, out digestAlgorithm); + digest = digestDataBytes.ToArray(); } finally { @@ -427,9 +427,9 @@ public static byte[] FormatPkcs1Pss(ReadOnlySpan digest, int digestAlgorit var bufferAsSpan = new Span(buffer); - using HashAlgorithm digester = GetHashAlgorithm(digestAlgorithm); + using var digestHashAlgorithm = GetHashAlgorithm(digestAlgorithm); - if (digest.Length * 8 != digester.HashSize) + if (digest.Length * 8 != digestHashAlgorithm.HashSize) { throw new ArgumentException( string.Format( @@ -457,26 +457,26 @@ public static byte[] FormatPkcs1Pss(ReadOnlySpan digest, int digestAlgorit // Create H which is the digest of M' = 00 ... 00 || digest || salt. // that's 8 00 octets, the digest, and 20 bytes of random salt. - _ = digester.TransformBlock(buffer, 0, 8, null, 0); + _ = digestHashAlgorithm.TransformBlock(buffer, 0, 8, null, 0); // Now copy the digest into the buffer, just so we can operate on it // (we need it in a byte array, not a Span). digest.CopyTo(bufferAsSpan[offsetHash..]); - _ = digester.TransformBlock(buffer, offsetHash, digest.Length, null, 0); + _ = digestHashAlgorithm.TransformBlock(buffer, offsetHash, digest.Length, null, 0); // Generate the random salt and digest it. - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); randomObject.GetBytes(buffer, offsetSalt, digest.Length); - _ = digester.TransformFinalBlock(buffer, offsetSalt, digest.Length); + _ = digestHashAlgorithm.TransformFinalBlock(buffer, offsetSalt, digest.Length); // Place H into its location in the buffer. // Also, place the 01 (that comes after PS) and the trailer field. - Array.Copy(digester.Hash, 0, buffer, offsetHash, digester.Hash.Length); + Array.Copy(digestHashAlgorithm.Hash, 0, buffer, offsetHash, digestHashAlgorithm.Hash.Length); buffer[psLength] = 1; buffer[^1] = TrailerField; // Now compute the mask for DB using MGF1. - PerformMgf1(buffer, offsetHash, digest.Length, buffer, 0, psLength + digest.Length + 1, digester); + PerformMgf1(buffer, offsetHash, digest.Length, buffer, 0, psLength + digest.Length + 1, digestHashAlgorithm); // Note that at this point, the algorithm calls for making sure the // appropriate leading bits are all 0. Because we support only 1024- @@ -694,9 +694,9 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature, return false; } - using HashAlgorithm digester = GetHashAlgorithm(digestAlgorithm); + using var digestHashAlgorithm = GetHashAlgorithm(digestAlgorithm); - if (digest.Length * 8 != digester.HashSize) + if (digest.Length * 8 != digestHashAlgorithm.HashSize) { throw new ArgumentException( string.Format( @@ -726,7 +726,7 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature, } // Run MGF1 to unmask the PS and salt. - PerformMgf1(buffer, offsetHash, digest.Length, buffer, 0, psLength + digest.Length + 1, digester); + PerformMgf1(buffer, offsetHash, digest.Length, buffer, 0, psLength + digest.Length + 1, digestHashAlgorithm); // It's possible the most significant bit is set if it had been // "manually" removed when signing. So remove it here. @@ -762,9 +762,9 @@ public static bool TryParsePkcs1Pss(ReadOnlySpan formattedSignature, Array.Copy(buffer, offsetHash, mPrimeAndH, mPrimeLength, digest.Length); // Compute Digest of M-prime and compare it to H. - digester.Initialize(); - _ = digester.TransformFinalBlock(mPrimeAndH, 0, mPrimeLength); - var digestAsSpan = new Span(digester.Hash); + digestHashAlgorithm.Initialize(); + _ = digestHashAlgorithm.TransformFinalBlock(mPrimeAndH, 0, mPrimeLength); + var digestAsSpan = new Span(digestHashAlgorithm.Hash); isVerified = digestAsSpan.SequenceEqual(mPrimeAsSpan[mPrimeLength..]); } @@ -872,7 +872,7 @@ public static byte[] FormatPkcs1Encrypt(ReadOnlySpan inputData, int keySiz // Generate non-00 random pad bytes. int paddingLength = buffer.Length - (inputData.Length + 3); - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); randomObject.GetBytes(buffer, 2, paddingLength); int index; @@ -885,7 +885,7 @@ public static byte[] FormatPkcs1Encrypt(ReadOnlySpan inputData, int keySiz buffer[1] = Pkcs1EncryptByte; buffer[paddingLength + 2] = Pkcs1Separator; - Span bufferAsSpan = new Span(buffer)[(paddingLength + 3)..]; + var bufferAsSpan = new Span(buffer)[(paddingLength + 3)..]; inputData.CopyTo(bufferAsSpan); return buffer; @@ -1110,9 +1110,9 @@ public static byte[] FormatPkcs1Oaep(ReadOnlySpan inputData, int digestAlg var bufferAsSpan = new Span(buffer); - using HashAlgorithm digester = GetHashAlgorithm(digestAlgorithm); + using var digestHashAlgorithm = GetHashAlgorithm(digestAlgorithm); - int digestLength = digester.HashSize / 8; + int digestLength = digestHashAlgorithm.HashSize / 8; if (inputData.Length == 0 || inputData.Length > buffer.Length - ((2 * digestLength) + 2)) { @@ -1126,14 +1126,14 @@ public static byte[] FormatPkcs1Oaep(ReadOnlySpan inputData, int digestAlg // 00 || seed || lHash || PS || 01 || input data // Beginning with lHash is the DB // DB = lHash || PS || 01 || input data - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); // seed randomObject.GetBytes(buffer, 1, digestLength); // lHash = digest of empty string. - _ = digester.TransformFinalBlock(buffer, 0, 0); - Array.Copy(digester.Hash, 0, buffer, digestLength + 1, digestLength); + _ = digestHashAlgorithm.TransformFinalBlock(buffer, 0, 0); + Array.Copy(digestHashAlgorithm.Hash, 0, buffer, digestLength + 1, digestLength); // 01 buffer[^(inputData.Length + 1)] = 1; @@ -1142,12 +1142,12 @@ public static byte[] FormatPkcs1Oaep(ReadOnlySpan inputData, int digestAlg // Use the seed to mask the DB. PerformMgf1( buffer, 1, digestLength, buffer, digestLength + 1, buffer.Length - (digestLength + 1), - digester); + digestHashAlgorithm); // Use the masked DB to mask the seed. PerformMgf1( buffer, digestLength + 1, buffer.Length - (digestLength + 1), buffer, 1, digestLength, - digester); + digestHashAlgorithm); return buffer; } @@ -1249,15 +1249,15 @@ public static bool TryParsePkcs1Oaep(ReadOnlySpan formattedData, return false; } - using HashAlgorithm digester = GetHashAlgorithm(digestAlgorithm); + using var digestHashAlgorithm = GetHashAlgorithm(digestAlgorithm); - int digestLength = digester.HashSize / 8; + int digestLength = digestHashAlgorithm.HashSize / 8; // Run all checks, even if a previous one failed, to help avoid // timing attacks. // The most significant byte must be 0. - int errorCount = (int)formattedData[0]; + int errorCount = formattedData[0]; // Copy the data into a byte[], so we can change the data (unmask) and // also pass it as an argument to the digester. @@ -1268,25 +1268,25 @@ public static bool TryParsePkcs1Oaep(ReadOnlySpan formattedData, // Use the masked DB to unmask the seed. PerformMgf1( buffer, digestLength + 1, buffer.Length - (digestLength + 1), buffer, 1, digestLength, - digester); + digestHashAlgorithm); // Use the seed to unmask the DB. PerformMgf1( buffer, 1, digestLength, buffer, digestLength + 1, buffer.Length - (digestLength + 1), - digester); + digestHashAlgorithm); // Verify the DB // block = 00 || salt || DB // DB = lHash || PS || 01 || input data // lHash = digest of empty string. - digester.Initialize(); - _ = digester.TransformFinalBlock(buffer, 0, 0); + digestHashAlgorithm.Initialize(); + _ = digestHashAlgorithm.TransformFinalBlock(buffer, 0, 0); int index = 0; for (; index < digestLength; index++) { - errorCount += (int)(digester.Hash[index] ^ buffer[index + digestLength + 1]); + errorCount += (int)(digestHashAlgorithm.Hash[index] ^ buffer[index + digestLength + 1]); } // Find the first byte after the PS, make sure it is 01. @@ -1379,7 +1379,7 @@ private static int BuildDigestInfo(ReadOnlySpan digest, int digestAlgorith // 04 digestLength // digest int totalLength = 10 + oid.Length + digestLength; - Span output = buffer[^totalLength..]; + var output = buffer[^totalLength..]; var tlvWriter = new TlvWriter(); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs index 2fbfacdc..6db3df20 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/AuthenticatorInfo.cs @@ -333,13 +333,13 @@ public AuthenticatorInfo(ReadOnlyMemory cborEncoding) } if (cborMap.Contains(KeyOptions)) { - CborMap optionsMap = cborMap.ReadMap(KeyOptions); - Options = optionsMap.AsDictionary(); + var optionsCborMap = cborMap.ReadMap(KeyOptions); + Options = optionsCborMap.AsDictionary(); } MaximumMessageSize = (int?)cborMap.ReadOptional(KeyMaxMsgSize); if (cborMap.Contains(KeyPinUvAuthProtocols)) { - IReadOnlyList temp = cborMap.ReadArray(KeyPinUvAuthProtocols); + var temp = cborMap.ReadArray(KeyPinUvAuthProtocols); var translator = new List(temp.Count); for (int index = 0; index < temp.Count; index++) { @@ -367,13 +367,13 @@ public AuthenticatorInfo(ReadOnlyMemory cborEncoding) UvModality = (int?)cborMap.ReadOptional(KeyUvModality); if (cborMap.Contains(KeyCertifications)) { - CborMap certMap = cborMap.ReadMap(KeyCertifications); - Certifications = certMap.AsDictionary(); + var certCborMap = cborMap.ReadMap(KeyCertifications); + Certifications = certCborMap.AsDictionary(); } RemainingDiscoverableCredentials = (int?)cborMap.ReadOptional(KeyRemainingDiscoverableCredentials); if (cborMap.Contains(KeyVendorPrototypeConfigCommands)) { - IReadOnlyList intList = cborMap.ReadArray(KeyVendorPrototypeConfigCommands); + var intList = cborMap.ReadArray(KeyVendorPrototypeConfigCommands); var int64List = new List(intList.Count); for (int index = 0; index < intList.Count; index++) { @@ -486,7 +486,7 @@ private void ReadAlgorithms(CborMap cborMap) { var algorithms = new List>(); - IReadOnlyList> entries = cborMap.ReadArray>(KeyAlgorithms); + var entries = cborMap.ReadArray>(KeyAlgorithms); for (int index = 0; index < entries.Count; index++) { string currentType = entries[index].ReadTextString(ParameterHelpers.TagType); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs index 52cff753..003f6103 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborHelpers.cs @@ -74,16 +74,16 @@ internal static class CborHelpers int? entries = cbor.ReadStartArray(); int count = entries ?? 0; - List dest = destination ?? new List(count); + var allDestinationsList = destination ?? new List(count); for (int index = 0; index < count; index++) { - dest.Add(cbor.ReadTextString()); + allDestinationsList.Add(cbor.ReadTextString()); } cbor.ReadEndArray(); - return dest; + return allDestinationsList; } /// @@ -149,7 +149,7 @@ public static byte[] EncodeArrayOfObjects(IReadOnlyList? localData) var cbor = new CborWriter(CborConformanceMode.Ctap2Canonical, convertIndefiniteLengthEncodings: true); cbor.WriteStartArray(localData.Count); - foreach (ICborEncode cborEncode in localData) + foreach (var cborEncode in localData) { cbor.WriteEncodedValue(cborEncode.CborEncode()); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs index 147ff45b..210ee8ae 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Cbor/CborMap.cs @@ -66,7 +66,7 @@ public CborMap(ReadOnlyMemory encoding) while (count > 0) { - TKey currentKey = ReadKey(cbor); + var currentKey = ReadKey(cbor); object? currentValue = ProcessSingleElement(cbor); _dict.Add(currentKey, currentValue); @@ -101,7 +101,7 @@ public CborMap(ReadOnlyMemory encoding) public IReadOnlyDictionary AsDictionary() { var returnValue = new Dictionary(_dict.Count); - foreach (KeyValuePair entry in _dict) + foreach (var entry in _dict) { object? currentValue = ConvertValue(entry.Value); if (!(currentValue is TValue targetValue)) @@ -434,18 +434,18 @@ private static TReadKey ReadKey(CborReader cbor) private static object? ProcessSubMap(CborReader cbor) { - ReadOnlyMemory encodedMap = cbor.ReadEncodedValue(); - var subCbor = new CborReader(encodedMap, CborConformanceMode.Ctap2Canonical); + var encodedMapBytes = cbor.ReadEncodedValue(); + var subCbor = new CborReader(encodedMapBytes, CborConformanceMode.Ctap2Canonical); _ = subCbor.ReadStartMap(); - CborReaderState cborType = subCbor.PeekState(); + var cborType = subCbor.PeekState(); switch (cborType) { case CborReaderState.UnsignedInteger: case CborReaderState.NegativeInteger: - return new CborMap(encodedMap); + return new CborMap(encodedMapBytes); case CborReaderState.TextString: - return new CborMap(encodedMap); + return new CborMap(encodedMapBytes); default: throw new InvalidOperationException(ExceptionMessages.TypeNotSupported); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginResponse.cs index cc140b67..f6833709 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollBeginResponse.cs @@ -42,16 +42,16 @@ public BioEnrollBeginResponse(ResponseApdu responseApdu) /// public BioEnrollSampleResult GetData() { - BioEnrollmentData enrollData = _response.GetData(); + var bioEnrollmentData = _response.GetData(); - if (!(enrollData.TemplateId is null) - && !(enrollData.LastEnrollSampleStatus is null) - && !(enrollData.RemainingSampleCount is null)) + if (!(bioEnrollmentData.TemplateId is null) + && !(bioEnrollmentData.LastEnrollSampleStatus is null) + && !(bioEnrollmentData.RemainingSampleCount is null)) { return new BioEnrollSampleResult( - enrollData.TemplateId.Value, - enrollData.LastEnrollSampleStatus.Value, - enrollData.RemainingSampleCount.Value); + bioEnrollmentData.TemplateId.Value, + bioEnrollmentData.LastEnrollSampleStatus.Value, + bioEnrollmentData.RemainingSampleCount.Value); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollEnumerateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollEnumerateResponse.cs index a09ef9df..d346b636 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollEnumerateResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollEnumerateResponse.cs @@ -55,11 +55,10 @@ public IReadOnlyList GetData() return new List(); } - BioEnrollmentData enrollData = _response.GetData(); - - if (!(enrollData.TemplateInfos is null)) + var bioEnrollmentData = _response.GetData(); + if (!(bioEnrollmentData.TemplateInfos is null)) { - return enrollData.TemplateInfos; + return bioEnrollmentData.TemplateInfos; } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleResponse.cs index e90aac06..24bc0134 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollNextSampleResponse.cs @@ -53,15 +53,14 @@ public BioEnrollSampleResult GetData() throw new InvalidOperationException(StatusMessage); } - BioEnrollmentData enrollData = _response.GetData(); - - if (!(enrollData.LastEnrollSampleStatus is null) - && !(enrollData.RemainingSampleCount is null)) + var bioEnrollmentData = _response.GetData(); + if (!(bioEnrollmentData.LastEnrollSampleStatus is null) + && !(bioEnrollmentData.RemainingSampleCount is null)) { return new BioEnrollSampleResult( _templateId, - enrollData.LastEnrollSampleStatus.Value, - enrollData.RemainingSampleCount.Value); + bioEnrollmentData.LastEnrollSampleStatus.Value, + bioEnrollmentData.RemainingSampleCount.Value); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollmentData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollmentData.cs index d623f8d8..33803b09 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollmentData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/BioEnrollmentData.cs @@ -175,9 +175,9 @@ public BioEnrollmentData(ReadOnlyMemory cborEncoding) if (cborMap.Contains(KeyTemplateInfos)) { - IReadOnlyList> templateList = cborMap.ReadArray>(KeyTemplateInfos); - var templateInfos = new List(templateList.Count); - foreach (CborMap currentMap in templateList) + var cborTemplateList = cborMap.ReadArray>(KeyTemplateInfos); + var templateInfos = new List(cborTemplateList.Count); + foreach (var currentMap in cborTemplateList) { byte[] currentId = currentMap.ReadByteString(KeyTemplateInfoId).ToArray(); string friendlyName = currentMap.Contains(KeyFriendlyName) ? diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs index 50d41e5d..1a360f23 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/ChangePinCommand.cs @@ -155,7 +155,7 @@ public ChangePinCommand(PinUvAuthProtocolBase pinProtocol, ReadOnlyMemory ExceptionMessages.InvalidFido2Pin)); } - using SHA256 sha256Object = CryptographyProviders.Sha256Creator(); + using var sha256Object = CryptographyProviders.Sha256Creator(); byte[] pin = currentPin.ToArray(); byte[] digest = sha256Object.ComputeHash(pin); CryptographicOperations.ZeroMemory(pin); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginResponse.cs index d710c1f3..c926147f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsBeginResponse.cs @@ -71,22 +71,22 @@ public EnumerateCredentialsBeginResponse(ResponseApdu responseApdu) /// public (int credentialCount, CredentialUserInfo credentialUserInfo) GetData() { - CredentialManagementData mgmtData = _response.GetData(); + var credentialManagementData = _response.GetData(); - if (!(mgmtData.TotalCredentialsForRelyingParty is null) - && !(mgmtData.User is null) - && !(mgmtData.CredentialId is null) - && !(mgmtData.CredentialPublicKey is null) - && !(mgmtData.CredProtectPolicy is null)) + if (!(credentialManagementData.TotalCredentialsForRelyingParty is null) + && !(credentialManagementData.User is null) + && !(credentialManagementData.CredentialId is null) + && !(credentialManagementData.CredentialPublicKey is null) + && !(credentialManagementData.CredProtectPolicy is null)) { var userInfo = new CredentialUserInfo( - mgmtData.User, - mgmtData.CredentialId, - mgmtData.CredentialPublicKey, - mgmtData.CredProtectPolicy.Value, - mgmtData.LargeBlobKey); + credentialManagementData.User, + credentialManagementData.CredentialId, + credentialManagementData.CredentialPublicKey, + credentialManagementData.CredProtectPolicy.Value, + credentialManagementData.LargeBlobKey); - return (mgmtData.TotalCredentialsForRelyingParty.Value, userInfo); + return (credentialManagementData.TotalCredentialsForRelyingParty.Value, userInfo); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsGetNextResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsGetNextResponse.cs index 2200d478..71a24621 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsGetNextResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateCredentialsGetNextResponse.cs @@ -42,19 +42,19 @@ public EnumerateCredentialsGetNextResponse(ResponseApdu responseApdu) /// public CredentialUserInfo GetData() { - CredentialManagementData mgmtData = _response.GetData(); + var credentialManagementData = _response.GetData(); - if (!(mgmtData.User is null) - && !(mgmtData.CredentialId is null) - && !(mgmtData.CredentialPublicKey is null) - && !(mgmtData.CredProtectPolicy is null)) + if (!(credentialManagementData.User is null) + && !(credentialManagementData.CredentialId is null) + && !(credentialManagementData.CredentialPublicKey is null) + && !(credentialManagementData.CredProtectPolicy is null)) { return new CredentialUserInfo( - mgmtData.User, - mgmtData.CredentialId, - mgmtData.CredentialPublicKey, - mgmtData.CredProtectPolicy.Value, - mgmtData.LargeBlobKey); + credentialManagementData.User, + credentialManagementData.CredentialId, + credentialManagementData.CredentialPublicKey, + credentialManagementData.CredProtectPolicy.Value, + credentialManagementData.LargeBlobKey); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs index 0cb83ab1..006ca2dc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsBeginResponse.cs @@ -70,15 +70,15 @@ public EnumerateRpsBeginResponse(ResponseApdu responseApdu) /// public (int totalRelyingPartyCount, RelyingParty relyingParty) GetData() { - CredentialManagementData mgmtData = _response.GetData(); + var credentialManagementData = _response.GetData(); - if (!(mgmtData.RelyingParty is null) - && !(mgmtData.RelyingPartyIdHash is null) - && !(mgmtData.TotalRelyingPartyCount is null)) + if (!(credentialManagementData.RelyingParty is null) + && !(credentialManagementData.RelyingPartyIdHash is null) + && !(credentialManagementData.TotalRelyingPartyCount is null)) { - if (mgmtData.RelyingParty.IsMatchingRelyingPartyId(mgmtData.RelyingPartyIdHash.Value)) + if (credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) { - return (mgmtData.TotalRelyingPartyCount.Value, mgmtData.RelyingParty); + return (credentialManagementData.TotalRelyingPartyCount.Value, credentialManagementData.RelyingParty); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs index 6aaf9a0a..aa2d8d21 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/EnumerateRpsGetNextResponse.cs @@ -42,14 +42,13 @@ public EnumerateRpsGetNextResponse(ResponseApdu responseApdu) /// public RelyingParty GetData() { - CredentialManagementData mgmtData = _response.GetData(); - - if (!(mgmtData.RelyingParty is null) - && !(mgmtData.RelyingPartyIdHash is null)) + var credentialManagementData = _response.GetData(); + if (!(credentialManagementData.RelyingParty is null) && + !(credentialManagementData.RelyingPartyIdHash is null)) { - if (mgmtData.RelyingParty.IsMatchingRelyingPartyId(mgmtData.RelyingPartyIdHash.Value)) + if (credentialManagementData.RelyingParty.IsMatchingRelyingPartyId(credentialManagementData.RelyingPartyIdHash.Value)) { - return mgmtData.RelyingParty; + return credentialManagementData.RelyingParty; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetBioModalityResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetBioModalityResponse.cs index 66e1c26e..9e18bf05 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetBioModalityResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetBioModalityResponse.cs @@ -47,11 +47,10 @@ public GetBioModalityResponse(ResponseApdu responseApdu) /// public int GetData() { - BioEnrollmentData enrollData = _response.GetData(); - - if (!(enrollData.Modality is null)) + var bioEnrollmentData = _response.GetData(); + if (!(bioEnrollmentData.Modality is null)) { - return enrollData.Modality.Value; + return bioEnrollmentData.Modality.Value; } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetCredentialMetadataResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetCredentialMetadataResponse.cs index 82cff66b..bc5655da 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetCredentialMetadataResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetCredentialMetadataResponse.cs @@ -57,11 +57,11 @@ public GetCredentialMetadataResponse(ResponseApdu responseApdu) /// public (int discoverableCredentialCount, int remainingCredentialCount) GetData() { - CredentialManagementData mgmtData = _response.GetData(); - - if (!(mgmtData.NumberOfDiscoverableCredentials is null) && !(mgmtData.RemainingCredentialCount is null)) + var credentialManagementData = _response.GetData(); + if (!(credentialManagementData.NumberOfDiscoverableCredentials is null) && + !(credentialManagementData.RemainingCredentialCount is null)) { - return (mgmtData.NumberOfDiscoverableCredentials.Value, mgmtData.RemainingCredentialCount.Value); + return (credentialManagementData.NumberOfDiscoverableCredentials.Value, credentialManagementData.RemainingCredentialCount.Value); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoResponse.cs index ba2b5d40..71dee548 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetFingerprintSensorInfoResponse.cs @@ -42,16 +42,16 @@ public GetFingerprintSensorInfoResponse(ResponseApdu responseApdu) /// public FingerprintSensorInfo GetData() { - BioEnrollmentData enrollData = _response.GetData(); + var bioEnrollmentData = _response.GetData(); - if (!(enrollData.FingerprintKind is null) - && !(enrollData.MaxCaptureCount is null) - && !(enrollData.MaxFriendlyNameBytes is null)) + if (!(bioEnrollmentData.FingerprintKind is null) && + !(bioEnrollmentData.MaxCaptureCount is null) && + !(bioEnrollmentData.MaxFriendlyNameBytes is null)) { return new FingerprintSensorInfo( - enrollData.FingerprintKind.Value, - enrollData.MaxCaptureCount.Value, - enrollData.MaxFriendlyNameBytes.Value); + bioEnrollmentData.FingerprintKind.Value, + bioEnrollmentData.MaxCaptureCount.Value, + bioEnrollmentData.MaxFriendlyNameBytes.Value); } throw new Ctap2DataException(ExceptionMessages.InvalidFido2Info); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetKeyAgreementResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetKeyAgreementResponse.cs index 9a7c4b68..6fc0bddc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetKeyAgreementResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetKeyAgreementResponse.cs @@ -49,9 +49,8 @@ public GetKeyAgreementResponse(ResponseApdu responseApdu) : base(responseApdu) /// public CoseEcPublicKey GetData() { - ClientPinData data = _response.GetData(); - - if (data.KeyAgreement is CoseEcPublicKey ecPublicKey) + var clientPinData = _response.GetData(); + if (clientPinData.KeyAgreement is CoseEcPublicKey ecPublicKey) { return ecPublicKey; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinRetriesResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinRetriesResponse.cs index 59ee4a90..96ad2c2c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinRetriesResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinRetriesResponse.cs @@ -53,14 +53,13 @@ public GetPinRetriesResponse(ResponseApdu responseApdu) : base(responseApdu) /// public (int retriesRemaining, bool? powerCycleRequired) GetData() { - ClientPinData data = _response.GetData(); - - if (data.PinRetries is null) + var clientPinData = _response.GetData(); + if (clientPinData.PinRetries is null) { throw new Ctap2DataException(ExceptionMessages.Ctap2MissingRequiredField); } - return (data.PinRetries.Value, data.PowerCycleState); + return (clientPinData.PinRetries.Value, clientPinData.PowerCycleState); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs index 7562cdc7..fc423494 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinTokenCommand.cs @@ -92,6 +92,7 @@ public GetPinTokenCommand(PinUvAuthProtocolBase pinProtocol, ReadOnlyMemory MaximumPinLength) { throw new ArgumentException( @@ -107,7 +109,7 @@ public GetPinTokenCommand(PinUvAuthProtocolBase pinProtocol, ReadOnlyMemory public ReadOnlyMemory GetData() { - ClientPinData data = _response.GetData(); - - if (data.PinUvAuthToken is null) + var clientPinData = _response.GetData(); + if (clientPinData.PinUvAuthToken is null) { throw new Ctap2DataException( string.Format( @@ -66,7 +65,7 @@ public ReadOnlyMemory GetData() ExceptionMessages.Ctap2MissingRequiredField)); } - return (ReadOnlyMemory)data.PinUvAuthToken; + return (ReadOnlyMemory)clientPinData.PinUvAuthToken; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs index 4db4bc8b..d3f25777 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetPinUvAuthTokenUsingPinCommand.cs @@ -137,7 +137,7 @@ public GetPinUvAuthTokenUsingPinCommand( ExceptionMessages.InvalidFido2Pin)); } - using SHA256 sha256Object = CryptographyProviders.Sha256Creator(); + using var sha256Object = CryptographyProviders.Sha256Creator(); byte[] pin = currentPin.ToArray(); byte[] digest = sha256Object.ComputeHash(pin); CryptographicOperations.ZeroMemory(pin); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetUvRetriesResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetUvRetriesResponse.cs index 165717d4..f1ccba00 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetUvRetriesResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/GetUvRetriesResponse.cs @@ -61,14 +61,13 @@ public GetUvRetriesResponse(ResponseApdu responseApdu) : base(responseApdu) /// public int GetData() { - ClientPinData data = _response.GetData(); - - if (data.UvRetries is null) + var clientPinData = _response.GetData(); + if (clientPinData.UvRetries is null) { throw new Ctap2DataException(ExceptionMessages.Ctap2MissingRequiredField); } - return data.UvRetries.Value; + return clientPinData.UvRetries.Value; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/VersionResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/VersionResponse.cs index db37e98f..52929c02 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/VersionResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Commands/VersionResponse.cs @@ -51,13 +51,13 @@ public FirmwareVersion GetData() throw new MalformedYubiKeyResponseException(ExceptionMessages.UnknownFidoError); } - ReadOnlySpan responseApduData = ResponseApdu.Data.Span; + var responseApduDataSpan = ResponseApdu.Data.Span; - return new FirmwareVersion() + return new FirmwareVersion { - Major = responseApduData[13], - Minor = responseApduData[14], - Patch = responseApduData[15] + Major = responseApduDataSpan[13], + Minor = responseApduDataSpan[14], + Patch = responseApduDataSpan[15] }; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs index c34bd408..7053c879 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/CredentialId.cs @@ -151,8 +151,8 @@ public CredentialId(ReadOnlyMemory encodedCredentialId, out int bytesRead) Id = cborMap.ReadByteString(TagId); if (cborMap.Contains(TagTransports)) { - IReadOnlyList transportArray = cborMap.ReadArray(TagTransports); - foreach (string entry in transportArray) + var transports = cborMap.ReadArray(TagTransports); + foreach (string entry in transports) { AddTransport(entry); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs index c609fe04..2692abc8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.BioEnrollment.cs @@ -44,8 +44,8 @@ public BioModality GetBioModality() _log.LogInformation("Get BioModality."); var cmd = new GetBioModalityCommand(); - GetBioModalityResponse rsp = Connection.SendCommand(cmd); - int modality = rsp.Status == ResponseStatus.Success ? rsp.GetData() : 0; + var response = Connection.SendCommand(cmd); + int modality = response.Status == ResponseStatus.Success ? response.GetData() : 0; return modality switch { @@ -76,7 +76,7 @@ public FingerprintSensorInfo GetFingerprintSensorInfo() _log.LogInformation("Get fingerprint sensor info."); var cmd = new GetFingerprintSensorInfoCommand(); - GetFingerprintSensorInfoResponse rsp = Connection.SendCommand(cmd); + var rsp = Connection.SendCommand(cmd); return rsp.Status == ResponseStatus.Success ? rsp.GetData() : throw new NotSupportedException(ExceptionMessages.NotSupportedByYubiKeyVersion); } @@ -98,9 +98,9 @@ public FingerprintSensorInfo GetFingerprintSensorInfo() /// public IReadOnlyList EnumerateBioEnrollments() { - ReadOnlyMemory currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); + var currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); var enumCmd = new BioEnrollEnumerateCommand(currentToken, AuthProtocol); - BioEnrollEnumerateResponse enumRsp = Connection.SendCommand(enumCmd); + var enumRsp = Connection.SendCommand(enumCmd); if (enumRsp.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); @@ -231,7 +231,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec { _log.LogInformation("Try to enroll a fingerprint."); - Func keyCollector = EnsureKeyCollector(); + var keyCollector = EnsureKeyCollector(); // Enumerate the current templates to see if there is a matching // friendly name. If there is, we won't set the new template's name @@ -245,9 +245,9 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec // Incidentally, enumerating will add some time to this method, but // the process of enrolling a fingerprint is so time consuming // already, a few milliseconds won't matter. - ReadOnlyMemory currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); + var currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); var enumCmd = new BioEnrollEnumerateCommand(currentToken, AuthProtocol); - BioEnrollEnumerateResponse enumRsp = Connection.SendCommand(enumCmd); + var enumRsp = Connection.SendCommand(enumCmd); if (enumRsp.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); @@ -257,13 +257,13 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec // If there was an error other than PinAuthInvalid, this call will // throw an exception. - IReadOnlyList templateList = enumRsp.GetData(); + var templateList = enumRsp.GetData(); string returnName = ""; if (!string.IsNullOrEmpty(friendlyName)) { returnName = friendlyName!; - foreach (TemplateInfo templateInfo in templateList) + foreach (var templateInfo in templateList) { if (returnName!.Equals(templateInfo.FriendlyName, StringComparison.Ordinal)) { @@ -275,7 +275,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec CtapStatus status; string generalErrorMsg = ExceptionMessages.UnknownFido2Status; - ReadOnlyMemory templateId = ReadOnlyMemory.Empty; + var templateId = ReadOnlyMemory.Empty; var keyEntryData = new KeyEntryData() { @@ -291,14 +291,14 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec try { var beginCmd = new BioEnrollBeginCommand(timeoutMilliseconds, currentToken, AuthProtocol); - BioEnrollBeginResponse beginRsp = Connection.SendCommand(beginCmd); + var beginRsp = Connection.SendCommand(beginCmd); var currentRsp = (IYubiKeyResponseWithData)beginRsp; status = fingerprintTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : beginRsp.CtapStatus; generalErrorMsg = beginRsp.StatusMessage; while (status == CtapStatus.Ok) { - BioEnrollSampleResult enrollResult = currentRsp.GetData(); + var enrollResult = currentRsp.GetData(); if (enrollResult.RemainingSampleCount <= 0) { templateId = enrollResult.TemplateId; @@ -312,7 +312,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec timeoutMilliseconds, currentToken, AuthProtocol); - BioEnrollNextSampleResponse nextRsp = Connection.SendCommand(nextCmd); + var nextRsp = Connection.SendCommand(nextCmd); currentRsp = (IYubiKeyResponseWithData)nextRsp; status = fingerprintTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : nextRsp.CtapStatus; generalErrorMsg = nextRsp.StatusMessage; @@ -321,7 +321,7 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec if (status == CtapStatus.Ok && !string.IsNullOrEmpty(returnName)) { var nameCmd = new BioEnrollSetFriendlyNameCommand(templateId, returnName, currentToken, AuthProtocol); - Fido2Response nameRsp = Connection.SendCommand(nameCmd); + var nameRsp = Connection.SendCommand(nameCmd); if (nameRsp.Status != ResponseStatus.Success) { @@ -390,9 +390,9 @@ public TemplateInfo EnrollFingerprint(string? friendlyName, int? timeoutMillisec /// public void SetBioTemplateFriendlyName(ReadOnlyMemory templateId, string friendlyName) { - ReadOnlyMemory currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); + var currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); var nameCmd = new BioEnrollSetFriendlyNameCommand(templateId, friendlyName, currentToken, AuthProtocol); - Fido2Response nameRsp = Connection.SendCommand(nameCmd); + var nameRsp = Connection.SendCommand(nameCmd); if (nameRsp.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); @@ -420,9 +420,9 @@ public void SetBioTemplateFriendlyName(ReadOnlyMemory templateId, string f /// public bool TryRemoveBioTemplate(ReadOnlyMemory templateId) { - ReadOnlyMemory currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); + var currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); var removeCmd = new BioEnrollRemoveCommand(templateId, currentToken, AuthProtocol); - Fido2Response removeRsp = Connection.SendCommand(removeCmd); + var removeRsp = Connection.SendCommand(removeCmd); if (removeRsp.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(false, PinUvAuthTokenPermissions.BioEnrollment, null); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs index 43f9c48b..64653d2c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Config.cs @@ -72,7 +72,7 @@ public bool TryEnableEnterpriseAttestation() { _log.LogInformation("Try to EnableEnterpriseAttestation."); - OptionValue epValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.ep); + var epValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.ep); if (epValue == OptionValue.True) { @@ -84,21 +84,21 @@ public bool TryEnableEnterpriseAttestation() return false; } - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); - var enableCmd = new EnableEnterpriseAttestationCommand(currentToken, AuthProtocol); - Fido2Response enableRsp = Connection.SendCommand(enableCmd); - if (enableRsp.CtapStatus == CtapStatus.PinAuthInvalid) + var command = new EnableEnterpriseAttestationCommand(currentToken, AuthProtocol); + var response = Connection.SendCommand(command); + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); - enableCmd = new EnableEnterpriseAttestationCommand(currentToken, AuthProtocol); - enableRsp = Connection.SendCommand(enableCmd); + command = new EnableEnterpriseAttestationCommand(currentToken, AuthProtocol); + response = Connection.SendCommand(command); } - if (enableRsp.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { // This operation can change the AuthenticatorInfo, so make sure // if someone gets it, they get a new one. @@ -106,7 +106,7 @@ public bool TryEnableEnterpriseAttestation() return true; } - throw new Ctap2DataException(enableRsp.StatusMessage); + throw new Ctap2DataException(response.StatusMessage); } /// @@ -164,27 +164,27 @@ public bool TryToggleAlwaysUv() { _log.LogInformation("Try to ToggleAlwaysUv."); - OptionValue alwaysUvValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.alwaysUv); + var alwaysUvValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.alwaysUv); if (alwaysUvValue != OptionValue.True && alwaysUvValue != OptionValue.False) { return false; } - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); - var toggleCmd = new ToggleAlwaysUvCommand(currentToken, AuthProtocol); - Fido2Response toggleRsp = Connection.SendCommand(toggleCmd); - if (toggleRsp.CtapStatus == CtapStatus.PinAuthInvalid) + var command = new ToggleAlwaysUvCommand(currentToken, AuthProtocol); + var response = Connection.SendCommand(command); + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); - toggleCmd = new ToggleAlwaysUvCommand(currentToken, AuthProtocol); - toggleRsp = Connection.SendCommand(toggleCmd); + command = new ToggleAlwaysUvCommand(currentToken, AuthProtocol); + response = Connection.SendCommand(command); } - if (toggleRsp.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { // This operation can change the AuthenticatorInfo, so make sure // if someone gets it, they get a new one. @@ -192,7 +192,7 @@ public bool TryToggleAlwaysUv() return true; } - throw new Ctap2DataException(toggleRsp.StatusMessage); + throw new Ctap2DataException(response.StatusMessage); } /// @@ -324,14 +324,14 @@ public bool TrySetPinConfig( { _log.LogInformation("Try to set the PIN config (setMinPINLength)."); - OptionValue setMinPinValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.setMinPINLength); + var setMinPinValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.setMinPINLength); if (setMinPinValue != OptionValue.True) { return false; } - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); @@ -342,7 +342,7 @@ public bool TrySetPinConfig( forceChangePin, currentToken, AuthProtocol); - Fido2Response setRsp = Connection.SendCommand(setCmd); + var setRsp = Connection.SendCommand(setCmd); if (setRsp.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.AuthenticatorConfiguration, null); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs index d683ea51..bc9189b8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.CredMgmt.cs @@ -86,19 +86,20 @@ public sealed partial class Fido2Session bool isPreview = CredMgmtGetIsPreview(); - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.CredentialManagement, null); - var cmd = new GetCredentialMetadataCommand(currentToken, AuthProtocol) + var command = new GetCredentialMetadataCommand(currentToken, AuthProtocol) { IsPreview = isPreview }; - GetCredentialMetadataResponse rsp = Connection.SendCommand(cmd); + + var response = Connection.SendCommand(command); // If the error is PinAuthInvalid, try again. // If the result is not PinAuthInvalid, we know we're not going // to try again, error or no error. - if (rsp.CtapStatus == CtapStatus.PinAuthInvalid) + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { // Get Metadata is an odd one. The standard says that the RpId is // optional with CredentialManagement. Except the standard also @@ -114,18 +115,18 @@ public sealed partial class Fido2Session // to save (and then restore) the AuthTokenPermissions as well. // Note that this method adds "cm", so make sure the original // restored includes this. - PinUvAuthTokenPermissions? savePermissions = AuthTokenPermissions; + var savePermissions = AuthTokenPermissions; string? saveRpId = AuthTokenRelyingPartyId; AuthTokenPermissions = null; AuthTokenRelyingPartyId = null; try { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.CredentialManagement, null); - cmd = new GetCredentialMetadataCommand(currentToken, AuthProtocol) + command = new GetCredentialMetadataCommand(currentToken, AuthProtocol) { IsPreview = isPreview }; - rsp = Connection.SendCommand(cmd); + response = Connection.SendCommand(command); } finally { @@ -137,7 +138,7 @@ public sealed partial class Fido2Session // This will return the data or throw an exception. We either have // the data, have an error other than PinAuthInvalid, or we do have // the error PinAuthInvalid but only after trying twice. - return rsp.GetData(); + return response.GetData(); } /// @@ -180,19 +181,19 @@ public IReadOnlyList EnumerateRelyingParties() bool isPreview = CredMgmtGetIsPreview(); - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.CredentialManagement, null); - var cmd = new EnumerateRpsBeginCommand(currentToken, AuthProtocol) + var command = new EnumerateRpsBeginCommand(currentToken, AuthProtocol) { IsPreview = isPreview }; - EnumerateRpsBeginResponse rsp = Connection.SendCommand(cmd); + var response = Connection.SendCommand(command); // If the error is PinAuthInvalid, try again. // If the result is not PinAuthInvalid, we know we're not going // to try again, error or no error. - if (rsp.CtapStatus == CtapStatus.PinAuthInvalid) + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { // EnumerateRPs is an odd one. The standard says that the // RpId is optional with CredentialManagement. Except the @@ -209,18 +210,18 @@ public IReadOnlyList EnumerateRelyingParties() // AuthTokenPermissions as well. // Note that this method adds "cm", so make sure the original // restored includes this. - PinUvAuthTokenPermissions? savePermissions = AuthTokenPermissions; + var savePermissions = AuthTokenPermissions; string? saveRpId = AuthTokenRelyingPartyId; AuthTokenPermissions = null; AuthTokenRelyingPartyId = null; try { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.CredentialManagement, null); - cmd = new EnumerateRpsBeginCommand(currentToken, AuthProtocol) + command = new EnumerateRpsBeginCommand(currentToken, AuthProtocol) { IsPreview = isPreview }; - rsp = Connection.SendCommand(cmd); + response = Connection.SendCommand(command); } finally { @@ -230,7 +231,7 @@ public IReadOnlyList EnumerateRelyingParties() } // If the response is NoCredentials, return an empty list. - if (rsp.CtapStatus == CtapStatus.NoCredentials) + if (response.CtapStatus == CtapStatus.NoCredentials) { return new List(); } @@ -238,7 +239,7 @@ public IReadOnlyList EnumerateRelyingParties() // This will return the data or throw an exception. We either have // the data, have an error other than PinAuthInvalid, or we do have // the error PinAuthInvalid but only after trying twice. - (int rpCount, RelyingParty firstRp) = rsp.GetData(); + (int rpCount, var firstRp) = response.GetData(); var returnValue = new List(rpCount) { @@ -253,8 +254,8 @@ public IReadOnlyList EnumerateRelyingParties() }; for (int index = 1; index < rpCount; index++) { - EnumerateRpsGetNextResponse nextRsp = Connection.SendCommand(nextCmd); - returnValue.Add(nextRsp.GetData()); + var nextResponse = Connection.SendCommand(nextCmd); + returnValue.Add(nextResponse.GetData()); } return returnValue; @@ -313,24 +314,24 @@ public IReadOnlyList EnumerateCredentialsForRelyingParty(Rel _log.LogInformation("Enumerate credentials for relying party: " + relyingParty.Id + "."); - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.CredentialManagement, relyingParty.Id); - using SHA256 digester = CryptographyProviders.Sha256Creator(); + using var digester = CryptographyProviders.Sha256Creator(); digester.Initialize(); byte[] utf = Encoding.UTF8.GetBytes(relyingParty.Id); byte[] digest = digester.ComputeHash(utf); - var cmd = new EnumerateCredentialsBeginCommand(relyingParty, currentToken, AuthProtocol) + var command = new EnumerateCredentialsBeginCommand(relyingParty, currentToken, AuthProtocol) { IsPreview = isPreview }; - EnumerateCredentialsBeginResponse rsp = Connection.SendCommand(cmd); + var response = Connection.SendCommand(command); // If the error is PinAuthInvalid, try again. // If the result is not PinAuthInvalid, we know we're not going // to try again, error or no error. - if (rsp.CtapStatus == CtapStatus.PinAuthInvalid) + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { // In order to enumerate the credentials, we need the relying // party. The standard specifies the RpIdHash as the way to @@ -346,15 +347,15 @@ public IReadOnlyList EnumerateCredentialsForRelyingParty(Rel AuthTokenRelyingPartyId = relyingParty.Id; } currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.CredentialManagement, null); - cmd = new EnumerateCredentialsBeginCommand(relyingParty, currentToken, AuthProtocol) + command = new EnumerateCredentialsBeginCommand(relyingParty, currentToken, AuthProtocol) { IsPreview = isPreview }; - rsp = Connection.SendCommand(cmd); + response = Connection.SendCommand(command); } // If the response is NoCredentials, return an empty list. - if (rsp.CtapStatus == CtapStatus.NoCredentials) + if (response.CtapStatus == CtapStatus.NoCredentials) { return new List(); } @@ -362,7 +363,7 @@ public IReadOnlyList EnumerateCredentialsForRelyingParty(Rel // This will return the data or throw an exception. We either have // the data, have an error other than PinAuthInvalid, or we do have // the error PinAuthInvalid but only after trying twice. - (int credCount, CredentialUserInfo userInfo) = rsp.GetData(); + (int credCount, var userInfo) = response.GetData(); var returnValue = new List(credCount) { @@ -377,8 +378,8 @@ public IReadOnlyList EnumerateCredentialsForRelyingParty(Rel }; for (int index = 1; index < credCount; index++) { - EnumerateCredentialsGetNextResponse nextRsp = Connection.SendCommand(nextCmd); - returnValue.Add(nextRsp.GetData()); + var nextResponse = Connection.SendCommand(nextCmd); + returnValue.Add(nextResponse.GetData()); } return returnValue; @@ -419,30 +420,30 @@ public void DeleteCredential(CredentialId credentialId) bool isPreview = CredMgmtGetIsPreview(); - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.CredentialManagement, null); - var cmd = new DeleteCredentialCommand(credentialId, currentToken, AuthProtocol) + var command = new DeleteCredentialCommand(credentialId, currentToken, AuthProtocol) { IsPreview = isPreview }; - Fido2Response rsp = Connection.SendCommand(cmd); + var response = Connection.SendCommand(command); // If the error is PinAuthInvalid, try again. // If the result is not PinAuthInvalid, we know we're not going // to try again, error or no error. - if (rsp.CtapStatus == CtapStatus.PinAuthInvalid) + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.CredentialManagement, null); - cmd = new DeleteCredentialCommand(credentialId, currentToken, AuthProtocol) + command = new DeleteCredentialCommand(credentialId, currentToken, AuthProtocol) { IsPreview = isPreview }; - rsp = Connection.SendCommand(cmd); + response = Connection.SendCommand(command); } // If the response is Success, we're done. - if (rsp.Status == ResponseStatus.Success || rsp.CtapStatus == CtapStatus.NoCredentials) + if (response.Status == ResponseStatus.Success || response.CtapStatus == CtapStatus.NoCredentials) { // After a credential has been deleted, the number of // discoverable credentials can change. Hence, this operation can @@ -453,7 +454,7 @@ public void DeleteCredential(CredentialId credentialId) } // If the response is not Success, throw an exception. - throw new Fido2Exception(rsp.StatusMessage); + throw new Fido2Exception(response.StatusMessage); } /// @@ -501,30 +502,30 @@ public void UpdateUserInfoForCredential(CredentialId credentialId, UserEntity ne { _log.LogInformation("Update user information."); - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( false, PinUvAuthTokenPermissions.CredentialManagement, null); - var cmd = new UpdateUserInfoCommand(credentialId, newUserInfo, currentToken, AuthProtocol); - Fido2Response rsp = Connection.SendCommand(cmd); + var command = new UpdateUserInfoCommand(credentialId, newUserInfo, currentToken, AuthProtocol); + var response = Connection.SendCommand(command); // If the error is PinAuthInvalid, try again. // If the result is not PinAuthInvalid, we know we're not going // to try again, error or no error. - if (rsp.CtapStatus == CtapStatus.PinAuthInvalid) + if (response.CtapStatus == CtapStatus.PinAuthInvalid) { currentToken = GetAuthToken(true, PinUvAuthTokenPermissions.CredentialManagement, null); - cmd = new UpdateUserInfoCommand(credentialId, newUserInfo, currentToken, AuthProtocol); - rsp = Connection.SendCommand(cmd); + command = new UpdateUserInfoCommand(credentialId, newUserInfo, currentToken, AuthProtocol); + response = Connection.SendCommand(command); } // If the response is Success, we're done. - if (rsp.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { return; } // If the response is not Success, throw an exception. - throw new Fido2Exception(rsp.StatusMessage); + throw new Fido2Exception(response.StatusMessage); } // Determine if the YubiKey supports "credMgmt or "CredentialMgmtPreview". @@ -533,7 +534,7 @@ public void UpdateUserInfoForCredential(CredentialId credentialId, UserEntity ne // If it supports neither, throw an exception. private bool CredMgmtGetIsPreview() { - OptionValue cmValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.credMgmt); + var cmValue = AuthenticatorInfo.GetOptionValue(AuthenticatorOptions.credMgmt); if (cmValue == OptionValue.True) { return false; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs index 0f1b4615..6fa063fb 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.GetAssertion.cs @@ -98,7 +98,8 @@ public IReadOnlyList GetAssertions(GetAssertionParameters para { throw new ArgumentNullException(nameof(parameters)); } - Func keyCollector = EnsureKeyCollector(); + + var keyCollector = EnsureKeyCollector(); byte[] token = new byte[MaximumAuthTokenLength]; byte[] clientDataHash = parameters.ClientDataHash.ToArray(); @@ -109,7 +110,7 @@ public IReadOnlyList GetAssertions(GetAssertionParameters para { // The first time through, forceToken will be false. // If there is a second time, it will be true. - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( forceToken, PinUvAuthTokenPermissions.GetAssertion, parameters.RelyingParty.Id); try @@ -128,12 +129,12 @@ public IReadOnlyList GetAssertions(GetAssertionParameters para // do nothing. parameters.EncodeHmacSecretExtension(AuthProtocol); - GetAssertionResponse rsp = RunGetAssertion(parameters, keyCollector, out CtapStatus ctapStatus); + var response = RunGetAssertion(parameters, keyCollector, out var ctapStatus); switch (ctapStatus) { case CtapStatus.Ok: - return CompleteGetAssertions(rsp.GetData()); + return CompleteGetAssertions(response.GetData()); case CtapStatus.PinAuthInvalid: // If forceToken is false (its initial value), this @@ -163,7 +164,7 @@ public IReadOnlyList GetAssertions(GetAssertionParameters para break; } - message = rsp.StatusMessage; + message = response.StatusMessage; } while (forceToken); throw new Fido2Exception(message); @@ -186,9 +187,9 @@ private GetAssertionResponse RunGetAssertion( try { - GetAssertionResponse rsp = Connection.SendCommand(new GetAssertionCommand(parameters)); - ctapStatus = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : rsp.CtapStatus; - return rsp; + var response = Connection.SendCommand(new GetAssertionCommand(parameters)); + ctapStatus = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : response.CtapStatus; + return response; } finally { @@ -205,7 +206,7 @@ private IReadOnlyList CompleteGetAssertions(GetAssertionData g for (int index = 1; index < numberOfCredentials; index++) { - GetAssertionResponse response = Connection.SendCommand(new GetNextAssertionCommand()); + var response = Connection.SendCommand(new GetNextAssertionCommand()); assertions.Add(response.GetData()); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs index c0902613..23fae17a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.LargeBlobs.cs @@ -125,7 +125,7 @@ public SerializedLargeBlobArray GetSerializedLargeBlobArray() do { var command = new GetLargeBlobCommand(offset, maxFragmentLength); - GetLargeBlobResponse response = Connection.SendCommand(command); + var response = Connection.SendCommand(command); currentData = response.GetData(); fullEncoding.Write(currentData.ToArray(), 0, currentData.Length); @@ -143,7 +143,7 @@ public SerializedLargeBlobArray GetSerializedLargeBlobArray() // 01 byte string var cborMap = new CborMap( fullEncoding.GetBuffer().AsMemory(0, (int)fullEncoding.Length)); - ReadOnlyMemory encodedArray = cborMap.ReadByteString(KeyEncodedArray); + var encodedArray = cborMap.ReadByteString(KeyEncodedArray); var returnValue = new SerializedLargeBlobArray(encodedArray); @@ -242,7 +242,7 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge do { - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( forceToken, PinUvAuthTokenPermissions.LargeBlobWrite, null); currentToken.CopyTo(token.AsMemory()); @@ -257,7 +257,8 @@ public void SetSerializedLargeBlobArray(SerializedLargeBlobArray serializedLarge encodedArray.Length, pinUvAuthParam, (int)AuthProtocol.Protocol); - SetLargeBlobResponse response = Connection.SendCommand(command); + + var response = Connection.SendCommand(command); if (response.Status == ResponseStatus.Success) { remaining -= currentLength; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs index 4e041d8c..ea849437 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.MakeCredential.cs @@ -92,18 +92,19 @@ public MakeCredentialData MakeCredential(MakeCredentialParameters parameters) { throw new ArgumentNullException(nameof(parameters)); } - Func keyCollector = EnsureKeyCollector(); + + var keyCollector = EnsureKeyCollector(); byte[] token = new byte[MaximumAuthTokenLength]; byte[] clientDataHash = parameters.ClientDataHash.ToArray(); bool forceToken = false; - string message = ""; + string message; do { // The first time through, forceToken will be false. // If there is a second time, it will be true. - ReadOnlyMemory currentToken = GetAuthToken( + var currentToken = GetAuthToken( forceToken, PinUvAuthTokenPermissions.MakeCredential, parameters.RelyingParty.Id); try @@ -118,7 +119,7 @@ public MakeCredentialData MakeCredential(MakeCredentialParameters parameters) CryptographicOperations.ZeroMemory(token); } - MakeCredentialResponse rsp = RunMakeCredential(parameters, keyCollector, out CtapStatus ctapStatus); + var response = RunMakeCredential(parameters, keyCollector, out var ctapStatus); switch (ctapStatus) { @@ -128,7 +129,7 @@ public MakeCredentialData MakeCredential(MakeCredentialParameters parameters) // operation can change the AuthenticatorInfo, so make // sure if someone gets it, they get a new one. _authenticatorInfo = null; - return rsp.GetData(); + return response.GetData(); case CtapStatus.PinAuthInvalid: // If forceToken is false (its initial value), this @@ -155,7 +156,7 @@ public MakeCredentialData MakeCredential(MakeCredentialParameters parameters) break; } - message = rsp.StatusMessage; + message = response.StatusMessage; } while (forceToken); throw new Fido2Exception(message); @@ -178,9 +179,10 @@ private MakeCredentialResponse RunMakeCredential( try { - MakeCredentialResponse rsp = Connection.SendCommand(new MakeCredentialCommand(parameters)); - ctapStatus = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : rsp.CtapStatus; - return rsp; + var response = Connection.SendCommand(new MakeCredentialCommand(parameters)); + ctapStatus = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : response.CtapStatus; + + return response; } finally { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs index c64f6df3..c7418e45 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.Pin.cs @@ -283,8 +283,8 @@ public void AddPermissions(PinUvAuthTokenPermissions permissions, string? relyin { _log.LogInformation("Add permissions (get new AuthToken with more permissions)."); - PinUvAuthTokenPermissions current = AuthTokenPermissions ?? PinUvAuthTokenPermissions.None; - PinUvAuthTokenPermissions allPermissions = permissions | current; + var currentPermissions = AuthTokenPermissions ?? PinUvAuthTokenPermissions.None; + var allPermissions = permissions | currentPermissions; // If the caller supplies an RpId, replace the one in the // AuthTokenRelyingPartyId property. @@ -513,9 +513,9 @@ public void SetPin() public bool TrySetPin() { _log.LogInformation("Try to set PIN (use KeyCollector)."); - Func keyCollector = EnsureKeyCollector(); - - var keyEntryData = new KeyEntryData() + + var keyCollector = EnsureKeyCollector(); + var keyEntryData = new KeyEntryData { Request = KeyEntryRequest.SetFido2Pin, }; @@ -584,9 +584,8 @@ public bool TrySetPin(ReadOnlyMemory newPin) ObtainSharedSecret(); - SetPinResponse result = Connection.SendCommand(new SetPinCommand(AuthProtocol, newPin)); - - if (result.Status == ResponseStatus.Success) + var response = Connection.SendCommand(new SetPinCommand(AuthProtocol, newPin)); + if (response.Status == ResponseStatus.Success) { // Setting the PIN changes the AuthenticatorInfo, so set this to // null so the next reference initiates a new GetInfo command. @@ -595,13 +594,13 @@ public bool TrySetPin(ReadOnlyMemory newPin) } // Spec says "PinAuthInvalid" for PIN already set. YubiKey says "NotAllowed". - if (GetCtapError(result) == CtapStatus.PinAuthInvalid || - GetCtapError(result) == CtapStatus.NotAllowed) + if (GetCtapError(response) == CtapStatus.PinAuthInvalid || + GetCtapError(response) == CtapStatus.NotAllowed) { return false; // PIN is already set. } - throw new Fido2Exception(GetCtapError(result), result.StatusMessage); + throw new Fido2Exception(GetCtapError(response), response.StatusMessage); } /// @@ -674,8 +673,8 @@ public void ChangePin() public bool TryChangePin() { _log.LogInformation("Try to change PIN (use KeyCollector)."); - Func keyCollector = EnsureKeyCollector(); - + + var keyCollector = EnsureKeyCollector(); var keyEntryData = new KeyEntryData() { Request = KeyEntryRequest.ChangeFido2Pin @@ -752,14 +751,13 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n ObtainSharedSecret(); - ChangePinResponse result = Connection.SendCommand(new ChangePinCommand(AuthProtocol, currentPin, newPin)); - - if (result.Status == ResponseStatus.Success) + var response = Connection.SendCommand(new ChangePinCommand(AuthProtocol, currentPin, newPin)); + if (response.Status == ResponseStatus.Success) { return true; } - if (GetCtapError(result) == CtapStatus.PinInvalid) + if (GetCtapError(response) == CtapStatus.PinInvalid) { // FIDO authenticators regenerate the public key used for the auth protocol. We need to // re-initialize everything so we can obtain the new shared secret. @@ -767,7 +765,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n return false; // PIN is invalid } - throw new Fido2Exception(GetCtapError(result), result.StatusMessage); + throw new Fido2Exception(GetCtapError(response), response.StatusMessage); } /// @@ -914,9 +912,9 @@ public void VerifyPin(PinUvAuthTokenPermissions? permissions = null, string? rel public bool TryVerifyPin(PinUvAuthTokenPermissions? permissions = null, string? relyingPartyId = null) { _log.LogInformation("Try to verify PIN (use KeyCollector)."); - Func keyCollector = EnsureKeyCollector(); - - var keyEntryData = new KeyEntryData() + + var keyCollector = EnsureKeyCollector(); + var keyEntryData = new KeyEntryData { Request = KeyEntryRequest.VerifyFido2Pin }; @@ -1056,8 +1054,7 @@ public bool TryVerifyPin( relyingPartyId); } - GetPinUvAuthTokenResponse response = Connection.SendCommand(command); - + var response = Connection.SendCommand(command); if (response.Status == ResponseStatus.Success) { AuthToken = response.GetData(); @@ -1211,9 +1208,9 @@ public void VerifyUv(PinUvAuthTokenPermissions permissions, string? relyingParty public bool TryVerifyUv(PinUvAuthTokenPermissions permissions, string? relyingPartyId = null) { _log.LogInformation("Try to verify UV (use KeyCollector)."); - CtapStatus status = DoVerifyUv(permissions, relyingPartyId, out string statusMessage); - - switch (status) + + var ctapStatus = DoVerifyUv(permissions, relyingPartyId, out string statusMessage); + switch (ctapStatus) { case CtapStatus.Ok: return true; @@ -1252,9 +1249,8 @@ private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? rel return CtapStatus.InvalidParameter; } - Func keyCollector = EnsureKeyCollector(); + var keyCollector = EnsureKeyCollector(); - CtapStatus status; ObtainSharedSecret(); var command = new GetPinUvAuthTokenUsingUvCommand(AuthProtocol, permissions, relyingPartyId); @@ -1270,12 +1266,13 @@ private CtapStatus DoVerifyUv(PinUvAuthTokenPermissions permissions, string? rel try { + CtapStatus status; do { - GetPinUvAuthTokenResponse response = Connection.SendCommand(command); - status = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : response.CtapStatus; + var response = Connection.SendCommand(command); + statusMessage = response.StatusMessage; - + status = touchTask.IsUserCanceled ? CtapStatus.KeepAliveCancel : response.CtapStatus; if (status == CtapStatus.Ok) { AuthToken = response.GetData(); @@ -1375,8 +1372,7 @@ private void VerifyPinLengthRequirements(ReadOnlyMemory newPin) private PinUvAuthProtocolBase GetPreferredPinProtocol() { - PinUvAuthProtocol protocol = AuthenticatorInfo.PinUvAuthProtocols?[0] ?? PinUvAuthProtocol.ProtocolOne; - + var protocol = AuthenticatorInfo.PinUvAuthProtocols?[0] ?? PinUvAuthProtocol.ProtocolOne; return protocol switch { PinUvAuthProtocol.ProtocolOne => new PinUvAuthProtocolOne(), @@ -1391,10 +1387,9 @@ private PinUvAuthProtocolBase GetPreferredPinProtocol() private CoseEcPublicKey GetPeerCoseKey() { - GetKeyAgreementResponse keyAgreementResponse = - Connection.SendCommand(new GetKeyAgreementCommand(AuthProtocol.Protocol)); - - CoseEcPublicKey peerCoseKey = keyAgreementResponse.GetData(); + var response = Connection.SendCommand(new GetKeyAgreementCommand(AuthProtocol.Protocol)); + var peerCoseKey = response.GetData(); + return peerCoseKey; } @@ -1403,7 +1398,7 @@ private void ObtainSharedSecret() if (AuthProtocol.PlatformPublicKey is null) { AuthProtocol.Initialize(); - CoseEcPublicKey peerCoseKey = GetPeerCoseKey(); + var peerCoseKey = GetPeerCoseKey(); AuthProtocol.Encapsulate(peerCoseKey); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.cs index 9209a7d9..3573b591 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/Fido2Session.cs @@ -215,8 +215,8 @@ public AuthenticatorInfo GetAuthenticatorInfo() // necessary to call the command. private AuthenticatorInfo SetAndReturnAuthenticatorInfoField() { - GetInfoResponse info = Connection.SendCommand(new GetInfoCommand()); - _authenticatorInfo = info.GetData(); + var response = Connection.SendCommand(new GetInfoCommand()); + _authenticatorInfo = response.GetData(); return _authenticatorInfo; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs index 601fe00d..bc196efa 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/GetAssertionData.cs @@ -130,32 +130,35 @@ public GetAssertionData(ReadOnlyMemory cborEncoding) try { var map = new CborMap(cborEncoding); + var stringCborMap = map.ReadMap(KeyCredential); - CborMap stringMap = map.ReadMap(KeyCredential); - CredentialId = new CredentialId() + CredentialId = new CredentialId { - Type = stringMap.ReadTextString(KeyCredentialType), - Id = stringMap.ReadByteString(KeyCredentialId), + Type = stringCborMap.ReadTextString(KeyCredentialType), + Id = stringCborMap.ReadByteString(KeyCredentialId), }; - if (stringMap.Contains(KeyCredentialTransports)) + + if (stringCborMap.Contains(KeyCredentialTransports)) { - IReadOnlyList transports = stringMap.ReadArray(KeyCredentialTransports); + var transports = stringCborMap.ReadArray(KeyCredentialTransports); foreach (string current in transports) { CredentialId.AddTransport(current); } } + AuthenticatorData = new AuthenticatorData(map.ReadByteString(KeyAuthData)); Signature = map.ReadByteString(KeySignature); if (map.Contains(KeyUser)) { - stringMap = map.ReadMap(KeyUser); - User = new UserEntity(stringMap.ReadByteString(KeyUserId)) + stringCborMap = map.ReadMap(KeyUser); + User = new UserEntity(stringCborMap.ReadByteString(KeyUserId)) { - Name = (string?)stringMap.ReadOptional(KeyUserName), - DisplayName = (string?)stringMap.ReadOptional(KeyUserDisplayName) + Name = (string?)stringCborMap.ReadOptional(KeyUserName), + DisplayName = (string?)stringCborMap.ReadOptional(KeyUserDisplayName) }; } + NumberOfCredentials = (int?)map.ReadOptional(KeyNumberCredentials); UserSelected = (bool?)map.ReadOptional(KeyUserSelected); _keyData = (byte[]?)map.ReadOptional(KeyLargeBlobKey); @@ -197,14 +200,15 @@ public GetAssertionData(ReadOnlyMemory cborEncoding) /// public bool VerifyAssertion(CoseKey publicKey, ReadOnlyMemory clientDataHash) { - using SHA256 digester = CryptographyProviders.Sha256Creator(); - _ = digester.TransformBlock( + using var digesterHashAlgorithm = CryptographyProviders.Sha256Creator(); + _ = digesterHashAlgorithm.TransformBlock( AuthenticatorData.EncodedAuthenticatorData.ToArray(), 0, AuthenticatorData.EncodedAuthenticatorData.Length, null, 0); - _ = digester.TransformFinalBlock(clientDataHash.ToArray(), 0, clientDataHash.Length); + + _ = digesterHashAlgorithm.TransformFinalBlock(clientDataHash.ToArray(), 0, clientDataHash.Length); using var ecdsaVfy = new EcdsaVerify(publicKey); - return ecdsaVfy.VerifyDigestedData(digester.Hash, Signature.ToArray()); + return ecdsaVfy.VerifyDigestedData(digesterHashAlgorithm.Hash, Signature.ToArray()); } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs index 36408160..2d55f0e4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/LargeBlobEntry.cs @@ -121,7 +121,7 @@ internal LargeBlobEntry(ReadOnlyMemory blobData, ReadOnlyMemory larg OriginalDataLength = blobData.Length; - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); byte[] nonce = new byte[NonceSize]; randomObject.GetBytes(nonce, 0, NonceSize); Nonce = new ReadOnlyMemory(nonce); @@ -245,13 +245,13 @@ public bool TryDecrypt(ReadOnlyMemory largeBlobKey, out Memory plain BinaryPrimitives.WriteInt32BigEndian(associatedData, AssociatedBlob); BinaryPrimitives.WriteInt64LittleEndian(associatedData.Slice(AssociatedSizeOffset), (long)OriginalDataLength); - IAesGcmPrimitives decryptor = CryptographyProviders.AesGcmPrimitivesCreator(); - bool returnValue = decryptor.DecryptAndVerify( + var decryptoAlgorithm = CryptographyProviders.AesGcmPrimitivesCreator(); + bool decryptSuccess = decryptoAlgorithm.DecryptAndVerify( largeBlobKey.Span, Nonce.Span, Ciphertext.Slice(0, dataToDecryptLength).Span, Ciphertext.Slice(dataToDecryptLength, GcmTagSize).Span, decryptedData, associatedData); - if (returnValue) + if (decryptSuccess) { using var compressedStream = new MemoryStream(decryptedData); using var decompressedStream = new MemoryStream(); @@ -259,16 +259,16 @@ public bool TryDecrypt(ReadOnlyMemory largeBlobKey, out Memory plain deflateStream.CopyTo(decompressedStream); deflateStream.Flush(); - returnValue = false; + decryptSuccess = false; if (decompressedStream.Length == OriginalDataLength) { byte[] dataToReturn = decompressedStream.ToArray(); plaintext = new Memory(dataToReturn); - returnValue = true; + decryptSuccess = true; } } - return returnValue; + return decryptSuccess; } finally { @@ -304,7 +304,7 @@ private ReadOnlyMemory EncryptBlobData(ReadOnlyMemory blobData, Read BinaryPrimitives.WriteInt64LittleEndian( associatedData.Slice(AssociatedSizeOffset), (long)blobData.Length); - IAesGcmPrimitives encryptor = CryptographyProviders.AesGcmPrimitivesCreator(); + var encryptor = CryptographyProviders.AesGcmPrimitivesCreator(); encryptor.EncryptAndAuthenticate( largeBlobKey.Span, Nonce.Span, dataToEncrypt, encryptedData, gcmTag, associatedData); Array.Copy(encryptedData, 0, ciphertext, 0, encryptedData.Length); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs index 3ebd7f9c..ce2243fd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/MakeCredentialData.cs @@ -236,22 +236,22 @@ public MakeCredentialData(ReadOnlyMemory cborEncoding) // If everything works, return true. Otherwise, return false. private bool ReadAttestation(CborMap map) { - CborMap attest = map.ReadMap(KeyAttestationStatement); - EncodedAttestationStatement = attest.Encoded; - if (!Format.Equals(PackedString, StringComparison.Ordinal) - || !attest.Contains(AlgString) || !attest.Contains(SigString) - || attest.Count > MaxAttestationMapCount - || (attest.Count == MaxAttestationMapCount && !attest.Contains(X5cString))) + var attestCborMap = map.ReadMap(KeyAttestationStatement); + EncodedAttestationStatement = attestCborMap.Encoded; + if (!Format.Equals(PackedString, StringComparison.Ordinal) || !attestCborMap.Contains(AlgString) || + !attestCborMap.Contains(SigString) || + attestCborMap.Count > MaxAttestationMapCount || + (attestCborMap.Count == MaxAttestationMapCount && !attestCborMap.Contains(X5cString))) { return false; } - AttestationAlgorithm = (CoseAlgorithmIdentifier)attest.ReadInt32(AlgString); - AttestationStatement = attest.ReadByteString(SigString); + AttestationAlgorithm = (CoseAlgorithmIdentifier)attestCborMap.ReadInt32(AlgString); + AttestationStatement = attestCborMap.ReadByteString(SigString); - if (attest.Contains(X5cString)) + if (attestCborMap.Contains(X5cString)) { - IReadOnlyList certList = attest.ReadArray(X5cString); + var certList = attestCborMap.ReadArray(X5cString); var attestationCertificates = new List(certList.Count); for (int index = 0; index < certList.Count; index++) @@ -293,7 +293,7 @@ public bool VerifyAttestation(ReadOnlyMemory clientDataHash) throw new InvalidOperationException(ExceptionMessages.MissingCtap2Data); } - using SHA256 digester = CryptographyProviders.Sha256Creator(); + using var digester = CryptographyProviders.Sha256Creator(); _ = digester.TransformBlock( AuthenticatorData.EncodedAuthenticatorData.ToArray(), 0, AuthenticatorData.EncodedAuthenticatorData.Length, null, 0); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs index 1f771c61..8e641d73 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/ParameterHelpers.cs @@ -43,7 +43,7 @@ public static List AddToList(T itemToAdd, List? currentList) throw new ArgumentNullException(); } - List returnList = currentList is null ? new List() : currentList; + var returnList = currentList ?? new List(); returnList.Add(itemToAdd); return returnList; @@ -69,7 +69,7 @@ public static Dictionary AddKeyValue( throw new ArgumentNullException(nameof(theValue)); } - Dictionary returnDictionary = + var returnDictionary = currentDictionary is null ? new Dictionary() : currentDictionary; // If the key already exists, replace the current value in the @@ -112,7 +112,7 @@ public static byte[] EncodeKeyValues(IReadOnlyDictionary var cbor = new CborWriter(CborConformanceMode.Ctap2Canonical, convertIndefiniteLengthEncodings: true); cbor.WriteStartMap(null); - foreach (KeyValuePair entry in localData) + foreach (var entry in localData) { cbor.WriteTextString(entry.Key); if (entry.Value is byte[] encodedValue) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolBase.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolBase.cs index b6ac6a6f..61261445 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolBase.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolBase.cs @@ -136,7 +136,7 @@ public virtual void Initialize() /// exception. /// /// - /// + /// /// The YubiKey's public key obtained by calling the /// . /// @@ -191,7 +191,7 @@ public virtual void Encapsulate(CoseKey authenticatorPublicKey) try { - IEcdhPrimitives ecdh = CryptographyProviders.EcdhPrimitivesCreator(); + var ecdh = CryptographyProviders.EcdhPrimitivesCreator(); platformKeyPair = ecdh.GenerateKeyPair(ECCurve.NamedCurves.nistP256); PlatformPublicKey = new CoseEcPublicKey(platformKeyPair.Value); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs index 409b46cf..165ec267 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolOne.cs @@ -63,13 +63,13 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length) ExceptionMessages.IncorrectPlaintextLength)); } - using Aes aes = CryptographyProviders.AesCreator(); + using var aes = CryptographyProviders.AesCreator(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.IV = new byte[BlockSize]; aes.Key = _keyData; - using ICryptoTransform aesTransform = aes.CreateEncryptor(); - + + using var aesTransform = aes.CreateEncryptor(); byte[] encryptedData = new byte[length]; _ = aesTransform.TransformBlock(plaintext, offset, length, encryptedData, 0); @@ -99,13 +99,13 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length) ExceptionMessages.IncorrectCiphertextLength)); } - using Aes aes = CryptographyProviders.AesCreator(); + using var aes = CryptographyProviders.AesCreator(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.IV = new byte[BlockSize]; aes.Key = _keyData; - using ICryptoTransform aesTransform = aes.CreateDecryptor(); - + + using var aesTransform = aes.CreateDecryptor(); byte[] decryptedData = new byte[length]; _ = aesTransform.TransformBlock(ciphertext, offset, length, decryptedData, 0); @@ -134,7 +134,7 @@ public override byte[] Authenticate(byte[] message) /// protected override byte[] Authenticate(byte[] keyData, byte[] message) { - using HMAC hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); + using var hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); hmacSha256.Key = keyData; return hmacSha256.ComputeHash(message).AsMemory(0, 16).ToArray(); } @@ -147,7 +147,7 @@ protected override void DeriveKeys(byte[] buffer) throw new ArgumentNullException(nameof(buffer)); } - using SHA256 sha256 = CryptographyProviders.Sha256Creator(); + using var sha256 = CryptographyProviders.Sha256Creator(); _ = sha256.TransformFinalBlock(buffer, 0, buffer.Length); if (sha256.Hash.Length != KeyLength) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs index f73d307c..740ec4c9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/PinProtocols/PinUvAuthProtocolTwo.cs @@ -73,17 +73,17 @@ public override byte[] Encrypt(byte[] plaintext, int offset, int length) // For protocol 2, generate a 16-byte, random IV, encrypt, then // return a buffer containing IV || ciphertext. + using var randomObject = CryptographyProviders.RngCreator(); byte[] initVector = new byte[BlockSize]; - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); randomObject.GetBytes(initVector); - using Aes aes = CryptographyProviders.AesCreator(); + using var aes = CryptographyProviders.AesCreator(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.IV = initVector; aes.Key = _aesKey; - using ICryptoTransform aesTransform = aes.CreateEncryptor(); - + + using var aesTransform = aes.CreateEncryptor(); byte[] encryptedData = new byte[BlockSize + length]; Array.Copy(initVector, 0, encryptedData, 0, BlockSize); _ = aesTransform.TransformBlock(plaintext, offset, length, encryptedData, BlockSize); @@ -120,13 +120,13 @@ public override byte[] Decrypt(byte[] ciphertext, int offset, int length) byte[] initVector = new byte[BlockSize]; Array.Copy(ciphertext, offset, initVector, 0, BlockSize); - using Aes aes = CryptographyProviders.AesCreator(); + using var aes = CryptographyProviders.AesCreator(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.IV = initVector; aes.Key = _aesKey; - using ICryptoTransform aesTransform = aes.CreateDecryptor(); - + + using var aesTransform = aes.CreateDecryptor(); byte[] decryptedData = new byte[length - BlockSize]; _ = aesTransform.TransformBlock(ciphertext, BlockSize + offset, length - BlockSize, decryptedData, 0); @@ -155,7 +155,7 @@ public override byte[] Authenticate(byte[] message) /// protected override byte[] Authenticate(byte[] keyData, byte[] message) { - using HMAC hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); + using var hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); hmacSha256.Key = keyData; return hmacSha256.ComputeHash(message); } @@ -194,7 +194,7 @@ protected override void DeriveKeys(byte[] buffer) { // Extract. byte[] salt = new byte[SaltLength]; - using HMAC hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); + using var hmacSha256 = CryptographyProviders.HmacCreator("HMACSHA256"); hmacSha256.Key = salt; prk = hmacSha256.ComputeHash(buffer); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs index a143dbce..42b7d50d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/RelyingParty.cs @@ -179,10 +179,10 @@ public bool IsMatchingRelyingPartyId(ReadOnlyMemory candidateHash) => // Perform the appropriate digest operation to generate the correct value. private void ComputeRelyingPartyIdHash() { - using SHA256 digester = CryptographyProviders.Sha256Creator(); - digester.Initialize(); + using var digestHashAlgorihm = CryptographyProviders.Sha256Creator(); + digestHashAlgorihm.Initialize(); byte[] utf = Encoding.UTF8.GetBytes(Id); - byte[] digest = digester.ComputeHash(utf); + byte[] digest = digestHashAlgorihm.ComputeHash(utf); RelyingPartyIdHash = new ReadOnlyMemory(digest); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs index 124b666d..c0ce06ac 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Fido2/SerializedLargeBlobArray.cs @@ -311,15 +311,17 @@ public void RemoveEntry(int index) public byte[] Encode() { _log.LogInformation("Build the Serialized Large Blob Array."); - ReadOnlyMemory encoding = EncodeBlobArray(); - ReadOnlyMemory digest = ComputeDigest(encoding); + + var encodingBytes = EncodeBlobArray(); + var digestBytes = ComputeDigest(encodingBytes); - byte[] returnValue = new byte[encoding.Length + digest.Length]; - var destination = new Memory(returnValue); - encoding.CopyTo(destination); - digest.CopyTo(destination.Slice(encoding.Length)); + byte[] serializedData = new byte[encodingBytes.Length + digestBytes.Length]; + var destination = new Memory(serializedData); + + encodingBytes.CopyTo(destination); + digestBytes.CopyTo(destination.Slice(encodingBytes.Length)); - return returnValue; + return serializedData; } // Create the CBOR Array of each of the entries. Set EncodedArray to this @@ -332,7 +334,7 @@ private ReadOnlyMemory EncodeBlobArray() Digest = null; var cbor = new CborWriter(CborConformanceMode.Ctap2Canonical, convertIndefiniteLengthEncodings: true); cbor.WriteStartArray(_entryList.Count); - foreach (LargeBlobEntry entry in _entryList) + foreach (var entry in _entryList) { cbor.WriteEncodedValue(new ReadOnlySpan(entry.CborEncode())); } @@ -364,7 +366,7 @@ public bool IsDigestVerified() if (!(EncodedArray is null) && !(Digest is null)) { - using SHA256 digester = CryptographyProviders.Sha256Creator(); + using var digester = CryptographyProviders.Sha256Creator(); byte[] computedDigest = digester.ComputeHash(EncodedArray.Value.ToArray()); var digestSpan = new Span(computedDigest, 0, DigestLength); returnValue = MemoryExtensions.SequenceEqual(digestSpan, Digest.Value.Span); @@ -380,7 +382,7 @@ private ReadOnlyMemory ComputeDigest(ReadOnlyMemory encoding) { if (Digest is null) { - using SHA256 digester = CryptographyProviders.Sha256Creator(); + using var digester = CryptographyProviders.Sha256Creator(); Digest = new ReadOnlyMemory(digester.ComputeHash(encoding.ToArray()), 0, DigestLength); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs index 86cdfcbe..24b86d69 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoConnection.cs @@ -49,8 +49,8 @@ public bool LoadQueryCancel(QueryCancel? queryCancel) public TResponse SendCommand(IYubiKeyCommand yubiKeyCommand) where TResponse : IYubiKeyResponse { - CommandApdu commandApdu = yubiKeyCommand.CreateCommandApdu(); - ResponseApdu responseApdu = _apduPipeline.Invoke(commandApdu, yubiKeyCommand.GetType(), typeof(TResponse)); + var commandApdu = yubiKeyCommand.CreateCommandApdu(); + var responseApdu = _apduPipeline.Invoke(commandApdu, yubiKeyCommand.GetType(), typeof(TResponse)); return yubiKeyCommand.CreateResponseForApdu(responseApdu); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs index 31ec8a45..624b49bf 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/FidoDeviceInfoFactory.cs @@ -39,29 +39,29 @@ public static YubiKeyDeviceInfo GetDeviceInfo(IHidDevice device) Log.LogInformation("Getting device info for FIDO device {Device}", device); - if (!TryGetDeviceInfoFromFido(device, out YubiKeyDeviceInfo? ykDeviceInfo)) + if (!TryGetDeviceInfoFromFido(device, out var deviceInfo)) { - ykDeviceInfo = new YubiKeyDeviceInfo(); + deviceInfo = new YubiKeyDeviceInfo(); } - ykDeviceInfo.IsSkySeries |= device.ProductId == ProductIdentifiers.SecurityKey; + deviceInfo.IsSkySeries |= device.ProductId == ProductIdentifiers.SecurityKey; // Manually fill in gaps, if necessary var defaultDeviceInfo = new YubiKeyDeviceInfo(); - if (ykDeviceInfo.FirmwareVersion == defaultDeviceInfo.FirmwareVersion - && TryGetFirmwareVersionFromFido(device, out FirmwareVersion? firmwareVersion)) + if (deviceInfo.FirmwareVersion == defaultDeviceInfo.FirmwareVersion && + TryGetFirmwareVersionFromFido(device, out var firmwareVersion)) { - ykDeviceInfo.FirmwareVersion = firmwareVersion; + deviceInfo.FirmwareVersion = firmwareVersion; } - if (ykDeviceInfo.FirmwareVersion < FirmwareVersion.V4_0_0 && - ykDeviceInfo.AvailableUsbCapabilities == YubiKeyCapabilities.None) + if (deviceInfo.FirmwareVersion < FirmwareVersion.V4_0_0 && + deviceInfo.AvailableUsbCapabilities == YubiKeyCapabilities.None) { - ykDeviceInfo.AvailableUsbCapabilities = YubiKeyCapabilities.FidoU2f; + deviceInfo.AvailableUsbCapabilities = YubiKeyCapabilities.FidoU2f; } - return ykDeviceInfo; + return deviceInfo; } private static bool TryGetDeviceInfoFromFido( @@ -112,8 +112,7 @@ private static bool TryGetFirmwareVersionFromFido( Log.LogInformation("Attempting to read firmware version through FIDO."); using var connection = new FidoConnection(device); - VersionResponse response = connection.SendCommand(new VersionCommand()); - + var response = connection.SendCommand(new VersionCommand()); if (response.Status == ResponseStatus.Success) { firmwareVersion = response.GetData(); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoHelper.cs b/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoHelper.cs index 199dcbe3..39746d01 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoHelper.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoHelper.cs @@ -31,8 +31,7 @@ internal static class GetDeviceInfoHelper /// The specific type of IGetPagedDeviceInfoCommand, e.g. GetPagedDeviceInfoCommand, which will then allow for returning the appropriate response. /// The connection interface to communicate with a YubiKey. /// A YubiKeyDeviceInfo? object containing all relevant device information if successful, otherwise null. - public static YubiKeyDeviceInfo? GetDeviceInfo( - IYubiKeyConnection connection) + public static YubiKeyDeviceInfo? GetDeviceInfo(IYubiKeyConnection connection) where TCommand : IGetPagedDeviceInfoCommand>>>, new() @@ -43,21 +42,18 @@ where TCommand bool hasMoreData = true; while (hasMoreData) { - IYubiKeyResponseWithData>> response = - connection.SendCommand(new TCommand { Page = (byte)page++ }); - + var response = connection.SendCommand(new TCommand { Page = (byte)page++ }); if (response.Status == ResponseStatus.Success) { - Dictionary> tlvData = response.GetData(); - - foreach (KeyValuePair> tlv in tlvData) + var tlvData = response.GetData(); + foreach (var tlv in tlvData) { combinedPages.Add(tlv.Key, tlv.Value); } const int moreDataTag = 0x10; - hasMoreData = tlvData.TryGetValue(moreDataTag, out ReadOnlyMemory hasMoreDataByte) + hasMoreData = tlvData.TryGetValue(moreDataTag, out var hasMoreDataByte) && hasMoreDataByte.Span.Length == 1 && hasMoreDataByte.Span[0] == 1; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoResponseHelper.cs b/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoResponseHelper.cs index f8580a86..0a2cb0c7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoResponseHelper.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/GetDeviceInfoResponseHelper.cs @@ -54,7 +54,7 @@ internal static class GetDeviceInfoResponseHelper while (tlvReader.HasData) { int tag = tlvReader.PeekTag(); - ReadOnlyMemory value = tlvReader.ReadValue(tag); + var value = tlvReader.ReadValue(tag); result.Add(tag, value); } @@ -81,7 +81,7 @@ internal static Dictionary> ParseResponse( }; } - Dictionary>? result = CreateApduDictionaryFromResponseData(responseApdu.Data); + var result = CreateApduDictionaryFromResponseData(responseApdu.Data); return result ?? throw new MalformedYubiKeyResponseException { ResponseClass = responseClass, diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardConnection.cs index a98fa38d..9aa2d1d7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardConnection.cs @@ -39,9 +39,8 @@ public KeyboardConnection(IHidDevice hidDevice) public TResponse SendCommand(IYubiKeyCommand yubiKeyCommand) where TResponse : IYubiKeyResponse { - CommandApdu apdu = yubiKeyCommand.CreateCommandApdu(); - - ResponseApdu responseApdu = _apduPipeline.Invoke(apdu, yubiKeyCommand.GetType(), typeof(TResponse)); + var commandApdu = yubiKeyCommand.CreateCommandApdu(); + var responseApdu = _apduPipeline.Invoke(commandApdu, yubiKeyCommand.GetType(), typeof(TResponse)); return yubiKeyCommand.CreateResponseForApdu(responseApdu); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs index 9e8f981b..9e0083d9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/KeyboardDeviceInfoFactory.cs @@ -40,32 +40,32 @@ public static YubiKeyDeviceInfo GetDeviceInfo(IHidDevice device) throw new ArgumentException(ExceptionMessages.InvalidDeviceNotKeyboard, nameof(device)); } - if (!TryGetDeviceInfoFromKeyboard(device, out YubiKeyDeviceInfo? ykDeviceInfo)) + if (!TryGetDeviceInfoFromKeyboard(device, out var deviceInfo)) { - ykDeviceInfo = new YubiKeyDeviceInfo(); + deviceInfo = new YubiKeyDeviceInfo(); } // Manually fill in gaps, if necessary var defaultDeviceInfo = new YubiKeyDeviceInfo(); - if (ykDeviceInfo.SerialNumber == defaultDeviceInfo.SerialNumber + if (deviceInfo.SerialNumber == defaultDeviceInfo.SerialNumber && TryGetSerialNumberFromKeyboard(device, out int? serialNumber)) { - ykDeviceInfo.SerialNumber = serialNumber; + deviceInfo.SerialNumber = serialNumber; } - if (ykDeviceInfo.FirmwareVersion == defaultDeviceInfo.FirmwareVersion - && TryGetFirmwareVersionFromKeyboard(device, out FirmwareVersion? firmwareVersion)) + if (deviceInfo.FirmwareVersion == defaultDeviceInfo.FirmwareVersion && + TryGetFirmwareVersionFromKeyboard(device, out var firmwareVersion)) { - ykDeviceInfo.FirmwareVersion = firmwareVersion; + deviceInfo.FirmwareVersion = firmwareVersion; } - if (ykDeviceInfo.FirmwareVersion < FirmwareVersion.V4_0_0 && ykDeviceInfo.AvailableUsbCapabilities == YubiKeyCapabilities.None) + if (deviceInfo.FirmwareVersion < FirmwareVersion.V4_0_0 && deviceInfo.AvailableUsbCapabilities == YubiKeyCapabilities.None) { - ykDeviceInfo.AvailableUsbCapabilities = YubiKeyCapabilities.Otp; + deviceInfo.AvailableUsbCapabilities = YubiKeyCapabilities.Otp; } - return ykDeviceInfo; + return deviceInfo; } private static bool TryGetDeviceInfoFromKeyboard(IHidDevice device, [MaybeNullWhen(returnValue: false)] out YubiKeyDeviceInfo yubiKeyDeviceInfo) @@ -109,8 +109,7 @@ private static bool TryGetSerialNumberFromKeyboard(IHidDevice device, out int? s Logger.LogInformation("Attempting to read serial number through the keybaord interface."); using var keyboardConnection = new KeyboardConnection(device); - Otp.Commands.GetSerialNumberResponse response = keyboardConnection.SendCommand(new Otp.Commands.GetSerialNumberCommand()); - + var response = keyboardConnection.SendCommand(new GetSerialNumberCommand()); if (response.Status == ResponseStatus.Success) { serialNumber = response.GetData(); @@ -145,8 +144,7 @@ private static bool TryGetFirmwareVersionFromKeyboard(IHidDevice device, [MaybeN Logger.LogInformation("Attempting to read firmware version through the keyboard interface."); using var keyboardConnection = new KeyboardConnection(device); - Otp.Commands.ReadStatusResponse response = keyboardConnection.SendCommand(new Otp.Commands.ReadStatusCommand()); - + var response = keyboardConnection.SendCommand(new ReadStatusCommand()); if (response.Status == ResponseStatus.Success) { firmwareVersion = response.GetData().FirmwareVersion; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/GetDeviceInfoResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/GetDeviceInfoResponse.cs index 769540b4..13b9e57a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/GetDeviceInfoResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Management/Commands/GetDeviceInfoResponse.cs @@ -59,7 +59,7 @@ public YubiKeyDeviceInfo GetData() }; } - if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out YubiKeyDeviceInfo? deviceInfo)) + if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out var deviceInfo)) { throw new MalformedYubiKeyResponseException { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs index d43ef489..51e6f3bf 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Code.cs @@ -79,7 +79,7 @@ public Code(string? value, CredentialPeriod period) { Value = value; - DateTimeOffset timestamp = DateTimeOffset.UtcNow; + var timestamp = DateTimeOffset.UtcNow; if (period != CredentialPeriod.Undefined) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponse.cs index d5edaf89..e0540b0f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsResponse.cs @@ -77,7 +77,7 @@ public IDictionary GetData() while (tlvReader.HasData) { (string? OtpString, int? Digits) response = (null, null); - CredentialType type = CredentialType.Totp; + var credentialType = CredentialType.Totp; bool requiresTouch = false; string label = tlvReader.PeekTag() switch @@ -94,7 +94,7 @@ public IDictionary GetData() { case HotpTag: _ = tlvReader.ReadByte(HotpTag); - type = CredentialType.Hotp; + credentialType = CredentialType.Hotp; break; case TouchTag: @@ -103,12 +103,12 @@ public IDictionary GetData() break; case FullResponseTag: - ReadOnlyMemory fullValue = tlvReader.ReadValue(FullResponseTag); + var fullValue = tlvReader.ReadValue(FullResponseTag); response = GetOtpValue(fullValue); break; case TruncatedResponseTag: - ReadOnlyMemory truncatedValue = tlvReader.ReadValue(TruncatedResponseTag); + var truncatedValue = tlvReader.ReadValue(TruncatedResponseTag); response = GetOtpValue(truncatedValue); break; @@ -120,7 +120,7 @@ public IDictionary GetData() }; } - Credential credential = FromLabelAndType(label, type); + var credential = FromLabelAndType(label, credentialType); credential.RequiresTouch = requiresTouch; credential.Digits = response.Digits; @@ -163,8 +163,8 @@ private static Credential FromLabelAndType(string label, CredentialType type) throw new ArgumentNullException(nameof(label)); } - (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, type); - return new Credential(issuer, account, type, period); + (var credentialPeriod, string? issuer, string account) = Credential.ParseLabel(label, type); + return new Credential(issuer, account, type, credentialPeriod); } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponse.cs index 1e0865d7..9c0235b3 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/CalculateCredentialResponse.cs @@ -77,7 +77,7 @@ public Code GetData() var tlvReader = new TlvReader(ResponseApdu.Data); - ReadOnlyMemory bytes = tlvReader.PeekTag() switch + var tlvBytes = tlvReader.PeekTag() switch { FullResponseTag => tlvReader.ReadValue(FullResponseTag), TruncatedResponseTag => tlvReader.ReadValue(TruncatedResponseTag), @@ -88,7 +88,7 @@ public Code GetData() } }; - if (bytes.Length < 5) + if (tlvBytes.Length < 5) { throw new MalformedYubiKeyResponseException() { @@ -97,10 +97,10 @@ public Code GetData() }; } - int digits = bytes.Span[0]; + int digits = tlvBytes.Span[0]; Credential.Digits = digits; - uint otpValue = BinaryPrimitives.ReadUInt32BigEndian(bytes.Slice(1).Span); + uint otpValue = BinaryPrimitives.ReadUInt32BigEndian(tlvBytes.Slice(1).Span); otpValue %= (uint)Math.Pow(10, digits); string response = otpValue.ToString(CultureInfo.InvariantCulture).PadLeft(digits, '0'); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListResponse.cs index 33275894..d509ba6f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ListResponse.cs @@ -92,18 +92,18 @@ public List GetData() /// private static Credential _GetCredential(ReadOnlyMemory value) { - _ThrowIfNotLength(value, 2); + ThrowIfNotLength(value, 2); byte algorithmType = value.Span[0]; var algorithm = (HashAlgorithm)(algorithmType & 0x0F); var type = (CredentialType)(algorithmType & 0xF0); string label = Encoding.UTF8.GetString(value.Slice(1).ToArray()); - (CredentialPeriod period, string? issuer, string account) = Credential.ParseLabel(label, type); + (var credentialPeriod, string? issuer, string account) = Credential.ParseLabel(label, type); - return new Credential(issuer, account, period, type, algorithm); + return new Credential(issuer, account, credentialPeriod, type, algorithm); } - private static void _ThrowIfNotLength(ReadOnlyMemory value, int minLength) + private static void ThrowIfNotLength(ReadOnlyMemory value, int minLength) { if (value.Length < minLength) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs index 7e3a19b5..5019e21b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/OathChallengeResponseBaseCommand.cs @@ -53,7 +53,7 @@ protected static byte[] GenerateTotpChallenge(CredentialPeriod? period) /// protected static byte[] GenerateRandomChallenge() { - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); byte[] randomBytes = new byte[8]; randomObject.GetBytes(randomBytes); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/SelectOathResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/SelectOathResponse.cs index 09322b95..e1e25672 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/SelectOathResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/SelectOathResponse.cs @@ -59,9 +59,9 @@ public OathApplicationData GetData() } FirmwareVersion? version = null; - ReadOnlyMemory salt = ReadOnlyMemory.Empty; - ReadOnlyMemory challenge = ReadOnlyMemory.Empty; - HashAlgorithm algorithm = HashAlgorithm.Sha1; + var salt = ReadOnlyMemory.Empty; + var challenge = ReadOnlyMemory.Empty; + var algorithm = HashAlgorithm.Sha1; var tlvReader = new TlvReader(ResponseApdu.Data); while (tlvReader.HasData) @@ -69,7 +69,7 @@ public OathApplicationData GetData() switch (tlvReader.PeekTag()) { case VersionTag: - ReadOnlySpan firmwareValue = tlvReader.ReadValue(VersionTag).Span; + var firmwareValue = tlvReader.ReadValue(VersionTag).Span; version = new FirmwareVersion { Major = firmwareValue[0], diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs index 5d98a025..7fa44a52 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Commands/ValidateResponse.cs @@ -72,7 +72,7 @@ public bool GetData() } var tlvReader = new TlvReader(ResponseApdu.Data); - ReadOnlyMemory value = tlvReader.ReadValue(ResponseTag); + var value = tlvReader.ReadValue(ResponseTag); return value.Span.SequenceEqual(Response.Span); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs index b6823137..17210d5a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/Credential.cs @@ -420,7 +420,7 @@ public Credential(string? issuer, string account, CredentialType type, HashAlgor /// internal static (CredentialPeriod period, string? issuer, string account) ParseLabel(string label, CredentialType type) { - CredentialPeriod period = CredentialPeriod.Period30; + var credentialPeriod = CredentialPeriod.Period30; string? issuer = null; string issuerAccount; @@ -430,7 +430,7 @@ internal static (CredentialPeriod period, string? issuer, string account) ParseL if (parsedLabel.Length > 1) { - period = (CredentialPeriod)ToInt32(parsedLabel[0], NumberFormatInfo.InvariantInfo); + credentialPeriod = (CredentialPeriod)ToInt32(parsedLabel[0], NumberFormatInfo.InvariantInfo); issuerAccount = parsedLabel[1]; } else @@ -441,7 +441,7 @@ internal static (CredentialPeriod period, string? issuer, string account) ParseL else { issuerAccount = label; - period = CredentialPeriod.Undefined; + credentialPeriod = CredentialPeriod.Undefined; } string[]? parsedAccount = issuerAccount.Split(':'); @@ -458,7 +458,7 @@ internal static (CredentialPeriod period, string? issuer, string account) ParseL string account = parsedAccount.Last(); - return (period, issuer, account); + return (credentialPeriod, issuer, account); } /// @@ -502,16 +502,16 @@ public static Credential ParseUri(Uri uri) throw new InvalidOperationException(ExceptionMessages.InvalidUriQuery); } - NameValueCollection? parsedUri = HttpUtility.ParseQueryString(uriQuery); + var parsedUri = HttpUtility.ParseQueryString(uriQuery); string? defaultIssuer = parsedUri["issuer"]; (string? issuer, string account) = ParseUriPath(uriPath, defaultIssuer); string secret = parsedUri["secret"]; - CredentialType type = uri.Host == "totp" ? CredentialType.Totp : CredentialType.Hotp; + var type = uri.Host == "totp" ? CredentialType.Totp : CredentialType.Hotp; - HashAlgorithm algorithm = HashAlgorithm.Sha1; + var algorithm = HashAlgorithm.Sha1; string algorithmString = parsedUri["algorithm"]; if (!string.IsNullOrWhiteSpace(algorithmString)) @@ -550,14 +550,14 @@ public static Credential ParseUri(Uri uri) digits = DefaultDigits; } - CredentialPeriod period = CredentialPeriod.Period30; + var credentialPeriod = CredentialPeriod.Period30; string periodString = parsedUri["period"]; if (!string.IsNullOrWhiteSpace(periodString)) { if (int.TryParse(periodString, NumberStyles.Any, CultureInfo.InvariantCulture, out int periodInt)) { - period = (CredentialPeriod)periodInt; + credentialPeriod = (CredentialPeriod)periodInt; } else { @@ -578,7 +578,7 @@ public static Credential ParseUri(Uri uri) issuer = Uri.UnescapeDataString(issuer); } - return new Credential(issuer, Uri.UnescapeDataString(account), type, algorithm, secret, period, digits, counter, false); + return new Credential(issuer, Uri.UnescapeDataString(account), type, algorithm, secret, credentialPeriod, digits, counter, false); } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs index 989400f6..262fdbb1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Credential.cs @@ -38,21 +38,21 @@ public sealed partial class OathSession : IDisposable /// public IList GetCredentials() { - var listCommand = new ListCommand(); - ListResponse listResponse = Connection.SendCommand(listCommand); + var command = new ListCommand(); + var response = Connection.SendCommand(command); - if (listResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPassword(); - listResponse = Connection.SendCommand(listCommand); + response = Connection.SendCommand(command); } - if (listResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(listResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } - IList result = listResponse.GetData(); + IList result = response.GetData(); return result; } @@ -83,21 +83,21 @@ public IList GetCredentials() public IDictionary CalculateAllCredentials( ResponseFormat responseFormat = ResponseFormat.Truncated) { - var calculateAllCommand = new CalculateAllCredentialsCommand(responseFormat); - CalculateAllCredentialsResponse calculateAllResponse = Connection.SendCommand(calculateAllCommand); + var command = new CalculateAllCredentialsCommand(responseFormat); + var response = Connection.SendCommand(command); - if (calculateAllResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPassword(); - calculateAllResponse = Connection.SendCommand(calculateAllCommand); + response = Connection.SendCommand(command); } - if (calculateAllResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(calculateAllResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } - IDictionary result = calculateAllResponse.GetData(); + var result = response.GetData(); return result; } @@ -129,21 +129,21 @@ public Code CalculateCredential( Credential credential, ResponseFormat responseFormat = ResponseFormat.Truncated) { - var calculateCommand = new CalculateCredentialCommand(credential, responseFormat); - CalculateCredentialResponse calculateResponse = Connection.SendCommand(calculateCommand); + var command = new CalculateCredentialCommand(credential, responseFormat); + var response = Connection.SendCommand(command); - if (calculateResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPassword(); - calculateResponse = Connection.SendCommand(calculateCommand); + response = Connection.SendCommand(command); } - if (calculateResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(calculateResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } - Code otpCode = calculateResponse.GetData(); + var otpCode = response.GetData(); return otpCode; } @@ -187,7 +187,7 @@ public Code CalculateCredential( ResponseFormat responseFormat = ResponseFormat.Truncated) { var credential = new Credential(issuer, account, type, period); - Code otpCode = CalculateCredential(credential, responseFormat); + var otpCode = CalculateCredential(credential, responseFormat); return otpCode; } @@ -228,18 +228,18 @@ public void AddCredential(Credential credential) throw new InvalidOperationException(ExceptionMessages.SHA512NotSupported); } - var putCommand = new PutCommand(credential); - OathResponse putResponse = Connection.SendCommand(putCommand); + var command = new PutCommand(credential); + var response = Connection.SendCommand(command); - if (putResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPassword(); - putResponse = Connection.SendCommand(putCommand); + response = Connection.SendCommand(command); } - if (putResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(putResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } @@ -451,18 +451,18 @@ public void RenameCredential(Credential credential, string? newIssuer, string ne throw new InvalidOperationException(ExceptionMessages.RenameCommandNotSupported); } - var renameCommand = new RenameCommand(credential, newIssuer, newAccount); - RenameResponse renameResponse = Connection.SendCommand(renameCommand); + var command = new RenameCommand(credential, newIssuer, newAccount); + var response = Connection.SendCommand(command); - if (renameResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPassword(); - renameResponse = Connection.SendCommand(renameCommand); + response = Connection.SendCommand(command); } - if (renameResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(renameResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs index 139948a9..dd96dd79 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.Password.cs @@ -50,13 +50,13 @@ public bool TryVerifyPassword() { if (KeyCollector!(keyEntryData)) { - ReadOnlyMemory password = keyEntryData.GetCurrentValue(); - var validateCommand = new ValidateCommand(password, _oathData); - ValidateResponse verifyResponse = Connection.SendCommand(validateCommand); - - if (verifyResponse.Status == ResponseStatus.Success) + var password = keyEntryData.GetCurrentValue(); + var command = new ValidateCommand(password, _oathData); + + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Success) { - passwordVerified = verifyResponse.GetData(); + passwordVerified = response.GetData(); } } } @@ -132,22 +132,22 @@ public void VerifyPassword() /// public bool TryVerifyPassword(ReadOnlyMemory password) { - var validateCommand = new ValidateCommand(password, _oathData); - ValidateResponse verifyResponse = Connection.SendCommand(validateCommand); + var command = new ValidateCommand(password, _oathData); + var response = Connection.SendCommand(command); - if (verifyResponse.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { - return verifyResponse.GetData(); + return response.GetData(); } - if (verifyResponse.StatusWord == SWConstants.InvalidCommandDataParameter - || verifyResponse.StatusWord == SWConstants.ReferenceDataUnusable) + if (response.StatusWord == SWConstants.InvalidCommandDataParameter || + response.StatusWord == SWConstants.ReferenceDataUnusable) { return false; } // If the response was anything else, that is an error. - throw new InvalidOperationException(verifyResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } /// @@ -186,8 +186,8 @@ public void SetPassword() { if (KeyCollector!(keyEntryData)) { - ReadOnlyMemory currentPassword = keyEntryData.GetCurrentValue(); - ReadOnlyMemory newPassword = keyEntryData.GetNewValue(); + var currentPassword = keyEntryData.GetCurrentValue(); + var newPassword = keyEntryData.GetNewValue(); if (currentPassword.Span.SequenceEqual(newPassword.Span)) { @@ -323,12 +323,11 @@ public bool TrySetPassword(ReadOnlyMemory currentPassword, ReadOnlyMemory< } var setPasswordCommand = new SetPasswordCommand(newPassword, _oathData); - SetPasswordResponse setPasswordResponse = Connection.SendCommand(setPasswordCommand); - + var setPasswordResponse = Connection.SendCommand(setPasswordCommand); if (setPasswordResponse.Status == ResponseStatus.Success) { - SelectOathResponse response = Connection.SendCommand(new SelectOathCommand()); - _oathData = response.GetData(); + var selectOathResponse = Connection.SendCommand(new SelectOathCommand()); + _oathData = selectOathResponse.GetData(); return true; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.cs index d08f8283..97d9c4cd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Oath/OathSession.cs @@ -120,15 +120,14 @@ public OathSession(IYubiKeyDevice yubiKey) /// public void ResetApplication() { - OathResponse resetResponse = Connection.SendCommand(new ResetCommand()); - - if (resetResponse.Status != ResponseStatus.Success) + var resetOathResponse = Connection.SendCommand(new ResetCommand()); + if (resetOathResponse.Status != ResponseStatus.Success) { - throw new InvalidOperationException(resetResponse.StatusMessage); + throw new InvalidOperationException(resetOathResponse.StatusMessage); } - SelectOathResponse response = Connection.SendCommand(new SelectOathCommand()); - _oathData = response.GetData(); + var selectOathResponse = Connection.SendCommand(new SelectOathCommand()); + _oathData = selectOathResponse.GetData(); } // Checks if the KeyCollector delegate is null diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommand.cs index 4bc6ca38..bcbcd23c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ConfigureSlotCommand.cs @@ -51,7 +51,7 @@ public void SetFixedData(ReadOnlySpan fixedData) fixedData.Length)); } - Span target = ConfigurationBuffer.Slice(FixedDataOffset, FixedDataLength); + var target = ConfigurationBuffer.Slice(FixedDataOffset, FixedDataLength); fixedData.CopyTo(target); // If the data is less than the buffer, make sure the rest is empty. if (fixedData.Length < FixedDataLength) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/GetDeviceInfoResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/GetDeviceInfoResponse.cs index 2eeb1afb..9cc4d772 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/GetDeviceInfoResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/GetDeviceInfoResponse.cs @@ -66,7 +66,7 @@ public YubiKeyDeviceInfo GetData() }; } - if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out YubiKeyDeviceInfo? deviceInfo)) + if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out var deviceInfo)) { throw new MalformedYubiKeyResponseException { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ReadStatusResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ReadStatusResponse.cs index fdf54fa2..bda83fbc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ReadStatusResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Commands/ReadStatusResponse.cs @@ -65,23 +65,23 @@ public OtpStatus GetData() }; } - ReadOnlySpan responseApduData = ResponseApdu.Data.Span; + var responseApduSpan = ResponseApdu.Data.Span; return new OtpStatus { FirmwareVersion = new FirmwareVersion { - Major = responseApduData[0], - Minor = responseApduData[1], - Patch = responseApduData[2] + Major = responseApduSpan[0], + Minor = responseApduSpan[1], + Patch = responseApduSpan[2] }, - SequenceNumber = responseApduData[3], - ShortPressConfigured = (responseApduData[4] & ShortPressValidMask) != 0, - LongPressConfigured = (responseApduData[4] & LongPressValidMask) != 0, - ShortPressRequiresTouch = (responseApduData[4] & ShortPressTouchMask) != 0, - LongPressRequiresTouch = (responseApduData[4] & LongPressTouchMask) != 0, - LedBehaviorInverted = (responseApduData[4] & LedInvertedMask) != 0, - TouchLevel = responseApduData[5], + SequenceNumber = responseApduSpan[3], + ShortPressConfigured = (responseApduSpan[4] & ShortPressValidMask) != 0, + LongPressConfigured = (responseApduSpan[4] & LongPressValidMask) != 0, + ShortPressRequiresTouch = (responseApduSpan[4] & ShortPressTouchMask) != 0, + LongPressRequiresTouch = (responseApduSpan[4] & LongPressTouchMask) != 0, + LedBehaviorInverted = (responseApduSpan[4] & LedInvertedMask) != 0, + TouchLevel = responseApduSpan[5], }; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefConfig.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefConfig.cs index 12f3c367..c85faca9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefConfig.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefConfig.cs @@ -111,7 +111,7 @@ public static byte[] CreateTextConfig(string value, string languageCode, bool en throw new ArgumentNullException(nameof(languageCode)); } - Encoding encoding = encodeAsUtf16 ? Encoding.BigEndianUnicode : Encoding.UTF8; + var encoding = encodeAsUtf16 ? Encoding.BigEndianUnicode : Encoding.UTF8; int languageLength = Encoding.ASCII.GetByteCount(languageCode); int valueLength = encoding.GetByteCount(value); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs index 0ae137ee..06032ace 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/NdefDataReader.cs @@ -91,7 +91,7 @@ public NdefDataReader(ReadOnlySpan responseData) Debug.Assert(responseData[2] == 0xD1); // Short Record, Well-known TypeName, Message Begin, Message End - ReadOnlySpan recordType = responseData.Slice(TypeOffset, typeLength); + var recordType = responseData.Slice(TypeOffset, typeLength); Type = recordType[0] switch { @@ -131,7 +131,7 @@ public NdefText ToText() int languageCodeLength = header & languageCodeLengthMask; int textOffset = languageCodeLength + 1; - Encoding encoding = Encoding.UTF8; + var encoding = Encoding.UTF8; if (isUtf16) { bool bomPresent; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/CalculateChallengeResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/CalculateChallengeResponse.cs index f7b46160..be938d4d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/CalculateChallengeResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/CalculateChallengeResponse.cs @@ -139,7 +139,8 @@ protected override void ExecuteOperation() OtpSlot!.Value, _algorithm, _challenge); - ChallengeResponseResponse response = Connection.SendCommand(cmd); + + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureChallengeResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureChallengeResponse.cs index 97148893..c27eabb3 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureChallengeResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureChallengeResponse.cs @@ -71,11 +71,11 @@ internal ConfigureChallengeResponse(IYubiKeyConnection connection, IOtpSession s /// protected override void ExecuteOperation() { - YubiKeyFlags ykFlags = Settings.YubiKeyFlags; + var yubiKeyFlags = Settings.YubiKeyFlags; var cmd = new ConfigureSlotCommand { - YubiKeyFlags = ykFlags, + YubiKeyFlags = yubiKeyFlags, OtpSlot = OtpSlot!.Value }; @@ -104,7 +104,7 @@ protected override void ExecuteOperation() cmd.ApplyCurrentAccessCode(CurrentAccessCode); cmd.SetAccessCode(NewAccessCode); - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException( @@ -268,7 +268,7 @@ private void ProcessKey() // Handle generating. if (_generateKey.Value) { - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + using var rng = CryptographyProviders.RngCreator(); rng.Fill(_randomKey.Span); _key = _randomKey; // From here forward, we use _key, so we'll release this diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureHotp.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureHotp.cs index 4a575bee..8e25ab4d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureHotp.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureHotp.cs @@ -41,11 +41,11 @@ internal ConfigureHotp(IYubiKeyConnection connection, IOtpSession session, Slot /// protected override void ExecuteOperation() { - YubiKeyFlags ykFlags = Settings.YubiKeyFlags; + var yubiKeyFlags = Settings.YubiKeyFlags; var cmd = new ConfigureSlotCommand { - YubiKeyFlags = ykFlags, + YubiKeyFlags = yubiKeyFlags, OtpSlot = OtpSlot!.Value }; @@ -68,7 +68,8 @@ protected override void ExecuteOperation() _key.Span.CopyTo(hotpKey[..HmacKeySize]); // Get a span that points to the bytes for the IMF. - Span imf = hotpKey[HmacKeySize..]; + var imf = hotpKey[HmacKeySize..]; + // Write it in network order (big endian). BinaryPrimitives.WriteUInt16BigEndian(imf, _imf); @@ -79,7 +80,7 @@ protected override void ExecuteOperation() cmd.ApplyCurrentAccessCode(CurrentAccessCode); cmd.SetAccessCode(NewAccessCode); - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( @@ -196,7 +197,7 @@ public ConfigureHotp GenerateKey(Memory key) } _key = key; - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + using var rng = CryptographyProviders.RngCreator(); rng.Fill(key.Span); return this; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureNdef.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureNdef.cs index 3f2b302f..ff43965e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureNdef.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureNdef.cs @@ -68,7 +68,7 @@ protected override void ExecuteOperation() ? NdefConfig.CreateUriConfig(_uri!) : NdefConfig.CreateTextConfig(_text!, _languageCode!, _useUtf16); - ReadStatusResponse response = Connection.SendCommand(new ConfigureNdefCommand(OtpSlot!.Value, configBuffer.Span)); + var response = Connection.SendCommand(new ConfigureNdefCommand(OtpSlot!.Value, configBuffer.Span)); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureStaticPassword.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureStaticPassword.cs index 35512107..12310b20 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureStaticPassword.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureStaticPassword.cs @@ -59,11 +59,11 @@ protected override void ExecuteOperation() _passwordHidCodes = _passwordHidCodes .Concat(new byte[SlotConfigureBase.MaxPasswordLength - _passwordHidCodes.Length]) .ToArray(); - YubiKeyFlags ykFlags = Settings.YubiKeyFlags; - + + var yubiKeyFlags = Settings.YubiKeyFlags; var cmd = new ConfigureSlotCommand { - YubiKeyFlags = ykFlags, + YubiKeyFlags = yubiKeyFlags, OtpSlot = OtpSlot!.Value }; cmd.SetFixedData(_passwordHidCodes.AsSpan(0, SlotConfigureBase.FixedDataLength)); @@ -74,7 +74,7 @@ protected override void ExecuteOperation() try { - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException( @@ -343,7 +343,8 @@ private void PopulateHidCodesIfReady() && _generatePassword.HasValue) { var translator = HidCodeTranslator.GetInstance(_keyboardLayout!.Value); - ReadOnlySpan password = _password.Span; + var password = _password.Span; + if (_generatePassword.Value) { GenerateRandomPassword(translator); @@ -376,8 +377,8 @@ private void PopulateHidCodesIfReady() // here. void GenerateRandomPassword(HidCodeTranslator translator) { - Span password = _generatedPassword.Span; - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + var password = _generatedPassword.Span; + using var rng = CryptographyProviders.RngCreator(); // Build the table of possible random characters. byte[] hidTable = translator .SupportedHidCodes diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtp.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtp.cs index 655466c8..f5106734 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtp.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/ConfigureYubicoOtp.cs @@ -82,11 +82,10 @@ internal ConfigureYubicoOtp(IYubiKeyConnection connection, IOtpSession session, /// protected override void ExecuteOperation() { - YubiKeyFlags ykFlags = Settings.YubiKeyFlags; - + var yubiKeyFlags = Settings.YubiKeyFlags; var cmd = new ConfigureSlotCommand { - YubiKeyFlags = ykFlags, + YubiKeyFlags = yubiKeyFlags, OtpSlot = OtpSlot!.Value }; try @@ -97,7 +96,7 @@ protected override void ExecuteOperation() cmd.ApplyCurrentAccessCode(CurrentAccessCode); cmd.SetAccessCode(NewAccessCode); - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( @@ -218,7 +217,7 @@ public ConfigureYubicoOtp UsePublicId(ReadOnlyMemory publicId) /// The current instance. public ConfigureYubicoOtp UseSerialNumberAsPublicId(Memory? publicId = null) { - Memory serialAsId = publicId ?? new byte[6]; + var serialAsId = publicId ?? new byte[6]; var exceptions = new List(); if (!(_useSerialAsPublicId ?? true)) { @@ -257,7 +256,7 @@ public ConfigureYubicoOtp UseSerialNumberAsPublicId(Memory? publicId = nul // we won't bother with the MODHEX step. // When ykman builds the byte collection, it deals with the serial // number as big-endian before converting it, so that's what we'll do. - Span pidSpan = serialAsId.Span; + var pidSpan = serialAsId.Span; pidSpan[0] = 0xff; pidSpan[1] = 0x00; BinaryPrimitives.WriteInt32BigEndian(pidSpan[2..], serialNumber!.Value); @@ -336,7 +335,7 @@ public ConfigureYubicoOtp GeneratePrivateId(Memory privateId) _privateIdentifier = privateId; - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + using var rng = CryptographyProviders.RngCreator(); rng.Fill(privateId.Span); return this; @@ -397,7 +396,7 @@ public ConfigureYubicoOtp GenerateKey(Memory key) } _key = key; - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + using var rng = CryptographyProviders.RngCreator(); rng.Fill(key.Span); return this; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/DeleteSlotConfiguration.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/DeleteSlotConfiguration.cs index 7ec21f9b..05960810 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/DeleteSlotConfiguration.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/DeleteSlotConfiguration.cs @@ -31,7 +31,7 @@ protected override void ExecuteOperation() }; cmd.ApplyCurrentAccessCode(CurrentAccessCode); - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/UpdateSlot.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/UpdateSlot.cs index 83cadab3..4453f2e7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/UpdateSlot.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/Operations/UpdateSlot.cs @@ -29,16 +29,17 @@ internal UpdateSlot(IYubiKeyConnection connection, IOtpSession session, Slot slo /// protected override void ExecuteOperation() { - YubiKeyFlags ykFlags = Settings.YubiKeyFlags; - var cmd = new UpdateSlotCommand + var yubiKeyFlags = Settings.YubiKeyFlags; + var command = new UpdateSlotCommand { - YubiKeyFlags = ykFlags, + YubiKeyFlags = yubiKeyFlags, OtpSlot = OtpSlot!.Value }; - cmd.ApplyCurrentAccessCode(CurrentAccessCode); - cmd.SetAccessCode(NewAccessCode); + + command.ApplyCurrentAccessCode(CurrentAccessCode); + command.SetAccessCode(NewAccessCode); - ReadStatusResponse response = Connection.SendCommand(cmd); + var response = Connection.SendCommand(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSession.cs index 07106c07..54fb532a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSession.cs @@ -180,8 +180,7 @@ public void SwapSlots() throw new InvalidOperationException(ExceptionMessages.OtpSlotsNotConfigured); } - ReadStatusResponse swapResponse = _connection.SendCommand(new SwapSlotsCommand()); - + var swapResponse = _connection.SendCommand(new SwapSlotsCommand()); if (swapResponse.Status != ResponseStatus.Success) { throw new InvalidOperationException(swapResponse.StatusMessage); @@ -245,7 +244,7 @@ public NdefDataReader ReadNdefTag() ReadNdefDataResponse response; using (_connection = YubiKey.Connect(YubiKeyApplication.OtpNdef)) { - OtpResponse selectResponse = _connection.SendCommand(new SelectNdefDataCommand() { FileID = NdefFileId.Ndef }); + var selectResponse = _connection.SendCommand(new SelectNdefDataCommand() { FileID = NdefFileId.Ndef }); if (selectResponse.Status != ResponseStatus.Success) { throw new InvalidOperationException( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.cs index ed9275eb..fe0a8a0c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Otp/OtpSettings.cs @@ -63,11 +63,12 @@ public YubiKeyFlags YubiKeyFlags int bitmask = 0; try { - foreach (Flag flag in FlagsSet.Where(k => k != Flag.None)) + foreach (var flag in FlagsSet.Where(k => k != Flag.None)) { - OtpFlagItem flagItem = _flagDefinitions[flag]; + var flagItem = _flagDefinitions[flag]; + // Doing this here makes the RequiredOr check easier. - Flag requiredOr = + var requiredOr = flagItem.RequiredOrFlags == Flag.None ? flag : flagItem.RequiredOrFlags; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/CommandChainingTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/CommandChainingTransform.cs index 7b64aee7..077ec08e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/CommandChainingTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/CommandChainingTransform.cs @@ -46,13 +46,13 @@ public ResponseApdu Invoke(CommandApdu command, Type commandType, Type responseT return _pipeline.Invoke(command, commandType, responseType); } - ReadOnlyMemory sourceData = command.Data; + var sourceData = command.Data; ResponseApdu? responseApdu = null; while (!sourceData.IsEmpty) { int length = Math.Min(MaxSize, sourceData.Length); - ReadOnlyMemory data = sourceData.Slice(0, length); + var data = sourceData.Slice(0, length); sourceData = sourceData.Slice(length); var partialApdu = new CommandApdu diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoErrorTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoErrorTransform.cs index e91a0a5a..9d2283fc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoErrorTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoErrorTransform.cs @@ -33,7 +33,7 @@ public FidoErrorTransform(IApduTransform nextTransform) /// public ResponseApdu Invoke(CommandApdu command, Type commandType, Type responseType) { - ResponseApdu fidoResponse = _nextTransform.Invoke( + var fidoResponse = _nextTransform.Invoke( command, commandType, responseType); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs index f586a606..e0f8cb5e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/FidoTransform.cs @@ -85,15 +85,13 @@ public ResponseApdu Invoke(CommandApdu commandApdu, Type commandType, Type respo } byte[] responseData = TransmitCommand(_channelId!.Value, ctapCmd, ctapData, out byte responseByte); - - ResponseApdu responseApdu = - responseByte switch - { - Ctap1Message => new ResponseApdu(responseData), - CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData), - CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData), - _ => new ResponseApdu(responseData, SWConstants.Success), - }; + var responseApdu = responseByte switch + { + Ctap1Message => new ResponseApdu(responseData), + CtapHidCbor => CtapToApduResponse.ToCtap2ResponseApdu(responseData), + CtapError => CtapToApduResponse.ToCtap1ResponseApdu(responseData), + _ => new ResponseApdu(responseData, SWConstants.Success), + }; return responseApdu; } @@ -132,11 +130,9 @@ private static byte[] ConstructContinuationPacket(uint cid, byte seq, ReadOnlySp } // This function applies a mask to remove the initial frame identifier (0x80) - private static byte GetPacketCmd(byte[] packet) => - (byte)(packet[4] & ~0x80); + private static byte GetPacketCmd(byte[] packet) => (byte)(packet[4] & ~0x80); - private static int GetPacketBcnt(byte[] packet) => - (packet[5] << 8) | packet[6]; + private static int GetPacketBcnt(byte[] packet) => (packet[5] << 8) | packet[6]; private byte[] TransmitCommand(uint channelId, byte commandByte, byte[] data, out byte responseByte) { @@ -157,7 +153,10 @@ private void SendRequest(uint channelId, byte commandByte, ReadOnlySpan da { // send init request packet bool requestFitsInInit = data.Length <= InitDataSize; - ReadOnlySpan dataInInitPacket = requestFitsInInit ? data : data.Slice(0, InitDataSize); + var dataInInitPacket = requestFitsInInit + ? data + : data.Slice(0, InitDataSize); + _hidConnection.SetReport(ConstructInitPacket(channelId, commandByte, dataInInitPacket, data.Length)); if (!requestFitsInInit) @@ -172,6 +171,7 @@ private void SendRequest(uint channelId, byte commandByte, ReadOnlySpan da data = data[ContinuationDataSize..]; seq++; } + _hidConnection.SetReport(ConstructContinuationPacket(channelId, seq, data)); } } @@ -213,11 +213,15 @@ private byte[] ReceiveResponse(uint channelId, byte commandByte, out byte respon { if (!(QueryCancel is null) && QueryCancel(commandByte)) { - _hidConnection.SetReport(ConstructInitPacket(channelId, CtapHidCancelCmd, ReadOnlySpan.Empty, 0)); + _hidConnection.SetReport( + ConstructInitPacket(channelId, CtapHidCancelCmd, ReadOnlySpan.Empty, 0)); + QueryCancel = null; } + responseInitPacket = _hidConnection.GetReport(); } + int responseDataLength = GetPacketBcnt(responseInitPacket); if (responseDataLength > MaxPayloadSize) @@ -242,6 +246,7 @@ private byte[] ReceiveResponse(uint channelId, byte commandByte, out byte respon continuationPacket.AsSpan(ContinuationHeaderSize).CopyTo(responseData.AsSpan(bytesRead)); bytesRead += ContinuationDataSize; } + byte[] lastContinuationPacket = _hidConnection.GetReport(); lastContinuationPacket.AsSpan(ContinuationHeaderSize).CopyTo(responseData.AsSpan(bytesRead)); } @@ -261,7 +266,7 @@ private void AcquireCtapHidChannel() rng.GetBytes(nonce); byte[] response = TransmitCommand(CtapHidBroadcastChannelId, CtapHidInitCmd, nonce, out _); - Span receivedNonce = response.AsSpan(0, 8); + var receivedNonce = response.AsSpan(0, 8); if (!nonce.AsSpan().SequenceEqual(receivedNonce)) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs index d5516638..3a2f6b09 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/KeyboardTransform.cs @@ -119,7 +119,7 @@ public void Cleanup() private void HandleSlotRequestInstruction(CommandApdu apdu, KeyboardFrameReader frameReader, bool configInstruction) { KeyboardReport? report = null; - foreach (KeyboardReport featureReport in apdu.GetHidReports()) + foreach (var featureReport in apdu.GetHidReports()) { _log.LogInformation("Wait for write pending..."); @@ -215,7 +215,7 @@ private KeyboardReport WaitFor( int timeLimitMs = shortTimeout ? 1023 : 14000; int sleepDurationMs = shortTimeout ? 1 : 250; int growthFactor = shortTimeout ? 2 : 1; - Stopwatch stopwatch = Stopwatch.StartNew(); + var stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < timeLimitMs) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs index 62eb1f7b..9379074d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/OtpErrorTransform.cs @@ -56,15 +56,15 @@ public ResponseApdu Invoke(CommandApdu command, Type commandType, Type responseT try { - ResponseApdu response = _nextTransform.Invoke(command, commandType, responseType); - int afterSequence = new ReadStatusResponse(response).GetData().SequenceNumber; + var responseApdu = _nextTransform.Invoke(command, commandType, responseType); + int afterSequence = new ReadStatusResponse(responseApdu).GetData().SequenceNumber; int expectedSequence = (beforeSequence + 1) % 0x100; // If we see the sequence number change, we can assume that the configuration was applied successfully. Otherwise // we just invent an error in the response. return afterSequence != expectedSequence - ? new ResponseApdu(response.Data.ToArray(), SWConstants.WarningNvmUnchanged) - : response; + ? new ResponseApdu(responseApdu.Data.ToArray(), SWConstants.WarningNvmUnchanged) + : responseApdu; } catch (KeyboardConnectionException e) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/ResponseChainingTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/ResponseChainingTransform.cs index d7c6a363..8ebb1884 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/ResponseChainingTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/ResponseChainingTransform.cs @@ -44,38 +44,38 @@ public ResponseApdu Invoke(CommandApdu command, Type commandType, Type responseT throw new ArgumentNullException(nameof(command)); } - ResponseApdu response = _pipeline.Invoke(command, commandType, responseType); + var responseApdu = _pipeline.Invoke(command, commandType, responseType); // Unless we see that bytes are available, there's nothing for this transform to do. - if (response.SW1 != SW1Constants.BytesAvailable) + if (responseApdu.SW1 != SW1Constants.BytesAvailable) { - return response; + return responseApdu; } var tempBuffer = new List(); do { - tempBuffer.AddRange(response.Data.ToArray()); + tempBuffer.AddRange(responseApdu.Data.ToArray()); // Note that OATH uses its own "get response" command. // See OathResponseChainingTransform - IYubiKeyCommand getResponseCommand = - CreateGetResponseCommand(command, response.SW2); + var getResponseCommand = + CreateGetResponseCommand(command, responseApdu.SW2); - response = _pipeline.Invoke( + responseApdu = _pipeline.Invoke( getResponseCommand.CreateCommandApdu(), commandType, responseType); } - while (response.SW1 == SW1Constants.BytesAvailable); + while (responseApdu.SW1 == SW1Constants.BytesAvailable); - if (response.SW == SWConstants.Success) + if (responseApdu.SW == SWConstants.Success) { - tempBuffer.AddRange(response.Data.ToArray()); + tempBuffer.AddRange(responseApdu.Data.ToArray()); } - return new ResponseApdu(tempBuffer.ToArray(), response.SW); + return new ResponseApdu(tempBuffer.ToArray(), responseApdu.SW); } protected virtual IYubiKeyCommand CreateGetResponseCommand(CommandApdu originatingCommand, short SW2) => diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs index 8f372e8b..2b5ce88d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Pipelines/Scp03ApduTransform.cs @@ -69,7 +69,7 @@ public Scp03ApduTransform(IApduTransform pipeline, StaticKeys staticKeys) /// public void Setup() { - using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); + using var rng = CryptographyProviders.RngCreator(); Setup(rng); } @@ -87,55 +87,53 @@ internal void Setup(RandomNumberGenerator rng) public ResponseApdu Invoke(CommandApdu command, Type commandType, Type responseType) { // Encode command - CommandApdu encodedCommand = _session.EncodeCommand(command); + var encodedCommand = _session.EncodeCommand(command); + // Pass along the encoded command - ResponseApdu response = _pipeline.Invoke(encodedCommand, commandType, responseType); - // Decode response and return it + var response = _pipeline.Invoke(encodedCommand, commandType, responseType); // Special carve out for SelectApplication here, since there will be nothing to decode if (commandType == typeof(InterIndustry.Commands.SelectApplicationCommand)) { return response; } - + + // Decode response and return it return _session.DecodeResponse(response); } private void PerformInitializeUpdate(byte[] hostChallenge) { - InitializeUpdateCommand initializeUpdateCommand = _session.BuildInitializeUpdate( + var initializeUpdateCommand = _session.BuildInitializeUpdate( Scp03Keys.KeyVersionNumber, hostChallenge); - ResponseApdu initializeUpdateResponseApdu = _pipeline.Invoke( + var initializeUpdateResponseApdu = _pipeline.Invoke( initializeUpdateCommand.CreateCommandApdu(), typeof(InitializeUpdateCommand), typeof(InitializeUpdateResponse)); - InitializeUpdateResponse initializeUpdateResponse = initializeUpdateCommand.CreateResponseForApdu(initializeUpdateResponseApdu); + var initializeUpdateResponse = initializeUpdateCommand.CreateResponseForApdu(initializeUpdateResponseApdu); initializeUpdateResponse.ThrowIfFailed(); _session.LoadInitializeUpdateResponse(initializeUpdateResponse, Scp03Keys); } private void PerformExternalAuthenticate() { - ExternalAuthenticateCommand externalAuthenticateCommand = _session.BuildExternalAuthenticate(); + var externalAuthenticateCommand = _session.BuildExternalAuthenticate(); - ResponseApdu externalAuthenticateResponseApdu = _pipeline.Invoke( + var externalAuthenticateResponseApdu = _pipeline.Invoke( externalAuthenticateCommand.CreateCommandApdu(), typeof(ExternalAuthenticateCommand), typeof(ExternalAuthenticateResponse)); - ExternalAuthenticateResponse externalAuthenticateResponse = externalAuthenticateCommand.CreateResponseForApdu(externalAuthenticateResponseApdu); + var externalAuthenticateResponse = externalAuthenticateCommand.CreateResponseForApdu(externalAuthenticateResponseApdu); externalAuthenticateResponse.ThrowIfFailed(); _session.LoadExternalAuthenticateResponse(externalAuthenticateResponse); } // There is a call to cleanup and a call to Dispose. The cleanup only // needs to call the cleanup on the local APDU Pipeline object. - public void Cleanup() - { - _pipeline.Cleanup(); - } + public void Cleanup() => _pipeline.Cleanup(); public void Dispose() { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs index 0188d1aa..cefc4b74 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AesForManagementKey.cs @@ -79,7 +79,7 @@ public AesForManagementKey(ReadOnlySpan managementKey, int expectedKeyLeng ExceptionMessages.IncorrectAesKeyLength)); } - using Aes aesObject = CryptographyProviders.AesCreator(); + using var aesObject = CryptographyProviders.AesCreator(); #pragma warning disable CA5358 // Allow the usage of cipher mode 'ECB' per the standard aesObject.Mode = CipherMode.ECB; #pragma warning restore CA5358 diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateResponse.cs index 75a386a3..2def017c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/AuthenticateResponse.cs @@ -128,8 +128,8 @@ public AuthenticateResponse(ResponseApdu responseApdu) : private byte[] ExtractGeneralAuthenticateResponseData() { var tlvReader = new TlvReader(ResponseApdu.Data); - TlvReader dataReader = tlvReader.ReadNestedTlv(NestedTag); - ReadOnlyMemory value = dataReader.ReadValue(ResponseTag); + var dataReader = tlvReader.ReadNestedTlv(NestedTag); + var value = dataReader.ReadValue(ResponseTag); return value.ToArray(); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs index 2ae7dc98..c6271ef0 100755 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyCommand.cs @@ -169,7 +169,7 @@ public CompleteAuthenticateManagementKeyCommand( Algorithm = initializeAuthenticationResponse.Algorithm; - (bool isMutual, ReadOnlyMemory clientAuthenticationChallenge) = initializeAuthenticationResponse.GetData(); + (bool isMutual, var clientAuthenticationChallenge) = initializeAuthenticationResponse.GetData(); _isMutual = isMutual; // With single auth, encrypt the challenge. Mutual decrypts. @@ -209,7 +209,7 @@ public CompleteAuthenticateManagementKeyCommand( if (_isMutual) { // For mutual auth, we will decrypt the witness - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); randomObject.GetBytes(_buffer, ExpectedResponseOffset * _blockSize, _blockSize); // The app will send the YubiKey a challenge in the clear. The diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs index dcc546d8..848d75be 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/CompleteAuthenticateManagementKeyResponse.cs @@ -152,9 +152,9 @@ public AuthenticateManagementKeyResult GetData() var tlvReader = new TlvReader(ResponseApdu.Data); if (tlvReader.TryReadNestedTlv(out tlvReader, EncodingTag)) { - if (tlvReader.TryReadValue(out ReadOnlyMemory responseValue, ResponseTag)) + if (tlvReader.TryReadValue(out var tlvBytes, ResponseTag)) { - return MemoryExtensions.SequenceEqual(responseValue.Span, YubiKeyAuthenticationExpectedResponse.Span) + return tlvBytes.Span.SequenceEqual(YubiKeyAuthenticationExpectedResponse.Span) ? AuthenticateManagementKeyResult.MutualFullyAuthenticated : AuthenticateManagementKeyResult.MutualYubiKeyAuthenticationFailed; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs index 5e11fae0..3bc47d60 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/GenerateKeyPairCommand.cs @@ -306,8 +306,9 @@ private byte[] BuildGenerateKeyPairApduData() } data[IndexValueLength] = (byte)valueLength; - Span returnValue = data.AsSpan(0, length); - return returnValue.ToArray(); + var apduData = data.AsSpan(0, length); + + return apduData.ToArray(); } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs index f8073dce..0cdc6146 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/InitializeAuthenticateManagementKeyResponse.cs @@ -113,9 +113,9 @@ public InitializeAuthenticateManagementKeyResponse(ResponseApdu responseApdu, Pi // just ignore any extra bytes. var tlvReader = new TlvReader(ResponseApdu.Data); int nestedTag = tlvReader.PeekTag(); - TlvReader authReader = tlvReader.ReadNestedTlv(nestedTag); + var authReader = tlvReader.ReadNestedTlv(nestedTag); int authTag = authReader.PeekTag(); - ReadOnlyMemory value = authReader.ReadValue(authTag); + var value = authReader.ReadValue(authTag); if (nestedTag != NestedTag || (authTag != MutualAuthTag && authTag != SingleAuthTag)) { @@ -124,6 +124,7 @@ public InitializeAuthenticateManagementKeyResponse(ResponseApdu responseApdu, Pi ResponseClass = nameof(InitializeAuthenticateManagementKeyResponse), }; } + if (value.Length < TDesDataLength) { throw new MalformedYubiKeyResponseException() diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs index 88ca6f8a..2082e4d1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/TripleDesForManagementKey.cs @@ -239,7 +239,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b // Build this object to use TripleDES with the given key. private ICryptoTransform BuildTripleDes(byte[] keyData) { - using TripleDES tripleDesObject = CryptographyProviders.TripleDesCreator(); + using var tripleDesObject = CryptographyProviders.TripleDesCreator(); #pragma warning disable CA5358 // Allow the usage of cipher mode 'ECB' tripleDesObject.Mode = CipherMode.ECB; #pragma warning restore CA5358 @@ -268,7 +268,7 @@ private ICryptoTransform BuildDes(byte[] threeKeyData, int offset) return BuildDesWithWeakKey(keyData); } #pragma warning restore CA5351 - using DES desObject = CryptographyProviders.DesCreator(); + using var desObject = CryptographyProviders.DesCreator(); #pragma warning disable CA5358 // Allow the usage of cipher mode 'ECB' desObject.Mode = CipherMode.ECB; #pragma warning restore CA5358 @@ -322,11 +322,11 @@ private ICryptoTransform BuildDesWithWeakKey(byte[] keyData) try { #pragma warning disable CA5358 // Allow the usage of cipher mode 'ECB' - using TripleDES tripleDesObject = CryptographyProviders.TripleDesCreator(); + using var tripleDesObject = CryptographyProviders.TripleDesCreator(); tripleDesObject.Mode = CipherMode.ECB; tripleDesObject.Padding = PaddingMode.None; - using DES desObject = CryptographyProviders.DesCreator(); + using var desObject = CryptographyProviders.DesCreator(); desObject.Mode = CipherMode.ECB; desObject.Padding = PaddingMode.None; #pragma warning restore CA5358 diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VersionResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VersionResponse.cs index a7f62cae..cc334020 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VersionResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Commands/VersionResponse.cs @@ -93,12 +93,12 @@ public FirmwareVersion GetData() }; } - ReadOnlySpan responseApduData = ResponseApdu.Data.Span; + var responseApduDataSpan = ResponseApdu.Data.Span; return new FirmwareVersion { - Major = responseApduData[0], - Minor = responseApduData[1], - Patch = responseApduData[2] + Major = responseApduDataSpan[0], + Minor = responseApduDataSpan[1], + Patch = responseApduDataSpan[2] }; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs index d8d3eea9..695a115b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/AdminData.cs @@ -426,21 +426,21 @@ private bool ReadSalt(TlvReader tlvReader, ref byte elementsRead) // If we have read this before, the XOR will clear the bit. elementsRead ^= SaltRead; - bool isValid = tlvReader.TryReadValue(out ReadOnlyMemory salt, SaltTag); + bool isValid = tlvReader.TryReadValue(out var saltBytes, SaltTag); if (isValid) { - if (salt.Length == 0) + if (saltBytes.Length == 0) { Salt = null; return true; } - if (salt.Length != SaltLength) + if (saltBytes.Length != SaltLength) { return false; } - salt.CopyTo(_salt); + saltBytes.CopyTo(_salt); Salt = _salt; isValid = (elementsRead & SaltRead) != 0; } @@ -464,13 +464,13 @@ private bool ReadDate(TlvReader tlvReader, ref byte elementsRead) // Also, if the length is 0, there is no date, we'll want the // 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; + bool isValid = tlvReader.TryReadValue(out var theTimeAsBytes, DateTag); + isValid = isValid && theTimeAsBytes.Length <= 8; - if (isValid && theTime.Length > 0) + if (isValid && theTimeAsBytes.Length > 0) { var cpyObj = new Memory(new byte[8]); - theTime.CopyTo(cpyObj); + theTimeAsBytes.CopyTo(cpyObj); long unixTimeSeconds = BinaryPrimitives.ReadInt64LittleEndian(cpyObj.Span); PinLastUpdated = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds).UtcDateTime; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs index 4d91d201..ab31f784 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardCapabilityContainer.cs @@ -213,7 +213,7 @@ public void SetRandomCardId() _log.LogInformation("Set the CardId of CardCapabilityContainer with a random value."); Clear(); - using (RandomNumberGenerator randomObject = CryptographyProviders.RngCreator()) + using (var randomObject = CryptographyProviders.RngCreator()) { randomObject.GetBytes(_uniqueCardIdentifier, CardIdOffset, CardIdLength); } @@ -351,7 +351,7 @@ private bool TryReadUniqueId(bool isValid, TlvReader tlvReader) if (isValid) { _log.LogInformation("Decode data into CardCapabilityContainer: UniqueId."); - if (tlvReader.TryReadValue(out ReadOnlyMemory encodedUniqueId, UniqueCardIdTag)) + if (tlvReader.TryReadValue(out var encodedUniqueId, UniqueCardIdTag)) { if (encodedUniqueId.Length == UniqueCardIdLength && MemoryExtensions.SequenceEqual(encodedUniqueId.Slice(AidOffset, AidLength).Span, ApplicationIdentifier.Span)) @@ -380,34 +380,34 @@ private bool TryReadFixedValues(bool isValid, TlvReader tlvReader) } _log.LogInformation("Decode data into CardCapabilityContainer: FixedValues."); - bool returnValue = isValid; + bool readSuccessful = isValid; - Tuple[] elementList = GetFixedTupleArray(); + var elementList = GetFixedTupleArray(); int index = 0; - while (returnValue && index < elementList.Length) + while (readSuccessful && index < elementList.Length) { if (elementList[index].Item2 == 0) { - returnValue = tlvReader.TryReadValue(out ReadOnlyMemory currentValue, elementList[index].Item1) && + readSuccessful = tlvReader.TryReadValue(out var currentValue, elementList[index].Item1) && currentValue.Length == elementList[index].Item2; } else { - returnValue = tlvReader.TryReadByte(out byte currentValue, elementList[index].Item1) && + readSuccessful = tlvReader.TryReadByte(out byte currentValue, elementList[index].Item1) && currentValue == elementList[index].Item3; } index++; } - return returnValue; + return readSuccessful; } private void WriteFixedValues(TlvWriter tlvWriter) { - Tuple[] elementList = GetFixedTupleArray(); - ReadOnlySpan emptySpan = ReadOnlySpan.Empty; + var elementList = GetFixedTupleArray(); + var emptySpan = ReadOnlySpan.Empty; int index = 0; do diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs index 6916f1a4..1049f19b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/CardholderUniqueId.cs @@ -155,7 +155,7 @@ public void SetRandomGuid() _log.LogInformation("Set the GUID of CardholderUniqueId with a random value."); Clear(); - using (RandomNumberGenerator randomObject = CryptographyProviders.RngCreator()) + using (var randomObject = CryptographyProviders.RngCreator()) { randomObject.GetBytes(_guidValue, 0, GuidLength); } @@ -217,7 +217,7 @@ public override byte[] Encode() // 3e 00 // fe 00 var tlvWriter = new TlvWriter(); - ReadOnlySpan emptySpan = ReadOnlySpan.Empty; + var emptySpan = ReadOnlySpan.Empty; using (tlvWriter.WriteNestedTlv(EncodingTag)) { tlvWriter.WriteValue(FascNumberTag, FascNumber.Span); @@ -278,7 +278,7 @@ private bool TryReadFascNumber(bool isValid, TlvReader tlvReader) if (isValid) { _log.LogInformation("Decode data into CardholderUniqueId: FascNumber."); - if (tlvReader.TryReadValue(out ReadOnlyMemory encodedFascn, FascNumberTag)) + if (tlvReader.TryReadValue(out var encodedFascn, FascNumberTag)) { if (MemoryExtensions.SequenceEqual(encodedFascn.Span, FascNumber.Span)) { @@ -302,12 +302,12 @@ private bool TryReadGuid(bool isValid, TlvReader tlvReader) if (isValid) { _log.LogInformation("Decode data into CardholderUniqueId: Guid."); - if (tlvReader.TryReadValue(out ReadOnlyMemory encodedGuid, GuidTag)) + if (tlvReader.TryReadValue(out var encodedGuidBytes, GuidTag)) { - if (encodedGuid.Length == GuidLength) + if (encodedGuidBytes.Length == GuidLength) { var dest = new Memory(_guidValue); - encodedGuid.CopyTo(dest); + encodedGuidBytes.CopyTo(dest); return true; } } @@ -339,9 +339,9 @@ private bool TryReadTrailingElements(bool isValid, TlvReader tlvReader) if (isValid) { _log.LogInformation("Decode data into CardholderUniqueId: TrailingElements."); - if (tlvReader.TryReadValue(out ReadOnlyMemory signature, SignatureTag)) + if (tlvReader.TryReadValue(out var signatureBytes, SignatureTag)) { - if (signature.Length == 0 && tlvReader.TryReadValue(out ReadOnlyMemory lrc, LrcTag)) + if (signatureBytes.Length == 0 && tlvReader.TryReadValue(out var lrc, LrcTag)) { if (lrc.Length == 0 && !tlvReader.HasData) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs index dc7fe414..3cb0ef59 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/KeyHistory.cs @@ -250,7 +250,7 @@ public override bool TryDecode(ReadOnlyMemory encodedData) // FE 00 byte onCard = 0; byte offCard = 0; - ReadOnlyMemory offCardUrl = ReadOnlyMemory.Empty; + var offCardUrl = ReadOnlyMemory.Empty; var tlvReader = new TlvReader(encodedData); bool isValid = tlvReader.TryReadNestedTlv(out tlvReader, EncodingTag); if (isValid) @@ -267,7 +267,7 @@ public override bool TryDecode(ReadOnlyMemory encodedData) } if (isValid) { - isValid = tlvReader.TryReadValue(out ReadOnlyMemory unusedData, UnusedTag); + isValid = tlvReader.TryReadValue(out var unusedData, UnusedTag); if (isValid) { isValid = unusedData.Length == 0; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs index e8d6e597..b16ef7cd 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/Objects/PinProtectedData.cs @@ -221,7 +221,7 @@ public override bool TryDecode(ReadOnlyMemory encodedData) // 88 1A (or 12 or 22) // 89 18 (or 10 or 20) // --management key-- - ReadOnlyMemory mgmtKey = ReadOnlyMemory.Empty; + var managementKey = ReadOnlyMemory.Empty; var tlvReader = new TlvReader(encodedData); bool isValid = true; @@ -232,21 +232,21 @@ public override bool TryDecode(ReadOnlyMemory encodedData) { 0 => tlvReader.TryReadNestedTlv(out tlvReader, EncodingTag), 1 => tlvReader.TryReadNestedTlv(out tlvReader, PinProtectedTag), - 2 => tlvReader.TryReadValue(out mgmtKey, MgmtKeyTag), + 2 => tlvReader.TryReadValue(out managementKey, MgmtKeyTag), _ => false, }; count++; } - if (IsValidKeyLength(mgmtKey.Length)) + if (IsValidKeyLength(managementKey.Length)) { - mgmtKey.CopyTo(_mgmtKey); - ManagementKey = _mgmtKey.Slice(0, mgmtKey.Length); + managementKey.CopyTo(_mgmtKey); + ManagementKey = _mgmtKey.Slice(0, managementKey.Length); } else { - if (mgmtKey.Length != 0) + if (managementKey.Length != 0) { isValid = false; } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivBioMetadata.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivBioMetadata.cs index 27db58fd..d7ef6f78 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivBioMetadata.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivBioMetadata.cs @@ -61,7 +61,7 @@ public PivBioMetadata(ReadOnlyMemory responseData) while (tlvReader.HasData) { int tag = tlvReader.PeekTag(); - ReadOnlyMemory value = tlvReader.ReadValue(tag); + var value = tlvReader.ReadValue(tag); switch (tag) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs index 17cc9f79..1b28ad62 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivDataTagExtensions.cs @@ -63,8 +63,7 @@ public static bool IsValidTagForPut(this PivDataTag tag) => /// public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory encoding) { - TlvReader? tlvReader = GetTlvReader(tag, encoding); - + var tlvReader = GetTlvReader(tag, encoding); if (tlvReader is null) { return false; @@ -334,7 +333,7 @@ public static bool IsValidEncodingForPut(this PivDataTag tag, ReadOnlyMemory value = tlvReader.ReadValue(expectedFormat[index]); + var value = tlvReader.ReadValue(expectedFormat[index]); - returnValue = expectedFormat[index + 1] != 0 + verifySuccess = expectedFormat[index + 1] != 0 ? value.Length <= expectedFormat[index + 1] : value.Length == expectedFormat[index + 2]; @@ -399,11 +398,11 @@ private static bool VerifyTagLength(TlvReader tlvReader, int[] expectedFormat, i } catch (TlvException) { - returnValue = false; + verifySuccess = false; } } - return returnValue; + return verifySuccess; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs index 89655331..07329d1b 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivEccPrivateKey.cs @@ -109,7 +109,7 @@ public static PivEccPrivateKey CreateEccPrivateKey(ReadOnlyMemory encodedP ExceptionMessages.InvalidPrivateKeyData)); } - ReadOnlyMemory value = tlvReader.ReadValue(EccTag); + var value = tlvReader.ReadValue(EccTag); return new PivEccPrivateKey(value.Span); } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs index 6d81bebb..4ba9955a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivMetadata.cs @@ -175,7 +175,7 @@ public PivMetadata(ReadOnlyMemory responseData, byte slotNumber) while (tlvReader.HasData) { int tag = tlvReader.PeekTag(); - ReadOnlyMemory value = tlvReader.ReadValue(tag); + var value = tlvReader.ReadValue(tag); switch (tag) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPublicKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPublicKey.cs index 4e60cd29..fdf9c658 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPublicKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivPublicKey.cs @@ -125,9 +125,8 @@ public static PivPublicKey Create(ReadOnlyMemory encodedPublicKey) { // Try to decode as an RSA public key. If that works, we're done. If // not, try ECC. If that doesn't work, exception. - bool isCreated = PivRsaPublicKey.TryCreate(out PivPublicKey publicKeyObject, encodedPublicKey); - - if (isCreated == false) + bool isCreated = PivRsaPublicKey.TryCreate(out var publicKeyObject, encodedPublicKey); + if (!isCreated) { if (PivEccPublicKey.TryCreate(out publicKeyObject, encodedPublicKey) == false) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs index 8e8f87db..9b5b257d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivRsaPrivateKey.cs @@ -202,7 +202,7 @@ public static PivRsaPrivateKey CreateRsaPrivateKey(ReadOnlyMemory encodedP } int tag = tlvReader.PeekTag(); - ReadOnlyMemory temp = tlvReader.ReadValue(tag); + var temp = tlvReader.ReadValue(tag); if (tag <= 0 || tag > CrtComponentCount) { continue; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs index eae1d3c2..e995414f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Attestation.cs @@ -117,12 +117,12 @@ public X509Certificate2 CreateAttestationStatement(byte slotNumber) if (_yubiKeyDevice.HasFeature(YubiKeyFeature.PivAttestation)) { // This call will throw an exception if the slot number is incorrect. - var createCommand = new CreateAttestationStatementCommand(slotNumber); - CreateAttestationStatementResponse createResponse = Connection.SendCommand(createCommand); + var command = new CreateAttestationStatementCommand(slotNumber); + var response = Connection.SendCommand(command); // This call will throw an exception if there was a problem with // attestation (imported, invalid cert, etc.). - return createResponse.GetData(); + return response.GetData(); } throw new NotSupportedException( @@ -183,13 +183,14 @@ public X509Certificate2 GetAttestationCertificate() { if (_yubiKeyDevice.HasFeature(YubiKeyFeature.PivAttestation)) { - var getCommand = new GetDataCommand(AttestationCertTag); - GetDataResponse getResponse = Connection.SendCommand(getCommand); - ReadOnlyMemory certData = getResponse.GetData(); + var command = new GetDataCommand(AttestationCertTag); + var response = Connection.SendCommand(command); + var certData = response.GetData(); var tlvReader = new TlvReader(certData); tlvReader = tlvReader.ReadNestedTlv(PivEncodingTag); certData = tlvReader.ReadValue(PivCertTag); + return new X509Certificate2(certData.ToArray()); } @@ -341,16 +342,15 @@ public void ReplaceAttestationKeyAndCertificate(PivPrivateKey privateKey, X509Ce ImportPrivateKey(PivSlot.Attestation, privateKey); - var putCommand = new PutDataCommand(AttestationCertTag, encodedCert); - PutDataResponse putResponse = Connection.SendCommand(putCommand); - - if (putResponse.Status != ResponseStatus.Success) + var command = new PutDataCommand(AttestationCertTag, encodedCert); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.CommandResponseApduUnexpectedResult, - putResponse.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); + response.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs index 9bea73db..58b0da5e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Crypto.cs @@ -393,10 +393,9 @@ 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> commandToPerform, + PivAlgorithm algorithm,string algorithmExceptionMessage) { bool pinRequired = true; @@ -412,10 +411,10 @@ private byte[] PerformPrivateKeyOperation(byte slotNumber, if (_yubiKeyDevice.HasFeature(YubiKeyFeature.PivMetadata)) { var metadataCommand = new GetMetadataCommand(slotNumber); - GetMetadataResponse metadataResponse = Connection.SendCommand(metadataCommand); + var metadataResponse = Connection.SendCommand(metadataCommand); // If there is no key in the slot, this will throw an exception. - PivMetadata metadata = metadataResponse.GetData(); + var metadata = metadataResponse.GetData(); // We know the algorithm based on the input data. Is it the // algorithm of the key in the slot? @@ -442,7 +441,7 @@ private byte[] PerformPrivateKeyOperation(byte slotNumber, // Metadata is not available on this YubiKey. // Try to perform the operation. If it works, we're done. If not, // we can get limited information on why not. - IYubiKeyResponseWithData initialResponse = Connection.SendCommand(command); + var initialResponse = Connection.SendCommand(commandToPerform); // If the response is AuthRequired, either the PIN is required or // touch is. The response does not tell us which. @@ -476,11 +475,10 @@ private byte[] PerformPrivateKeyOperation(byte slotNumber, VerifyPin(); } - IYubiKeyResponseWithData response = Connection.SendCommand(command); - - if (response.Status != ResponseStatus.AuthenticationRequired) + var commandToPerformResponse = Connection.SendCommand(commandToPerform); + if (commandToPerformResponse.Status != ResponseStatus.AuthenticationRequired) { - return response.GetData(); + return commandToPerformResponse.GetData(); } // If we reach this code, the Status is AuthRequired and the problem is touch. diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs index 1f2ecaa0..1d520b0d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.KeyPairs.cs @@ -139,10 +139,10 @@ public PivPublicKey GenerateKeyPair(byte slotNumber, AuthenticateManagementKey(); } - var generateCommand = new GenerateKeyPairCommand(slotNumber, algorithm, pinPolicy, touchPolicy); - GenerateKeyPairResponse generateResponse = Connection.SendCommand(generateCommand); + var command = new GenerateKeyPairCommand(slotNumber, algorithm, pinPolicy, touchPolicy); + var response = Connection.SendCommand(command); - return generateResponse.GetData(); + return response.GetData(); } /// @@ -254,12 +254,11 @@ public void ImportPrivateKey(byte slotNumber, AuthenticateManagementKey(); } - var importCommand = new ImportAsymmetricKeyCommand(privateKey, slotNumber, pinPolicy, touchPolicy); - ImportAsymmetricKeyResponse importResponse = Connection.SendCommand(importCommand); - - if (importResponse.Status != ResponseStatus.Success) + var command = new ImportAsymmetricKeyCommand(privateKey, slotNumber, pinPolicy, touchPolicy); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(importResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } @@ -343,7 +342,7 @@ public void ImportCertificate(byte slotNumber, X509Certificate2 certificate) AuthenticateManagementKey(); } - PivDataTag dataTag = GetCertDataTagFromSlotNumber(slotNumber); + var dataTag = GetCertDataTagFromSlotNumber(slotNumber); byte[] certDer = certificate.GetRawCertData(); var tlvWriter = new TlvWriter(); @@ -357,12 +356,11 @@ public void ImportCertificate(byte slotNumber, X509Certificate2 certificate) byte[] encodedCert = tlvWriter.Encode(); - var putCommand = new PutDataCommand((int)dataTag, encodedCert); - PutDataResponse putResponse = Connection.SendCommand(putCommand); - - if (putResponse.Status != ResponseStatus.Success) + var command = new PutDataCommand((int)dataTag, encodedCert); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(putResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } @@ -405,19 +403,18 @@ public void ImportCertificate(byte slotNumber, X509Certificate2 certificate) /// public X509Certificate2 GetCertificate(byte slotNumber) { - PivDataTag dataTag = GetCertDataTagFromSlotNumber(slotNumber); + var dataTag = GetCertDataTagFromSlotNumber(slotNumber); - var getCommand = new GetDataCommand((int)dataTag); - GetDataResponse getResponse = Connection.SendCommand(getCommand); - ReadOnlyMemory encodedCertData = getResponse.GetData(); + var command = new GetDataCommand((int)dataTag); + var response = Connection.SendCommand(command); + var encodedCertData = response.GetData(); var tlvReader = new TlvReader(encodedCertData); - bool isValid = tlvReader.TryReadNestedTlv(out TlvReader nestedReader, PivEncodingTag); - + + bool isValid = tlvReader.TryReadNestedTlv(out var nestedReader, PivEncodingTag); if (isValid) { - isValid = nestedReader.TryReadValue(out ReadOnlyMemory certData, PivCertTag); - + isValid = nestedReader.TryReadValue(out var certData, PivCertTag); if (isValid) { return new X509Certificate2(certData.ToArray()); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs index 05745d1d..12a7a207 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.ManagementKey.cs @@ -241,8 +241,9 @@ public bool TryAuthenticateManagementKey(bool mutualAuthentication = true) _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)) + var currentPinOnlyMode = TryAuthenticatePinOnly(true); + if (currentPinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected) || + currentPinOnlyMode.HasFlag(PivPinOnlyMode.PinDerived)) { return true; } @@ -667,10 +668,9 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK return false; } - var setCommand = new SetManagementKeyCommand(keyEntryData.GetNewValue(), touchPolicy, newKeyAlgorithm); - SetManagementKeyResponse setResponse = Connection.SendCommand(setCommand); - - if (setResponse.Status == ResponseStatus.Success) + var command = new SetManagementKeyCommand(keyEntryData.GetNewValue(), touchPolicy, newKeyAlgorithm); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Success) { ManagementKeyAlgorithm = newKeyAlgorithm; @@ -681,7 +681,7 @@ public bool TryChangeManagementKey(PivTouchPolicy touchPolicy, PivAlgorithm newK string.Format( CultureInfo.CurrentCulture, ExceptionMessages.CommandResponseApduUnexpectedResult, - setResponse.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); + response.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); } finally { @@ -905,17 +905,16 @@ private bool TryForcedChangeManagementKey(ReadOnlyMemory currentKey, { if (TryAuthenticateManagementKey(currentKey, true)) { - var setCommand = new SetManagementKeyCommand(newKey, touchPolicy, newKeyAlgorithm); - SetManagementKeyResponse setResponse = Connection.SendCommand(setCommand); - - if (setResponse.Status == ResponseStatus.Success) + var command = new SetManagementKeyCommand(newKey, touchPolicy, newKeyAlgorithm); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Success) { ManagementKeyAlgorithm = newKeyAlgorithm; return true; } - _log.LogInformation($"Failed to set management key. Message: {setResponse.StatusMessage}"); + _log.LogInformation($"Failed to set management key. Message: {response.StatusMessage}"); } @@ -938,9 +937,9 @@ private void CheckManagementKeyAlgorithm(PivAlgorithm algorithm, bool checkMode) { if (checkMode) { - PivPinOnlyMode mode = GetPinOnlyMode(); - - if (mode.HasFlag(PivPinOnlyMode.PinProtected) || mode.HasFlag(PivPinOnlyMode.PinDerived)) + var pinOnlyMode = GetPinOnlyMode(); + if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected) || + pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerived)) { throw new InvalidOperationException( string.Format( @@ -1033,10 +1032,10 @@ private bool TryAuthenticateManagementKey(bool mutualAuthentication, PivAlgorithm algorithm) { var initCommand = new InitializeAuthenticateManagementKeyCommand(mutualAuthentication, algorithm); - InitializeAuthenticateManagementKeyResponse initResponse = Connection.SendCommand(initCommand); + var initResponse = Connection.SendCommand(initCommand); var completeCommand = new CompleteAuthenticateManagementKeyCommand(initResponse, mgmtKey); - CompleteAuthenticateManagementKeyResponse completeResponse = Connection.SendCommand(completeCommand); + var completeResponse = Connection.SendCommand(completeCommand); ManagementKeyAuthenticationResult = completeResponse.GetData(); if (completeResponse.Status == ResponseStatus.Success) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs index aa373749..472ca4c4 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Msroots.cs @@ -280,7 +280,7 @@ public void WriteMsroots(ReadOnlySpan contents) /// public void WriteMsrootsStream(Stream contents) { - Span contentsSpan = GetSpanFromStream(contents, out int maxLength); + var contentsSpan = GetSpanFromStream(contents, out int maxLength); WriteMsrootsSpan(contentsSpan, maxLength); } @@ -390,15 +390,15 @@ private void WriteMsrootsSpan(ReadOnlySpan contents, int maxLength) ExceptionMessages.InvalidDataEncoding)); } - var putCommand = new PutDataCommand(MsrootsTag + index, encoding.Slice(0, bytesWritten)); - PutDataResponse putResponse = Connection.SendCommand(putCommand); - if (putResponse.Status != ResponseStatus.Success) + var command = new PutDataCommand(MsrootsTag + index, encoding.Slice(0, bytesWritten)); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.CommandResponseApduUnexpectedResult, - putResponse.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); + response.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); } offset += dataLength; @@ -481,24 +481,25 @@ public byte[] ReadMsroots() for (int index = 0; index < MsrootsObjectCount; index++) { - var getCommand = new GetDataCommand(MsrootsTag + index); - GetDataResponse getResponse = Connection.SendCommand(getCommand); + var command = new GetDataCommand(MsrootsTag + index); + var response = Connection.SendCommand(command); - if (getResponse.Status == ResponseStatus.NoData) + if (response.Status == ResponseStatus.NoData) { break; } - if (getResponse.Status != ResponseStatus.Success) + + if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.CommandResponseApduUnexpectedResult, - getResponse.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); + response.StatusWord.ToString("X4", CultureInfo.InvariantCulture))); } - var tlvReader = new TlvReader(getResponse.GetData()); - TlvReader nestedReader = tlvReader.ReadNestedTlv(PivEncodingTag); + var tlvReader = new TlvReader(response.GetData()); + var nestedReader = tlvReader.ReadNestedTlv(PivEncodingTag); int msrootsDataTag = nestedReader.PeekTag(); contentArray[index] = nestedReader.ReadValue(msrootsDataTag); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs index c0b064c2..f0645e04 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Objects.cs @@ -313,15 +313,15 @@ public sealed partial class PivSession : IDisposable // instantiation. private bool TryReadObject(PivDataObject pivDataObject) { - var getDataCommand = new GetDataCommand(pivDataObject.DataTag); - GetDataResponse getDataResponse = Connection.SendCommand(getDataCommand); + var command = new GetDataCommand(pivDataObject.DataTag); + var response = Connection.SendCommand(command); // If GetDataCommand requires the PIN and it had not been verified, // verify it now and run it again. - if (getDataResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { VerifyPin(); - getDataResponse = Connection.SendCommand(getDataCommand); + response = Connection.SendCommand(command); } // If there is no data, simply return the object created, the IsEmpty @@ -330,9 +330,9 @@ private bool TryReadObject(PivDataObject pivDataObject) // the data or we will get an exception because of an error in the // GetData, which is the kind of exception we want to throw, even // though this is a Try method. - if (getDataResponse.Status != ResponseStatus.NoData) + if (response.Status != ResponseStatus.NoData) { - ReadOnlyMemory encodedData = getDataResponse.GetData(); + var encodedData = response.GetData(); return pivDataObject.TryDecode(encodedData); } @@ -391,20 +391,20 @@ public void WriteObject(PivDataObject pivDataObject) try { dataToStore = pivDataObject.Encode(); - var putDataCommand = new PutDataCommand(pivDataObject.DataTag, dataToStore); - PutDataResponse putDataResponse = Connection.SendCommand(putDataCommand); + var command = new PutDataCommand(pivDataObject.DataTag, dataToStore); + var response = Connection.SendCommand(command); // The PutDataCommand requires mgmt key auth, if it has not been // authenticated, do so now and run it again. - if (putDataResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { AuthenticateManagementKey(true); - putDataResponse = Connection.SendCommand(putDataCommand); + response = Connection.SendCommand(command); } - if (putDataResponse.Status != ResponseStatus.Success) + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(putDataResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } finally diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs index fd508dc1..ddc647f9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pin.cs @@ -280,16 +280,17 @@ public void VerifyPin() public bool TryVerifyPin(ReadOnlyMemory pin, out int? retriesRemaining) { _log.LogInformation("Try to verify the PIV PIN with supplied PIN."); + retriesRemaining = null; PinVerified = false; - var verifyCommand = new VerifyPinCommand(pin); - VerifyPinResponse verifyResponse = Connection.SendCommand(verifyCommand); - - PinVerified = verifyResponse.Status == ResponseStatus.Success; + + var command = new VerifyPinCommand(pin); + var response = Connection.SendCommand(command); + PinVerified = response.Status == ResponseStatus.Success; if (!PinVerified) { - retriesRemaining = verifyResponse.GetData(); + retriesRemaining = response.GetData(); if ((retriesRemaining ?? 1) == 0) { @@ -421,7 +422,7 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount // PIN-derived, set mode to None and return true. // If it does return, then check the mode. If it is PIN-derived, the // PIN has been verified and the mgmt key has been authenticated. - if (!TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _)) + if (!TryGetChangePinMode(ReadOnlyMemory.Empty, out var pinOnlyMode, out _)) { throw new OperationCanceledException( string.Format( @@ -439,17 +440,16 @@ public void ChangePinAndPukRetryCounts(byte newRetryCountPin, byte newRetryCount VerifyPin(); } - SetPinRetriesResponse setRetriesResponse = Connection.SendCommand(setRetriesCommand); - - if (setRetriesResponse.Status != ResponseStatus.Success) + var response = Connection.SendCommand(setRetriesCommand); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(setRetriesResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } - if (mode != PivPinOnlyMode.None) + if (pinOnlyMode != PivPinOnlyMode.None) { // By passing Empty, this method will use the default PIN. - SetPinOnlyMode(ReadOnlyMemory.Empty, mode, out _); + SetPinOnlyMode(ReadOnlyMemory.Empty, pinOnlyMode, out _); } UpdateAdminData(); @@ -540,14 +540,13 @@ public bool TryChangePinAndPukRetryCounts(ReadOnlyMemory managementKey, // It will also return true if the mode is None (YubiKey is not // Pin-derived), in which case neither the PIN nor mgmt key is // verified/authenticated. - if (TryGetChangePinMode(pin, out PivPinOnlyMode mode, out retriesRemaining)) + if (TryGetChangePinMode(pin, out var mode, out retriesRemaining)) { if (ManagementKeyAuthenticated || TryAuthenticateManagementKey(managementKey, true)) { if (PinVerified || TryVerifyPin(pin, out retriesRemaining)) { - SetPinRetriesResponse setRetriesResponse = Connection.SendCommand(setRetriesCommand); - + var setRetriesResponse = Connection.SendCommand(setRetriesCommand); if (setRetriesResponse.Status == ResponseStatus.Success) { if (mode != PivPinOnlyMode.None) @@ -668,7 +667,7 @@ public bool TryChangePin() { _log.LogInformation("Try to change the PIV PIN with KeyCollector."); - if (TryGetChangePinMode(ReadOnlyMemory.Empty, out PivPinOnlyMode mode, out _)) + if (TryGetChangePinMode(ReadOnlyMemory.Empty, out var mode, out _)) { return TryChangeReference(KeyEntryRequest.ChangePivPin, ChangePinOrPuk, mode); } @@ -782,12 +781,11 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n { _log.LogInformation("Try to change the PIV PIN with supplied PINs."); - if (TryGetChangePinMode(currentPin, out PivPinOnlyMode mode, out retriesRemaining)) + if (TryGetChangePinMode(currentPin, out var mode, out retriesRemaining)) { - var changeCommand = new ChangeReferenceDataCommand(PivSlot.Pin, currentPin, newPin); - ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); - - if (changeResponse.Status == ResponseStatus.Success) + var command = new ChangeReferenceDataCommand(PivSlot.Pin, currentPin, newPin); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Success) { if (mode != PivPinOnlyMode.None) { @@ -798,7 +796,8 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n return true; } - else if (changeResponse.Status == ResponseStatus.ConditionsNotSatisfied) + + if (response.Status == ResponseStatus.ConditionsNotSatisfied) { throw new SecurityException( string.Format( @@ -809,7 +808,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n } - retriesRemaining = changeResponse.GetData(); + retriesRemaining = response.GetData(); } if ((retriesRemaining ?? 1) == 0) @@ -992,10 +991,10 @@ public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory n out int? retriesRemaining) { _log.LogInformation("Try to change the PIV PUK with supplied PUKs."); - var changeCommand = new ChangeReferenceDataCommand(PivSlot.Puk, currentPuk, newPuk); - ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); - - if (changeResponse.Status == ResponseStatus.ConditionsNotSatisfied) + + var command = new ChangeReferenceDataCommand(PivSlot.Puk, currentPuk, newPuk); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.ConditionsNotSatisfied) { retriesRemaining = null; throw new SecurityException( @@ -1006,9 +1005,9 @@ public bool TryChangePuk(ReadOnlyMemory currentPuk, ReadOnlyMemory n ); } - retriesRemaining = changeResponse.GetData(); + retriesRemaining = response.GetData(); - return changeResponse.Status == ResponseStatus.Success; + return response.Status == ResponseStatus.Success; } /// @@ -1119,9 +1118,9 @@ 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 _)) + if (TryGetChangePinMode(ReadOnlyMemory.Empty, out var pinOnlyMode, out _)) { - return TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, mode); + return TryChangeReference(KeyEntryRequest.ResetPivPinWithPuk, ResetPin, pinOnlyMode); } return false; @@ -1227,10 +1226,10 @@ public void ResetPin() public bool TryResetPin(ReadOnlyMemory puk, ReadOnlyMemory newPin, out int? retriesRemaining) { _log.LogInformation("Try to reset the PIV PIN using the PIV PUK with supplied PUK and PIN."); - var resetCommand = new ResetRetryCommand(puk, newPin); - ResetRetryResponse resetResponse = Connection.SendCommand(resetCommand); - - if (resetResponse.Status == ResponseStatus.ConditionsNotSatisfied) + + var command = new ResetRetryCommand(puk, newPin); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.ConditionsNotSatisfied) { retriesRemaining = null; throw new SecurityException( @@ -1241,8 +1240,7 @@ public bool TryResetPin(ReadOnlyMemory puk, ReadOnlyMemory newPin, o ); } - retriesRemaining = resetResponse.GetData(); - + retriesRemaining = response.GetData(); if ((retriesRemaining ?? 1) == 0) { throw new SecurityException( @@ -1251,7 +1249,7 @@ public bool TryResetPin(ReadOnlyMemory puk, ReadOnlyMemory newPin, o ExceptionMessages.NoMoreRetriesRemaining)); } - return resetResponse.Status == ResponseStatus.Success; + return response.Status == ResponseStatus.Success; } // Common code to change a PIN or PUK by either ChangeReferenceData or @@ -1285,9 +1283,8 @@ private bool TryChangeReference(KeyEntryRequest request, { while (KeyCollector(keyEntryData)) { - ResponseStatus status = commandResponse(keyEntryData); - - if (status == ResponseStatus.Success) + var responseStatus = commandResponse(keyEntryData); + if (responseStatus == ResponseStatus.Success) { if (mode != PivPinOnlyMode.None) { @@ -1310,7 +1307,7 @@ private bool TryChangeReference(KeyEntryRequest request, ExceptionMessages.NoMoreRetriesRemaining)); } - if (status == ResponseStatus.ConditionsNotSatisfied) + if (responseStatus == ResponseStatus.ConditionsNotSatisfied) { keyEntryData.IsViolatingPinComplexity = true; } @@ -1339,34 +1336,34 @@ private ResponseStatus ChangePinOrPuk(KeyEntryData keyEntryData) ? PivSlot.Pin : PivSlot.Puk; - var changeCommand = new ChangeReferenceDataCommand( + var command = new ChangeReferenceDataCommand( slotNumber, keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue()); - ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); + var response = Connection.SendCommand(command); // If success, GetData returns null. // If wrong PIN/PUK, returns count. // If error, throws exception. - keyEntryData.RetriesRemaining = changeResponse.GetData(); + keyEntryData.RetriesRemaining = response.GetData(); - return changeResponse.Status; + return response.Status; } // This is a delegate that implements the CommandResponse declaration of // TryChangeReference. It executes the ResetRetry command and response. private ResponseStatus ResetPin(KeyEntryData keyEntryData) { - var resetCommand = new ResetRetryCommand( + var command = new ResetRetryCommand( keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue()); - ResetRetryResponse resetResponse = Connection.SendCommand(resetCommand); + var response = Connection.SendCommand(command); // If success, GetData returns null. // If wrong PUK, returns count. // If error, throws exception. - keyEntryData.RetriesRemaining = resetResponse.GetData(); + keyEntryData.RetriesRemaining = response.GetData(); - return resetResponse.Status; + return response.Status; } // If the PIN has been changed, update the AdminData element diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs index cdd82b6d..1bbc20e9 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.Pinonly.cs @@ -88,26 +88,26 @@ public PivPinOnlyMode GetPinOnlyMode() { _log.LogInformation("Get the PIV PIN-only mode of a YubiKey based on AdminData."); - PivPinOnlyMode returnValue = PivPinOnlyMode.PinProtectedUnavailable | PivPinOnlyMode.PinDerivedUnavailable; + var pinOnlyMode = PivPinOnlyMode.PinProtectedUnavailable | PivPinOnlyMode.PinDerivedUnavailable; if (TryReadObject(out AdminData adminData)) { - returnValue = PivPinOnlyMode.None; + pinOnlyMode = PivPinOnlyMode.None; if (adminData.PinProtected) { - returnValue |= PivPinOnlyMode.PinProtected; + pinOnlyMode |= PivPinOnlyMode.PinProtected; } if (!(adminData.Salt is null)) { - returnValue |= PivPinOnlyMode.PinDerived; + pinOnlyMode |= PivPinOnlyMode.PinDerived; } adminData.Dispose(); } - return returnValue; + return pinOnlyMode; } /// @@ -191,15 +191,15 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() { _log.LogInformation("Try to authenticate using PIN-only."); - PivPinOnlyMode returnValue = TryAuthenticatePinOnly(false); + var pinOnlyMode = TryAuthenticatePinOnly(false); // If the result is None, or PinProtected, or PinDerived, or // PinProtected | PinDerived, then everything is fine, just return. // In other words, if it does not contain an Unavailable. - if (!returnValue.HasFlag(PivPinOnlyMode.PinProtectedUnavailable) && - !returnValue.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)) + if (!pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtectedUnavailable) && + !pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)) { - return returnValue; + return pinOnlyMode; } // If we reach this point, either PinProtectedUnavailable or @@ -208,7 +208,7 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // data is correct and the mgmt key has been authenticated. But we // also know that PinDerivedUnavailable is set. That means the ADMIN // DATA is wrong. We need to reset it. - if (returnValue.HasFlag(PivPinOnlyMode.PinProtected)) + if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected)) { // Make sure the PUK is blocked. It probably is, but we're going // to set the PukBlocked field in adminData to true, so make sure @@ -235,16 +235,16 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // YubiKey to also PIN-protected. Otherwise // Reset PRINTED to empty, and make sure ADMIN DATA indicates PUK // blocked and PinProtected is false. - if (returnValue.HasFlag(PivPinOnlyMode.PinDerived)) + if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerived)) { // Read the AdminData to get the salt. - AdminData adminData = ReadObject(); + var adminData = ReadObject(); // Clear out the contents of PRINTED. using var pinProtect = new PinProtectedData(); WriteObject(pinProtect); - PivPinOnlyMode protectMode = PivPinOnlyMode.None; + var protectMode = PivPinOnlyMode.None; if (adminData.PinProtected) { @@ -266,7 +266,7 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // means the mgmt key is not authenticated. // If we can authenticate the mgmt key, then set ADMIN DATA and // PRINTED. - Func? userKeyCollector = KeyCollector; + var userKeyCollector = KeyCollector; using var specialKeyCollector = new SpecialKeyCollector(); try @@ -279,7 +279,7 @@ 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) + using var adminData = pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable) ? new AdminData() : ReadObject(); @@ -296,7 +296,7 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() // either the PinProtected or the PinProtectedUnavailable bit // set, and if we reach this point we know the PinProtected bit // is not set). Just leave it. If it was set, clear PRINTED. - if (returnValue.HasFlag(PivPinOnlyMode.PinProtectedUnavailable)) + if (pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtectedUnavailable)) { using var pinProtect = new PinProtectedData(); WriteObject(pinProtect); @@ -306,11 +306,11 @@ public PivPinOnlyMode TryRecoverPinOnlyMode() } catch (InvalidOperationException) { - return returnValue; + return pinOnlyMode; } catch (OperationCanceledException) { - return returnValue; + return pinOnlyMode; } finally { @@ -339,17 +339,16 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) bool tryPinProtected = true; bool tryPinDerived = true; - PivPinOnlyMode returnValue = PivPinOnlyMode.None; + var pinOnlyMode = PivPinOnlyMode.None; if (trustAdminData) { - returnValue = GetPinOnlyMode(); - - tryPinProtected = returnValue.HasFlag(PivPinOnlyMode.PinProtected); - tryPinDerived = returnValue.HasFlag(PivPinOnlyMode.PinDerived); + pinOnlyMode = GetPinOnlyMode(); + tryPinProtected = pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected); + tryPinDerived = pinOnlyMode.HasFlag(PivPinOnlyMode.PinDerived); } - Func? userKeyCollector = KeyCollector; + var userKeyCollector = KeyCollector; using var specialKeyCollector = new SpecialKeyCollector(); try @@ -358,11 +357,10 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) if (tryPinProtected) { - returnValue = GetPrintedPinProtectedStatus(specialKeyCollector, userKeyCollector); - - if (trustAdminData && returnValue.HasFlag(PivPinOnlyMode.PinProtected)) + pinOnlyMode = GetPrintedPinProtectedStatus(specialKeyCollector, userKeyCollector); + if (trustAdminData && pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected)) { - return returnValue; + return pinOnlyMode; } } @@ -370,12 +368,12 @@ private PivPinOnlyMode TryAuthenticatePinOnly(bool trustAdminData) { using var adminData = new AdminData(); - returnValue |= GetPinDerivedStatus( - adminData, returnValue.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, + pinOnlyMode |= GetPinDerivedStatus( + adminData, pinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, userKeyCollector); } - return returnValue; + return pinOnlyMode; } finally { @@ -400,25 +398,25 @@ private PivPinOnlyMode GetPrintedPinProtectedStatus( // verified, ReadObject won't collect and save it. // Hence, in order to be able to call VerifyPinAndSave, but only if // needed, call the GetDataCommand directly. - var getDataCommand = new GetDataCommand((int)PivDataTag.Printed); - GetDataResponse getDataResponse = Connection.SendCommand(getDataCommand); + var command = new GetDataCommand((int)PivDataTag.Printed); + var response = Connection.SendCommand(command); - if (getDataResponse.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { specialKeyCollector.VerifyPinAndSave(this, userKeyCollector); - getDataResponse = Connection.SendCommand(getDataCommand); + response = Connection.SendCommand(command); } - if (getDataResponse.Status == ResponseStatus.NoData) + if (response.Status == ResponseStatus.NoData) { return PivPinOnlyMode.None; } - if (getDataResponse.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { using var pinProtect = new PinProtectedData(); - if (pinProtect.TryDecode(getDataResponse.GetData())) + if (pinProtect.TryDecode(response.GetData())) { if (pinProtect.ManagementKey is null) { @@ -465,17 +463,16 @@ private PivPinOnlyMode GetPinDerivedStatus( // 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 // data. - var getDataCommand = new GetDataCommand(adminData.DataTag); - GetDataResponse getDataResponse = Connection.SendCommand(getDataCommand); - - if (getDataResponse.Status == ResponseStatus.NoData) + var command = new GetDataCommand(adminData.DataTag); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.NoData) { return PivPinOnlyMode.None; } - if (getDataResponse.Status == ResponseStatus.Success) + if (response.Status == ResponseStatus.Success) { - if (adminData.TryDecode(getDataResponse.GetData())) + if (adminData.TryDecode(response.GetData())) { if (adminData.Salt is null) { @@ -753,7 +750,7 @@ public void SetPinOnlyMode(PivPinOnlyMode pinOnlyMode, PivAlgorithm mgmtKeyAlgor "Set a YubiKey to PIV PIN-only mode: {PivPinOnlyMode}, mgmt key alg = {PivAlgorithm}.", pinOnlyMode.ToString(), mgmtKeyAlgorithm.ToString()); - Func? userKeyCollector = KeyCollector; + var userKeyCollector = KeyCollector; using var specialKeyCollector = new SpecialKeyCollector(); try @@ -773,14 +770,13 @@ public void SetPinOnlyMode(PivPinOnlyMode pinOnlyMode, PivAlgorithm mgmtKeyAlgor // there is one) will be the same algorithm of the current one. private void SetPinOnlyMode(ReadOnlyMemory pin, PivPinOnlyMode pinOnlyMode, out int? retriesRemaining) { - ReadOnlyMemory pinToUse = pin; - - if (pin.Length == 0) + var pinToUse = pin; + if (pinToUse.Length == 0) { pinToUse = new ReadOnlyMemory(new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36 }); } - Func? userKeyCollector = KeyCollector; + var userKeyCollector = KeyCollector; using var specialKeyCollector = new SpecialKeyCollector(); try @@ -837,24 +833,23 @@ private void SetPinOnlyMode( // We might need to set a mode because it is currently set and the // caller wants a new algorithm. // Or some other reason. - PivPinOnlyMode newMode = PivPinOnlyMode.None; - - PivPinOnlyMode currentMode = GetPrintedPinProtectedStatus(specialKeyCollector, userKeyCollector); - - PinOnlyCheck pinOnlyCheck = CheckPinOnlyStatus( - currentMode, pinOnlyMode, PivPinOnlyMode.PinProtected, PivPinOnlyMode.PinProtectedUnavailable, - newAlgorithm, ref newMode); + var newPinOnlyMode = PivPinOnlyMode.None; + var currentPinOnlyMode = GetPrintedPinProtectedStatus(specialKeyCollector, userKeyCollector); + + var pinOnlyCheck = CheckPinOnlyStatus( + currentPinOnlyMode, pinOnlyMode, PivPinOnlyMode.PinProtected, PivPinOnlyMode.PinProtectedUnavailable, + newAlgorithm, ref newPinOnlyMode); using var adminData = new AdminData(); if (pinOnlyCheck == PinOnlyCheck.CanContinue) { - currentMode |= GetPinDerivedStatus( - adminData, currentMode.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, userKeyCollector); + currentPinOnlyMode |= GetPinDerivedStatus( + adminData, currentPinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected), specialKeyCollector, userKeyCollector); pinOnlyCheck = CheckPinOnlyStatus( - currentMode, pinOnlyMode, PivPinOnlyMode.PinDerived, PivPinOnlyMode.PinDerivedUnavailable, - newAlgorithm, ref newMode); + currentPinOnlyMode, pinOnlyMode, PivPinOnlyMode.PinDerived, PivPinOnlyMode.PinDerivedUnavailable, + newAlgorithm, ref newPinOnlyMode); } if (pinOnlyCheck == PinOnlyCheck.Unavailable) @@ -876,7 +871,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 (!currentPinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected) && !currentPinOnlyMode.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 @@ -912,7 +907,7 @@ private void SetPinOnlyMode( // take care of that. if (newAlgorithm) { - ClearPinOnly(currentMode, specialKeyCollector); + ClearPinOnly(currentPinOnlyMode, specialKeyCollector); if (pinOnlyMode == PivPinOnlyMode.None) { @@ -929,7 +924,7 @@ private void SetPinOnlyMode( // If it was authenticated not using PIN-only, then the currentMode // contains neither Protected nor Derived. - if (newMode.HasFlag(PivPinOnlyMode.PinDerived)) + if (newPinOnlyMode.HasFlag(PivPinOnlyMode.PinDerived)) { // This will also check to see if we need to set PinProtected // as well, but the newMode is not set yet. @@ -937,10 +932,10 @@ private void SetPinOnlyMode( // mode is Derived. We need to set Derived, but then reset // Protected to the Derived value. SetYubiKeyPinDerived( - adminData, currentMode, mgmtKeyAlgorithm, specialKeyCollector, userKeyCollector, ref newMode); + adminData, currentPinOnlyMode, mgmtKeyAlgorithm, specialKeyCollector, userKeyCollector, ref newPinOnlyMode); } - if (newMode.HasFlag(PivPinOnlyMode.PinProtected)) + if (newPinOnlyMode.HasFlag(PivPinOnlyMode.PinProtected)) { SetYubiKeyPinProtected(adminData, mgmtKeyAlgorithm, specialKeyCollector); } @@ -949,7 +944,7 @@ private void SetPinOnlyMode( // If the currentMode is UnavailablePinDerived, then don't update // AdminData. It was something other than defined value, so we're // leaving it. - if (!currentMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)) + if (!currentPinOnlyMode.HasFlag(PivPinOnlyMode.PinDerivedUnavailable)) { WriteObject(adminData); } @@ -1044,12 +1039,11 @@ private void PutEmptyData(int dataTag) { byte[] emptyObject = { 0x53, 0x00 }; - var putCmd = new PutDataCommand(dataTag, emptyObject); - PutDataResponse putRsp = Connection.SendCommand(putCmd); - - if (putRsp.Status != ResponseStatus.Success) + var command = new PutDataCommand(dataTag, emptyObject); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(putRsp.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } @@ -1086,14 +1080,15 @@ private void SetYubiKeyPinDerived( newMode |= PivPinOnlyMode.PinProtected; } - ReadOnlyMemory salt = specialKeyCollector.DeriveKeyData + var saltBytes = specialKeyCollector.DeriveKeyData (ReadOnlyMemory.Empty, mgmtKeyAlgorithm, isNewKey: true); // Call this method instead of the PivSession.Change method directly, // because this method will update the current key with the new key. specialKeyCollector.ChangeManagementKey(this, mgmtKeyAlgorithm); _ = BlockPinOrPuk(PivSlot.Puk); - adminData.SetSalt(salt); + + adminData.SetSalt(saltBytes); adminData.PukBlocked = true; } @@ -1154,7 +1149,7 @@ private bool TryGetChangePinMode(ReadOnlyMemory pin, out PivPinOnlyMode mo mode = PivPinOnlyMode.None; - Func? userKeyCollector = KeyCollector; + var userKeyCollectorFunc = KeyCollector; using var specialKeyCollector = new SpecialKeyCollector(); bool isValid = TryReadObject(out AdminData adminData); @@ -1171,7 +1166,7 @@ private bool TryGetChangePinMode(ReadOnlyMemory pin, out PivPinOnlyMode mo // In order to do that we need to verify the PIN. isValid = pin.Length switch { - 0 => specialKeyCollector.TryVerifyPinAndSave(this, userKeyCollector, out retriesRemaining), + 0 => specialKeyCollector.TryVerifyPinAndSave(this, userKeyCollectorFunc, out retriesRemaining), _ => specialKeyCollector.TrySetPin(this, pin, out retriesRemaining) }; @@ -1235,7 +1230,7 @@ private bool TryGetChangePinMode(ReadOnlyMemory pin, out PivPinOnlyMode mo finally { adminData.Dispose(); - KeyCollector = userKeyCollector; + KeyCollector = userKeyCollectorFunc; } return true; @@ -1301,7 +1296,7 @@ public void SetKeyData(ReadOnlyMemory newData, PivAlgorithm algorithm) } else { - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); do { @@ -1318,18 +1313,19 @@ 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. + // It will also set the KeyData of the MgmtKeyHolder public ReadOnlyMemory DeriveKeyData( ReadOnlyMemory pin, ReadOnlyMemory salt, PivAlgorithm algorithm) { - ReadOnlyMemory returnValue = salt; + var returnValue = salt; if (salt.Length != PinDerivedSaltLength) { byte[] saltData = new byte[PinDerivedSaltLength]; returnValue = new ReadOnlyMemory(saltData); - using RandomNumberGenerator randomObject = CryptographyProviders.RngCreator(); + using var randomObject = CryptographyProviders.RngCreator(); do { @@ -1482,23 +1478,23 @@ public void Dispose() // If generating new key data, this will reject weak keys. public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey, PivAlgorithm algorithm) { - MgmtKeyHolder dest = isNewKey ? _newKey : _currentKey; + var destinationKeyHolder = isNewKey ? _newKey : _currentKey; if (setFlag == SetKeyDataBuffer) { - dest.SetKeyData(keyData, algorithm); + destinationKeyHolder.SetKeyData(keyData, algorithm); return; } if (setFlag == SetKeyDataRandom) { - dest.SetKeyData(ReadOnlyMemory.Empty, algorithm); + destinationKeyHolder.SetKeyData(ReadOnlyMemory.Empty, algorithm); return; } - dest.SetKeyData(_defaultKey, PivAlgorithm.TripleDes); + destinationKeyHolder.SetKeyData(_defaultKey, PivAlgorithm.TripleDes); } // Derive the mgmt key from the PIN in this object, along with the @@ -1518,9 +1514,9 @@ public void SetKeyData(int setFlag, ReadOnlyMemory keyData, bool isNewKey, // result if a salt is given. public ReadOnlyMemory DeriveKeyData(ReadOnlyMemory salt, PivAlgorithm algorithm, bool isNewKey) { - MgmtKeyHolder dest = isNewKey ? _newKey : _currentKey; + var destinationKeyHolder = isNewKey ? _newKey : _currentKey; - return dest.DeriveKeyData(_pinMemory.Slice(start: 0, _pinLength), salt, algorithm); + return destinationKeyHolder.DeriveKeyData(_pinMemory.Slice(start: 0, _pinLength), salt, algorithm); } // Change the management key from what is in current to what is in diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs index 121a2b2a..cad5eddc 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Piv/PivSession.cs @@ -380,10 +380,10 @@ public PivMetadata GetMetadata(byte slotNumber) ExceptionMessages.NotSupportedByYubiKeyVersion)); } - var metadataCommand = new GetMetadataCommand(slotNumber); - GetMetadataResponse metadataResponse = Connection.SendCommand(metadataCommand); + var command = new GetMetadataCommand(slotNumber); + var response = Connection.SendCommand(command); - return metadataResponse.GetData(); + return response.GetData(); } /// @@ -477,10 +477,9 @@ public void ResetApplication() TryBlock(PivSlot.Pin); TryBlock(PivSlot.Puk); - var resetCommand = new ResetPivCommand(); - ResetPivResponse resetResponse = Connection.SendCommand(resetCommand); - - if (resetResponse.Status != ResponseStatus.Success) + var command = new ResetPivCommand(); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { throw new SecurityException( string.Format( @@ -532,9 +531,9 @@ public void MoveKey(byte sourceSlot, byte destinationSlot) } _log.LogDebug("Moving key from {SourceSlot} to {DestinationSlot}", sourceSlot, destinationSlot); + var command = new MoveKeyCommand(sourceSlot, destinationSlot); - MoveKeyResponse response = Connection.SendCommand(command); - + var response = Connection.SendCommand(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); @@ -580,8 +579,9 @@ public void DeleteKey(byte slotToClear) } _log.LogDebug("Deleting key at slot {TargetSlot}", slotToClear); + var command = new DeleteKeyCommand(slotToClear); - DeleteKeyResponse response = Connection.SendCommand(command); + var response = Connection.SendCommand(command); bool unsuccessfulStatus = response.Status != ResponseStatus.Success && @@ -627,15 +627,14 @@ private bool BlockPinOrPuk(byte slotNumber) 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }; - var changeCommand = new ChangeReferenceDataCommand(slotNumber, currentValue, newValue); - ChangeReferenceDataResponse changeResponse = Connection.SendCommand(changeCommand); - - if (changeResponse.Status == ResponseStatus.Failed) + var command = new ChangeReferenceDataCommand(slotNumber, currentValue, newValue); + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Failed) { return false; } - retriesRemaining = changeResponse.GetData() ?? 1; + retriesRemaining = response.GetData() ?? 1; } while (retriesRemaining > 0); @@ -662,13 +661,13 @@ private void UpdateManagementKey(IYubiKeyDevice yubiKey) => private PivAlgorithm GetManagementKeyAlgorithm() { - GetMetadataResponse response = Connection.SendCommand(new GetMetadataCommand(PivSlot.Management)); + var response = Connection.SendCommand(new GetMetadataCommand(PivSlot.Management)); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); } - PivMetadata metadata = response.GetData(); + var metadata = response.GetData(); return metadata.Algorithm; } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs index 975f27ce..384154a7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/ChannelMac.cs @@ -31,14 +31,14 @@ public static (CommandApdu macdApdu, byte[] newMacChainingValue) MacApdu(Command throw new ArgumentException(ExceptionMessages.UnknownScp03Error, nameof(macChainingValue)); } - CommandApdu apduWithLongerLen = AddDataToApdu(apdu, new byte[8]); + var apduWithLongerLen = AddDataToApdu(apdu, new byte[8]); byte[] apduBytesWithZeroMac = ApduToBytes(apduWithLongerLen); byte[] apduBytes = apduBytesWithZeroMac.Take(apduBytesWithZeroMac.Length - 8).ToArray(); byte[] macInp = new byte[16 + apduBytes.Length]; macChainingValue.CopyTo(macInp, 0); apduBytes.CopyTo(macInp, 16); - using ICmacPrimitives cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); + using var cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); cmacObj.CmacInit(macKey); cmacObj.CmacUpdate(macInp); cmacObj.CmacFinal(macChainingValue); @@ -68,13 +68,13 @@ public static void VerifyRmac(byte[] response, byte[] rmacKey, byte[] macChainin macInp[16 + respDataLen] = SW1Constants.Success; macInp[16 + respDataLen + 1] = SWConstants.Success & 0xFF; - using ICmacPrimitives cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); + using var cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); byte[] cmac = new byte[16]; cmacObj.CmacInit(rmacKey); cmacObj.CmacUpdate(macInp); cmacObj.CmacFinal(cmac); - Span calculatedRmac = cmac.AsSpan(0, 8); - + + var calculatedRmac = cmac.AsSpan(0, 8); if (!CryptographicOperations.FixedTimeEquals(recvdRmac, calculatedRmac)) { throw new SecureChannelException(ExceptionMessages.IncorrectRmac); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/InitializeUpdateResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/InitializeUpdateResponse.cs index c400e5a9..bc62e79e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/InitializeUpdateResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Commands/InitializeUpdateResponse.cs @@ -44,7 +44,7 @@ public InitializeUpdateResponse(ResponseApdu responseApdu) : throw new ArgumentException(ExceptionMessages.IncorrectInitializeUpdateResponseData, nameof(responseApdu)); } - ReadOnlySpan responseData = responseApdu.Data.Span; + var responseData = responseApdu.Data.Span; DiversificationData = new ReadOnlyCollection(responseData[0..10].ToArray()); KeyInfo = new ReadOnlyCollection(responseData[10..13].ToArray()); CardChallenge = new ReadOnlyCollection(responseData[13..21].ToArray()); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs index 2e697a26..cf3c5a76 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Derivation.cs @@ -58,7 +58,7 @@ public static byte[] Derive( cardChallenge.CopyTo(macInp, 24); byte[] cmac = new byte[16]; - using ICmacPrimitives cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); + using var cmacObj = CryptographyProviders.CmacPrimitivesCreator(CmacBlockCipherAlgorithm.Aes128); cmacObj.CmacInit(kdfKey); cmacObj.CmacUpdate(macInp); cmacObj.CmacFinal(cmac); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs index a06f88d3..6e2cb1b6 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Connection.cs @@ -38,7 +38,7 @@ public Scp03Connection( public Scp03Connection(ISmartCardDevice smartCardDevice, byte[] applicationId, StaticKeys scp03Keys) : base(smartCardDevice, YubiKeyApplication.Unknown, applicationId) { - YubiKeyApplication setError = YubiKeyApplication.Unknown; + var setError = YubiKeyApplication.Unknown; if (applicationId.SequenceEqual(YubiKeyApplication.Fido2.GetIso7816ApplicationId())) { setError = YubiKeyApplication.Fido2; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs index 16072b12..a2944787 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/Scp03/Scp03Session.cs @@ -250,19 +250,20 @@ public void PutKeySet(StaticKeys newKeySet) { throw new ArgumentNullException(nameof(newKeySet)); } - var cmd = new PutKeyCommand(Connection.GetScp03Keys(), newKeySet); - PutKeyResponse rsp = Connection.SendCommand(cmd); - if (rsp.Status != ResponseStatus.Success) + + var command = new PutKeyCommand(Connection.GetScp03Keys(), newKeySet); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { throw new SecureChannelException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.YubiKeyOperationFailed, - rsp.StatusMessage)); + response.StatusMessage)); } - ReadOnlyMemory checksum = rsp.GetData(); - if (!CryptographicOperations.FixedTimeEquals(checksum.Span, cmd.ExpectedChecksum.Span)) + var checksum = response.GetData(); + if (!CryptographicOperations.FixedTimeEquals(checksum.Span, command.ExpectedChecksum.Span)) { throw new SecureChannelException(ExceptionMessages.ChecksumError); } @@ -290,17 +291,17 @@ public void PutKeySet(StaticKeys newKeySet) /// public void DeleteKeySet(byte keyVersionNumber, bool isLastKey = false) { - _log.LogInformation("Delete an SCP03 key set from a YubiKey."); + _log.LogInformation("Deleting an SCP03 key set from a YubiKey."); - var cmd = new DeleteKeyCommand(keyVersionNumber, isLastKey); - Scp03Response rsp = Connection.SendCommand(cmd); - if (rsp.Status != ResponseStatus.Success) + var command = new DeleteKeyCommand(keyVersionNumber, isLastKey); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { throw new SecureChannelException( string.Format( CultureInfo.CurrentCulture, ExceptionMessages.YubiKeyOperationFailed, - rsp.StatusMessage)); + response.StatusMessage)); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardConnection.cs b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardConnection.cs index f9590baa..e0c5d778 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardConnection.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardConnection.cs @@ -117,8 +117,8 @@ private void SelectApplication() }; _log.LogInformation("Selecting smart card application [{AID}]", Hex.BytesToHex(_applicationId ?? _yubiKeyApplication.GetIso7816ApplicationId())); - ResponseApdu responseApdu = _smartCardConnection.Transmit(selectApplicationCommand.CreateCommandApdu()); - + + var responseApdu = _smartCardConnection.Transmit(selectApplicationCommand.CreateCommandApdu()); if (responseApdu.SW != SWConstants.Success) { throw new ApduException( @@ -131,20 +131,20 @@ private void SelectApplication() }; } - ISelectApplicationResponse? response = selectApplicationCommand.CreateResponseForApdu(responseApdu); + var response = selectApplicationCommand.CreateResponseForApdu(responseApdu); SelectApplicationData = response.GetData(); } public TResponse SendCommand(IYubiKeyCommand yubiKeyCommand) where TResponse : IYubiKeyResponse { - using (IDisposable _ = _smartCardConnection.BeginTransaction(out bool cardWasReset)) + using (var _ = _smartCardConnection.BeginTransaction(out bool cardWasReset)) { if (cardWasReset) { SelectApplication(); } - ResponseApdu responseApdu = _apduPipeline.Invoke( + var responseApdu = _apduPipeline.Invoke( yubiKeyCommand.CreateCommandApdu(), yubiKeyCommand.GetType(), typeof(TResponse)); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs index 26ee4d31..33492d0e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/SmartCardDeviceInfoFactory.cs @@ -27,7 +27,7 @@ internal static class SmartCardDeviceInfoFactory public static YubiKeyDeviceInfo GetDeviceInfo( ISmartCardDevice device) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); if (!device.IsYubicoDevice()) { @@ -36,7 +36,7 @@ public static YubiKeyDeviceInfo GetDeviceInfo( log.LogInformation("Getting device info for smart card {Device}.", device); - if (!TryGetDeviceInfoFromManagement(device, out YubiKeyDeviceInfo? deviceInfo)) + if (!TryGetDeviceInfoFromManagement(device, out var deviceInfo)) { deviceInfo = new YubiKeyDeviceInfo(); } @@ -52,7 +52,7 @@ public static YubiKeyDeviceInfo GetDeviceInfo( } if (deviceInfo.FirmwareVersion == defaultDeviceInfo.FirmwareVersion - && TryGetFirmwareVersionFromOtp(device, out FirmwareVersion? firmwareVersion)) + && TryGetFirmwareVersionFromOtp(device, out var firmwareVersion)) { deviceInfo.FirmwareVersion = firmwareVersion; } @@ -86,7 +86,7 @@ private static bool TryGetDeviceInfoFromManagement( ISmartCardDevice device, [MaybeNullWhen(returnValue: false)] out YubiKeyDeviceInfo deviceInfo) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); try { @@ -121,15 +121,14 @@ private static bool TryGetFirmwareVersionFromOtp( ISmartCardDevice device, [MaybeNullWhen(returnValue: false)] out FirmwareVersion firmwareVersion) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); try { log.LogInformation("Attempting to read firmware version through OTP."); using var connection = new SmartCardConnection(device, YubiKeyApplication.Otp); - Otp.Commands.ReadStatusResponse response = - connection.SendCommand(new Otp.Commands.ReadStatusCommand()); + var response = connection.SendCommand(new Otp.Commands.ReadStatusCommand()); if (response.Status == ResponseStatus.Success) { @@ -164,14 +163,14 @@ private static bool TryGetFirmwareVersionFromPiv( ISmartCardDevice device, [MaybeNullWhen(returnValue: false)] out FirmwareVersion firmwareVersion) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); try { log.LogInformation("Attempting to read firmware version through the PIV application."); using var connection = new SmartCardConnection(device, YubiKeyApplication.Piv); - Piv.Commands.VersionResponse response = connection.SendCommand(new Piv.Commands.VersionCommand()); + var response = connection.SendCommand(new Piv.Commands.VersionCommand()); if (response.Status == ResponseStatus.Success) { @@ -202,16 +201,14 @@ private static bool TryGetSerialNumberFromOtp( ISmartCardDevice device, out int? serialNumber) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); try { log.LogInformation("Attempting to read serial number through the OTP application."); using var connection = new SmartCardConnection(device, YubiKeyApplication.Otp); - Otp.Commands.GetSerialNumberResponse response = - connection.SendCommand(new Otp.Commands.GetSerialNumberCommand()); - + var response = connection.SendCommand(new Otp.Commands.GetSerialNumberCommand()); if (response.Status == ResponseStatus.Success) { serialNumber = response.GetData(); @@ -246,16 +243,14 @@ private static bool TryGetSerialNumberFromPiv( ISmartCardDevice device, out int? serialNumber) { - ILogger log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); + var log = Log.GetLogger(typeof(SmartCardDeviceInfoFactory).FullName!); try { log.LogInformation("Attempting to read serial number through the PIV application."); using var connection = new SmartCardConnection(device, YubiKeyApplication.Piv); - Piv.Commands.GetSerialNumberResponse response = - connection.SendCommand(new Piv.Commands.GetSerialNumberCommand()); - + var response = connection.SendCommand(new Piv.Commands.GetSerialNumberCommand()); if (response.Status == ResponseStatus.Success) { serialNumber = response.GetData(); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs index b683d860..da23d5b7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/TouchFingerprintTask.cs @@ -154,8 +154,9 @@ 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.EnrollFingerprint : KeyEntryRequest.Release; + var request = keyEntryData.Request == KeyEntryRequest.EnrollFingerprint + ? KeyEntryRequest.EnrollFingerprint + : KeyEntryRequest.Release; lock (_updateLock) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetDeviceInfoResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetDeviceInfoResponse.cs index 116a8314..73d9b8b7 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetDeviceInfoResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetDeviceInfoResponse.cs @@ -59,7 +59,7 @@ public YubiKeyDeviceInfo GetData() }; } - if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out YubiKeyDeviceInfo? deviceInfo)) + if (!YubiKeyDeviceInfo.TryCreateFromResponseData(ResponseApdu.Data, out var deviceInfo)) { throw new MalformedYubiKeyResponseException { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetProtocolVersionResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetProtocolVersionResponse.cs index 5262dbbb..2057ddc2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetProtocolVersionResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/Commands/GetProtocolVersionResponse.cs @@ -63,7 +63,7 @@ public string GetData() throw new InvalidOperationException(StatusMessage); } - ReadOnlySpan responseApduData = ResponseApdu.Data.Span; + var responseApduData = ResponseApdu.Data.Span; return Encoding.ASCII.GetString(responseApduData.ToArray()); } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs index 59ed3e77..4ec6f5d0 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/RegistrationData.cs @@ -138,13 +138,13 @@ public RegistrationData(ReadOnlyMemory encodedResponse) int certLength = 1; if (encodedResponse.Length > MinEncodedLength) { - if (encodedResponse.Span[MsgReservedOffset] == MsgReservedValue - && encodedResponse.Span[MsgKeyHandleOffset] == KeyHandleLength - && encodedResponse.Span[MsgPublicKeyOffset] == PublicKeyTag) + if (encodedResponse.Span[MsgReservedOffset] == MsgReservedValue && + encodedResponse.Span[MsgKeyHandleOffset] == KeyHandleLength && + encodedResponse.Span[MsgPublicKeyOffset] == PublicKeyTag) { - ReadOnlyMemory certAndSig = encodedResponse.Slice(MsgCertOffset); - var tlvReader = new TlvReader(certAndSig); - if (tlvReader.TryReadEncoded(out ReadOnlyMemory cert, CertTag)) + var certAndSignatureBytes = encodedResponse.Slice(MsgCertOffset); + var tlvReader = new TlvReader(certAndSignatureBytes); + if (tlvReader.TryReadEncoded(out var cert, CertTag)) { certLength = cert.Length; isValid = true; diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs index 0fc2a260..db3091c2 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.Pin.cs @@ -107,7 +107,7 @@ public void SetPin() public bool TrySetPin() { _log.LogInformation("Try to set the U2F PIN using the KeyCollector."); - Func keyCollector = EnsureKeyCollector(); + var keyCollectorFunc = EnsureKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -116,7 +116,7 @@ public bool TrySetPin() try { - while (keyCollector(keyEntryData)) + while (keyCollectorFunc(keyEntryData)) { if (TrySetPin(keyEntryData.GetCurrentValue())) { @@ -131,7 +131,7 @@ public bool TrySetPin() keyEntryData.Clear(); keyEntryData.Request = KeyEntryRequest.Release; - _ = keyCollector(keyEntryData); + _ = keyCollectorFunc(keyEntryData); } return false; @@ -164,10 +164,10 @@ public bool TrySetPin() public bool TrySetPin(ReadOnlyMemory pin) { _log.LogInformation("Try to set the U2F PIN using a provided value."); - var setCommand = new SetPinCommand(ReadOnlyMemory.Empty, pin); - SetPinResponse setResponse = Connection.SendCommand(setCommand); - - return setResponse.StatusWord switch + + var command = new SetPinCommand(ReadOnlyMemory.Empty, pin); + var response = Connection.SendCommand(command); + return response.StatusWord switch { SWConstants.Success => true, SWConstants.VerifyFail => throw new SecurityException( @@ -285,7 +285,7 @@ public void ChangePin() public bool TryChangePin() { _log.LogInformation("Try to change the U2F PIN using the KeyCollector."); - Func keyCollector = EnsureKeyCollector(); + var keyCollectorFunc = EnsureKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -294,7 +294,7 @@ public bool TryChangePin() try { - while (keyCollector(keyEntryData)) + while (keyCollectorFunc(keyEntryData)) { if (TryChangePin(keyEntryData.GetCurrentValue(), keyEntryData.GetNewValue())) { @@ -309,7 +309,7 @@ public bool TryChangePin() keyEntryData.Clear(); keyEntryData.Request = KeyEntryRequest.Release; - _ = keyCollector(keyEntryData); + _ = keyCollectorFunc(keyEntryData); } return false; @@ -337,10 +337,9 @@ public bool TryChangePin() public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory newPin) { _log.LogInformation("Try to change the U2F PIN using provided values."); - var setCommand = new SetPinCommand(currentPin, newPin); - SetPinResponse setResponse = Connection.SendCommand(setCommand); - - return setResponse.StatusWord switch + var command = new SetPinCommand(currentPin, newPin); + var response = Connection.SendCommand(command); + return response.StatusWord switch { SWConstants.Success => true, SWConstants.AuthenticationMethodBlocked => throw new SecurityException( @@ -434,7 +433,7 @@ public bool TryChangePin(ReadOnlyMemory currentPin, ReadOnlyMemory n private bool CommonVerifyPin(bool throwOnCancel) { _log.LogInformation("Verify the U2F PIN using the KeyCollector."); - Func keyCollector = EnsureKeyCollector(); + var keyCollectorFunc = EnsureKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -443,7 +442,7 @@ private bool CommonVerifyPin(bool throwOnCancel) try { - while (keyCollector(keyEntryData)) + while (keyCollectorFunc(keyEntryData)) { if (TryVerifyPin(keyEntryData.GetCurrentValue())) { @@ -458,7 +457,7 @@ private bool CommonVerifyPin(bool throwOnCancel) keyEntryData.Clear(); keyEntryData.Request = KeyEntryRequest.Release; - _ = keyCollector(keyEntryData); + _ = keyCollectorFunc(keyEntryData); } if (throwOnCancel) @@ -494,10 +493,10 @@ private bool CommonVerifyPin(bool throwOnCancel) public bool TryVerifyPin(ReadOnlyMemory pin) { _log.LogInformation("Try to verify the U2F PIN using a provided value."); - var verifyCommand = new VerifyPinCommand(pin); - VerifyPinResponse verifyResponse = Connection.SendCommand(verifyCommand); - - return verifyResponse.StatusWord switch + + var command = new VerifyPinCommand(pin); + var response = Connection.SendCommand(command); + return response.StatusWord switch { SWConstants.Success => true, SWConstants.AuthenticationMethodBlocked => throw new SecurityException( diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs index 61be105c..55e8670c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/U2f/U2fSession.cs @@ -315,7 +315,7 @@ public RegistrationData Register(ReadOnlyMemory applicationId, TimeSpan timeout) { _log.LogInformation("Register a new U2F credential."); - RegisterResponse response = CommonRegister(applicationId, clientDataHash, timeout, true); + var response = CommonRegister(applicationId, clientDataHash, timeout, true); // If everything worked, this will return the correct result. If // there was an error, this will throw an exception. @@ -423,7 +423,7 @@ public bool TryRegister(ReadOnlyMemory applicationId, [MaybeNullWhen(returnValue: false)] out RegistrationData registrationData) { _log.LogInformation("Try to register a new U2F credential."); - RegisterResponse response = CommonRegister(applicationId, clientDataHash, timeout, false); + var response = CommonRegister(applicationId, clientDataHash, timeout, false); if (response.Status == ResponseStatus.Success) { @@ -450,10 +450,10 @@ private RegisterResponse CommonRegister(ReadOnlyMemory applicationId, Task? touchMessageTask = null; var keyEntryData = new KeyEntryData(); - TimeSpan timeoutToUse = GetTimeoutToUse(timeout); + var timeoutToUseTimeSpan = GetTimeoutToUse(timeout); var command = new RegisterCommand(applicationId, clientDataHash); - RegisterResponse response = Connection.SendCommand(command); + var response = Connection.SendCommand(command); // This should only apply to FIPS series devices. // This response happens if the PIN is not verified. @@ -491,8 +491,8 @@ private RegisterResponse CommonRegister(ReadOnlyMemory applicationId, Thread.Sleep(100); response = Connection.SendCommand(command); } - while (response.Status == ResponseStatus.ConditionsNotSatisfied - && timer.Elapsed < timeoutToUse); + while (response.Status == ResponseStatus.ConditionsNotSatisfied && + timer.Elapsed < timeoutToUseTimeSpan); // Did we break out because of timeout or because the // response was something other than ConditionsNotSatisfied. @@ -577,7 +577,7 @@ public bool VerifyKeyHandle(ReadOnlyMemory applicationId, var command = new AuthenticateCommand(U2fAuthenticationType.CheckOnly, applicationId, clientDataHash, keyHandle); - AuthenticateResponse response = Connection.SendCommand(command); + var response = Connection.SendCommand(command); // The standard specifies that if the key handle matches, the token // must respond with the test-of-user-presence error. If the key @@ -697,8 +697,7 @@ public AuthenticationData Authenticate(ReadOnlyMemory applicationId, { _log.LogInformation("Authenticate a U2F credential."); - AuthenticateResponse response = CommonAuthenticate( - applicationId, clientDataHash, keyHandle, timeout, requireProofOfPresence); + var response = CommonAuthenticate(applicationId, clientDataHash, keyHandle, timeout, requireProofOfPresence); // If everything worked, this will return the correct result. If // there was an error, this will throw an exception. @@ -771,9 +770,7 @@ public bool TryAuthenticate(ReadOnlyMemory applicationId, { _log.LogInformation("Try to authenticate a U2F credential."); - AuthenticateResponse response = CommonAuthenticate( - applicationId, clientDataHash, keyHandle, timeout, requireProofOfPresence); - + var response = CommonAuthenticate(applicationId, clientDataHash, keyHandle, timeout, requireProofOfPresence); if (response.Status == ResponseStatus.Success) { authenticationData = response.GetData(); @@ -799,15 +796,14 @@ private AuthenticateResponse CommonAuthenticate(ReadOnlyMemory application Task? touchMessageTask = null; var keyEntryData = new KeyEntryData(); - TimeSpan timeoutToUse = GetTimeoutToUse(timeout); + var timeoutToUseTimeSpan = GetTimeoutToUse(timeout); - U2fAuthenticationType authType = requireProofOfPresence + var authType = requireProofOfPresence ? U2fAuthenticationType.EnforceUserPresence : U2fAuthenticationType.DontEnforceUserPresence; var command = new AuthenticateCommand(authType, applicationId, clientDataHash, keyHandle); - AuthenticateResponse response = Connection.SendCommand(command); - + var response = Connection.SendCommand(command); if (response.Status == ResponseStatus.ConditionsNotSatisfied) { // On a separate thread, call the KeyCollector to announce we @@ -829,8 +825,8 @@ private AuthenticateResponse CommonAuthenticate(ReadOnlyMemory application Thread.Sleep(100); response = Connection.SendCommand(command); } - while (response.Status == ResponseStatus.ConditionsNotSatisfied - && timer.Elapsed < timeoutToUse); + while (response.Status == ResponseStatus.ConditionsNotSatisfied && + timer.Elapsed < timeoutToUseTimeSpan); // Did we break out because of timeout or because the // response was something other than ConditionsNotSatisfied. @@ -886,7 +882,7 @@ private AuthenticateResponse CommonAuthenticate(ReadOnlyMemory application /// public static byte[] EncodeAndHashString(string data) { - using (SHA256 sha = CryptographyProviders.Sha256Creator()) + using (var sha = CryptographyProviders.Sha256Creator()) { byte[] encodedString = Encoding.UTF8.GetBytes(data); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommand.cs index b3f360d3..b89956c1 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommand.cs @@ -127,7 +127,7 @@ public AddCredentialResponse CreateResponseForApdu(ResponseApdu responseApdu) => /// private byte[] BuildDataField() { - TlvWriter tlvWriter = new TlvWriter(); + var tlvWriter = new TlvWriter(); tlvWriter.WriteValue(DataTagConstants.ManagementKey, _managementKey.Span); tlvWriter.WriteString(DataTagConstants.Label, _credentialWithSecrets.Label, Encoding.UTF8); @@ -139,10 +139,10 @@ private byte[] BuildDataField() tlvWriter.WriteByte(DataTagConstants.Touch, _credentialWithSecrets.TouchRequired ? (byte)1 : (byte)0); - byte[] returnValue = tlvWriter.Encode(); + byte[] tlvBytes = tlvWriter.Encode(); tlvWriter.Clear(); - return returnValue; + return tlvBytes; } /// diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommand.cs index c3e07309..217e919d 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommand.cs @@ -128,14 +128,14 @@ public ChangeManagementKeyResponse CreateResponseForApdu(ResponseApdu responseAp /// private byte[] BuildDataField() { - TlvWriter tlvWriter = new TlvWriter(); + var tlvWriter = new TlvWriter(); tlvWriter.WriteValue(DataTagConstants.ManagementKey, _currentManagementKey.Span); tlvWriter.WriteValue(DataTagConstants.ManagementKey, _newManagementKey.Span); - byte[] returnValue = tlvWriter.Encode(); + byte[] tlvBytes = tlvWriter.Encode(); tlvWriter.Clear(); - return returnValue; + return tlvBytes; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommand.cs index 559cde47..37a989e8 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommand.cs @@ -127,15 +127,15 @@ public DeleteCredentialResponse CreateResponseForApdu(ResponseApdu responseApdu) private byte[] BuildDataField() { - TlvWriter tlvWriter = new TlvWriter(); + var tlvWriter = new TlvWriter(); tlvWriter.WriteValue(DataTagConstants.ManagementKey, _managementKey.Span); tlvWriter.WriteString(DataTagConstants.Label, Label, Encoding.UTF8); - byte[] returnValue = tlvWriter.Encode(); + byte[] tlvBytes = tlvWriter.Encode(); tlvWriter.Clear(); - return returnValue; + return tlvBytes; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommand.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommand.cs index 05f7b035..5a5c0164 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommand.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommand.cs @@ -176,7 +176,7 @@ public GetAes128SessionKeysResponse CreateResponseForApdu(ResponseApdu responseA /// private byte[] BuildDataField() { - TlvWriter tlvWriter = new TlvWriter(); + var tlvWriter = new TlvWriter(); tlvWriter.WriteString(DataTagConstants.Label, CredentialLabel, Encoding.UTF8); @@ -187,10 +187,10 @@ private byte[] BuildDataField() tlvWriter.WriteValue(DataTagConstants.Password, _credentialPassword.Span); - byte[] returnValue = tlvWriter.Encode(); + byte[] tlvBytes = tlvWriter.Encode(); tlvWriter.Clear(); - return returnValue; + return tlvBytes; } } } diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponse.cs index f8d2bf32..accc570a 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponse.cs @@ -97,7 +97,7 @@ public SessionKeys GetData() throw new MalformedYubiKeyResponseException(); } - SessionKeys keys = new SessionKeys( + var keys = new SessionKeys( ResponseApdu.Data.Slice(encStart, keyLength), ResponseApdu.Data.Slice(macStart, keyLength), ResponseApdu.Data.Slice(rmacStart, keyLength)); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponse.cs index 1762bc45..4c3bcf16 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponse.cs @@ -35,9 +35,8 @@ public ApplicationVersion GetData() throw new InvalidOperationException(StatusMessage); } - ReadOnlySpan versionData = ResponseApdu.Data.Span; - - ApplicationVersion version = new ApplicationVersion() + var versionData = ResponseApdu.Data.Span; + var version = new ApplicationVersion { Major = versionData[0], Minor = versionData[1], diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs index 10629995..57f5e044 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponse.cs @@ -69,8 +69,7 @@ public List GetData() throw new InvalidOperationException(StatusMessage); } - List credentialRetryPairs = new List(); - + var credentialRetryPairs = new List(); var tlvReader = new TlvReader(ResponseApdu.Data); // Parse data by iterating over each LabelList element, parsing it into a @@ -78,7 +77,6 @@ public List GetData() while (tlvReader.HasData) { int nextTagValue = tlvReader.PeekTag(); - if (nextTagValue != DataTagConstants.LabelList) { throw new MalformedYubiKeyResponseException( @@ -88,18 +86,17 @@ public List GetData() nextTagValue)); } - ReadOnlySpan credentialRetryElement = - tlvReader.ReadValue(DataTagConstants.LabelList).Span; + var credentialRetryElement = tlvReader.ReadValue(DataTagConstants.LabelList).Span; // Check that it's formatted correctly - if (credentialRetryElement.Length < MinElementSize - || credentialRetryElement.Length > MaxElementSize) + if (credentialRetryElement.Length < MinElementSize || + credentialRetryElement.Length > MaxElementSize) { throw new MalformedYubiKeyResponseException( ExceptionMessages.InvalidCredentialRetryDataLength); } - Credential credential = new Credential( + var credential = new Credential( (CryptographicKeyType)credentialRetryElement[CryptoKeyTypeIndex], Encoding.UTF8.GetString(credentialRetryElement[LabelRange].ToArray()), credentialRetryElement[TouchIndex] != 0); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs index 93d2451d..1b7c5e86 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.Credential.cs @@ -109,28 +109,21 @@ public bool TryAddCredential(ReadOnlyMemory managementKey, { managementKeyRetries = null; - AddCredentialCommand addCredCmd = - new AddCredentialCommand(managementKey, credentialWithSecrets); - - AddCredentialResponse addCredRsp = Connection.SendCommand(addCredCmd); - - if (addCredRsp.Status != ResponseStatus.Success) + var command = new AddCredentialCommand(managementKey, credentialWithSecrets); + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { - if (addCredRsp.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { - managementKeyRetries = addCredRsp.RetriesRemaining!; + managementKeyRetries = response.RetriesRemaining!; return false; } - else - { - throw new InvalidOperationException(addCredRsp.StatusMessage); - } - } - else - { - return true; + + throw new InvalidOperationException(response.StatusMessage); } + + return true; } /// @@ -198,7 +191,7 @@ public bool TryAddCredential(ReadOnlyMemory managementKey, /// public bool TryAddCredential(CredentialWithSecrets credentialWithSecrets) { - Func? keyCollector = GetKeyCollector(); + var keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -320,7 +313,7 @@ public bool TryAddCredential(CredentialWithSecrets credentialWithSecrets) /// public bool TryDeleteCredential(string label) { - Func? keyCollector = GetKeyCollector(); + var keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -446,10 +439,10 @@ public bool TryDeleteCredential(ReadOnlyMemory managementKey, { managementKeyRetries = null; - DeleteCredentialCommand deleteCredCmd = + var deleteCredCmd = new DeleteCredentialCommand(managementKey, label); - DeleteCredentialResponse deleteCredRsp = + var deleteCredRsp = Connection.SendCommand(deleteCredCmd); if (deleteCredRsp.Status != ResponseStatus.Success) @@ -486,7 +479,7 @@ public bool TryDeleteCredential(ReadOnlyMemory managementKey, /// public IReadOnlyList ListCredentials() { - ListCredentialsResponse listCredsRsp = + var listCredsRsp = Connection.SendCommand(new ListCredentialsCommand()); if (listCredsRsp.Status != ResponseStatus.Success) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs index b4b37cda..8ebdbd1c 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.ManagementKey.cs @@ -45,15 +45,13 @@ public partial class YubiHsmAuthSession /// public int GetManagementKeyRetries() { - GetManagementKeyRetriesResponse retryCountResponse = - Connection.SendCommand(new GetManagementKeyRetriesCommand()); - - if (retryCountResponse.Status != ResponseStatus.Success) + var response = Connection.SendCommand(new GetManagementKeyRetriesCommand()); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(retryCountResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } - return retryCountResponse.GetData(); + return response.GetData(); } /// @@ -131,7 +129,7 @@ public int GetManagementKeyRetries() /// public bool TryChangeManagementKey() { - Func keyCollector = GetKeyCollector(); + var keyCollector = GetKeyCollector(); var keyEntryData = new KeyEntryData { @@ -237,7 +235,7 @@ public bool TryChangeManagementKey( var changeMgmtKeyCmd = new ChangeManagementKeyCommand(currentManagementKey, newManagementKey); - ChangeManagementKeyResponse changeMgmtKeyRsp = + var changeMgmtKeyRsp = Connection.SendCommand(changeMgmtKeyCmd); if (changeMgmtKeyRsp.Status == ResponseStatus.Success) diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs index 738fe523..2419493f 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.SessionKeys.cs @@ -101,36 +101,32 @@ public SessionKeys GetAes128SessionKeys(string credentialLabel, ReadOnlyMemory hostChallenge, ReadOnlyMemory hsmDeviceChallenge) { - GetAes128SessionKeysCommand getKeysCmd = - new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( credentialLabel, credentialPassword, hostChallenge, hsmDeviceChallenge); - GetAes128SessionKeysResponse getKeysRsp = - Connection.SendCommand(getKeysCmd); - - if (getKeysRsp.Status != ResponseStatus.Success) + var response = Connection.SendCommand(command); + if (response.Status != ResponseStatus.Success) { - if (getKeysRsp.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { throw new SecurityException(string.Format( CultureInfo.CurrentCulture, ExceptionMessages.YubiHsmAuthCredPasswordAuthFailed, - getKeysRsp.RetriesRemaining)); + response.RetriesRemaining)); } - else if (getKeysRsp.Status == ResponseStatus.RetryWithTouch) + + if (response.Status == ResponseStatus.RetryWithTouch) { throw new TimeoutException(ExceptionMessages.YubiHsmAuthTouchTimeout); } - else - { - throw new InvalidOperationException(getKeysRsp.StatusMessage); - } + + throw new InvalidOperationException(response.StatusMessage); } - return getKeysRsp.GetData(); + return response.GetData(); } /// @@ -234,7 +230,7 @@ public bool TryGetAes128SessionKeys(string credentialLabel, .Single(c => c.Credential.Label == credentialLabel) .Credential.TouchRequired; - Func? keyCollector = GetKeyCollector(); + var keyCollectorFunc = GetKeyCollector(); var keyEntryData = new KeyEntryData() { @@ -243,9 +239,9 @@ public bool TryGetAes128SessionKeys(string credentialLabel, try { - while (keyCollector(keyEntryData)) + while (keyCollectorFunc(keyEntryData)) { - var getKeysCmd = + var command = new GetAes128SessionKeysCommand( credentialLabel, keyEntryData.GetCurrentValue(), @@ -258,27 +254,25 @@ public bool TryGetAes128SessionKeys(string credentialLabel, // new thread and send a touch request to the key collector keyEntryData.Request = KeyEntryRequest.TouchRequest; - _ = Task.Run(() => keyCollector(keyEntryData)); + _ = Task.Run(() => keyCollectorFunc(keyEntryData)); // We ignore the return value, regardless. So no need to wait. } - GetAes128SessionKeysResponse getKeysRsp = - Connection.SendCommand(getKeysCmd); - - if (getKeysRsp.Status == ResponseStatus.Success) + var response = Connection.SendCommand(command); + if (response.Status == ResponseStatus.Success) { - sessionKeys = getKeysRsp.GetData(); + sessionKeys = response.GetData(); return true; } // Handle failure cases - if (getKeysRsp.Status == ResponseStatus.AuthenticationRequired) + if (response.Status == ResponseStatus.AuthenticationRequired) { // Incorrect credential password - retry auth (if possible) - if (getKeysRsp.RetriesRemaining == 0) + if (response.RetriesRemaining == 0) { throw new SecurityException( string.Format( @@ -288,11 +282,11 @@ public bool TryGetAes128SessionKeys(string credentialLabel, keyEntryData.Request = KeyEntryRequest.AuthenticateYubiHsmAuthCredentialPassword; keyEntryData.IsRetry = true; - keyEntryData.RetriesRemaining = getKeysRsp.RetriesRemaining; + keyEntryData.RetriesRemaining = response.RetriesRemaining; continue; } - else if (getKeysRsp.Status == ResponseStatus.RetryWithTouch) + else if (response.Status == ResponseStatus.RetryWithTouch) { // Touch was expected throw new TimeoutException(ExceptionMessages.YubiHsmAuthTouchTimeout); @@ -300,7 +294,7 @@ public bool TryGetAes128SessionKeys(string credentialLabel, else { // Other error - throw new InvalidOperationException(getKeysRsp.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } } @@ -309,7 +303,7 @@ public bool TryGetAes128SessionKeys(string credentialLabel, keyEntryData.Clear(); keyEntryData.Request = KeyEntryRequest.Release; - _ = keyCollector(keyEntryData); + _ = keyCollectorFunc(keyEntryData); } // User cancelled diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.cs index 9c89b4c8..3e8d7d26 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiHsmAuth/YubiHsmAuthSession.cs @@ -118,11 +118,10 @@ public YubiHsmAuthSession(IYubiKeyDevice yubiKey) /// public void ResetApplication() { - ResetApplicationResponse resetResponse = Connection.SendCommand(new ResetApplicationCommand()); - - if (resetResponse.Status != ResponseStatus.Success) + var response = Connection.SendCommand(new ResetApplicationCommand()); + if (response.Status != ResponseStatus.Success) { - throw new InvalidOperationException(resetResponse.StatusMessage); + throw new InvalidOperationException(response.StatusMessage); } } @@ -137,7 +136,7 @@ public void ResetApplication() /// public ApplicationVersion GetApplicationVersion() { - GetApplicationVersionResponse applicationVersionResponse = Connection.SendCommand(new GetApplicationVersionCommand()); + var applicationVersionResponse = Connection.SendCommand(new GetApplicationVersionCommand()); if (applicationVersionResponse.Status != ResponseStatus.Success) { diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyCapabilitiesExtensions.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyCapabilitiesExtensions.cs index eb352d33..e0dcad9e 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyCapabilitiesExtensions.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyCapabilitiesExtensions.cs @@ -17,26 +17,26 @@ namespace Yubico.YubiKey internal static class YubiKeyCapabilitiesExtensions { public static YubiKeyCapabilities ToDeviceInfoCapabilities( - this YubiKeyCapabilities yubiKeyCapabilities) + this YubiKeyCapabilities capabilities) { - if (yubiKeyCapabilities.HasFlag(YubiKeyCapabilities.All)) + if (capabilities.HasFlag(YubiKeyCapabilities.All)) { - return yubiKeyCapabilities; + return capabilities; } - YubiKeyCapabilities deviceInfoCapabilities = YubiKeyCapabilities.None; + var deviceInfoCapabilities = YubiKeyCapabilities.None; - if (yubiKeyCapabilities.HasFlag(YubiKeyCapabilities.Otp)) + if (capabilities.HasFlag(YubiKeyCapabilities.Otp)) { deviceInfoCapabilities |= YubiKeyCapabilities.Otp; } - if (yubiKeyCapabilities.HasFlag(YubiKeyCapabilities.FidoU2f)) + if (capabilities.HasFlag(YubiKeyCapabilities.FidoU2f)) { deviceInfoCapabilities |= YubiKeyCapabilities.FidoU2f | YubiKeyCapabilities.Fido2; } - if (yubiKeyCapabilities.HasFlag(YubiKeyCapabilities.Ccid)) + if (capabilities.HasFlag(YubiKeyCapabilities.Ccid)) { deviceInfoCapabilities |= YubiKeyCapabilities.Piv diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs index d9277e6a..16a95283 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Instance.cs @@ -118,7 +118,7 @@ public Transport AvailableTransports { get { - Transport transports = Transport.None; + var transports = Transport.None; if (HasHidKeyboard) { @@ -275,28 +275,28 @@ internal protected bool HasSameParentDevice(IDevice device) /// public IYubiKeyConnection Connect(YubiKeyApplication yubikeyApplication) { - _ = TryConnect(yubikeyApplication, null, true, out IYubiKeyConnection? returnValue); + _ = TryConnect(yubikeyApplication, null, true, out var returnValue); return returnValue!; } /// public IScp03YubiKeyConnection ConnectScp03(YubiKeyApplication yubikeyApplication, StaticKeys scp03Keys) { - _ = TryConnectScp03(yubikeyApplication, null, scp03Keys, true, out IScp03YubiKeyConnection? returnValue); + _ = TryConnectScp03(yubikeyApplication, null, scp03Keys, true, out var returnValue); return returnValue!; } /// public IYubiKeyConnection Connect(byte[] applicationId) { - _ = TryConnect(null, applicationId, true, out IYubiKeyConnection? returnValue); + _ = TryConnect(null, applicationId, true, out var returnValue); return returnValue!; } /// public IScp03YubiKeyConnection ConnectScp03(byte[] applicationId, StaticKeys scp03Keys) { - _ = TryConnectScp03(null, applicationId, scp03Keys, true, out IScp03YubiKeyConnection? returnValue); + _ = TryConnectScp03(null, applicationId, scp03Keys, true, out var returnValue); return returnValue!; } @@ -339,7 +339,7 @@ private bool TryConnect( [MaybeNullWhen(returnValue: false)] out IYubiKeyConnection connection) { - IYubiKeyConnection? returnValue = Connect(application, applicationId, null); + var returnValue = Connect(application, applicationId, null); if (!(returnValue is null) || !throwOnFail) { connection = returnValue; @@ -357,7 +357,7 @@ private bool TryConnectScp03( [MaybeNullWhen(returnValue: false)] out IScp03YubiKeyConnection connection) { - IYubiKeyConnection? returnValue = Connect(application, applicationId, scp03Keys); + var returnValue = Connect(application, applicationId, scp03Keys); if (!(returnValue is null) && returnValue is IScp03YubiKeyConnection scp03Connection) { connection = scp03Connection; @@ -458,7 +458,7 @@ public void SetEnabledNfcCapabilities(YubiKeyCapabilities yubiKeyCapabilities) ResetAfterConfig = true, }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { @@ -480,7 +480,7 @@ public void SetEnabledUsbCapabilities(YubiKeyCapabilities yubiKeyCapabilities) ResetAfterConfig = true, }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { @@ -501,7 +501,7 @@ public void SetChallengeResponseTimeout(int seconds) ChallengeResponseTimeout = (byte)seconds, }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { @@ -522,7 +522,7 @@ public void SetAutoEjectTimeout(int seconds) AutoEjectTimeout = seconds, }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { @@ -540,7 +540,7 @@ public void SetIsNfcRestricted(bool enabled) RestrictNfc = enabled }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); @@ -555,7 +555,7 @@ public void SetDeviceFlags(DeviceFlags deviceFlags) DeviceFlags = deviceFlags, }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); @@ -586,7 +586,7 @@ public void LockConfiguration(ReadOnlySpan lockCode) var command = new MgmtCmd.SetDeviceInfoCommand(); command.SetLockCode(lockCode); - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); @@ -611,7 +611,7 @@ public void UnlockConfiguration(ReadOnlySpan lockCode) command.ApplyLockCode(lockCode); command.SetLockCode(_lockCodeAllZeros.Span); - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { @@ -672,7 +672,7 @@ public void SetLegacyDeviceConfiguration( // Newer YubiKeys should use SetDeviceInfo if (FirmwareVersion.Major >= 5) { - DeviceFlags deviceFlags = + var deviceFlags = touchEjectEnabled ? DeviceFlags | DeviceFlags.TouchEject : DeviceFlags & ~DeviceFlags.TouchEject; @@ -735,7 +735,7 @@ public void SetTemporaryTouchThreshold(int value) TemporaryTouchThreshold = value }; - IYubiKeyResponse response = SendConfiguration(command); + var response = SendConfiguration(command); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(response.StatusMessage); @@ -1090,7 +1090,7 @@ private void WaitForReclaimTimeout(Transport newTransport) // should still probably wait a few milliseconds for things to stabilize. But definitely not the full // three seconds! For older keys, we use a value of 3.01 seconds to give us a little wiggle room as the // YubiKey's measurement for the reclaim timeout is likely not as accurate as our system clock. - TimeSpan reclaimTimeout = CanFastReclaim() ? TimeSpan.FromMilliseconds(100) : TimeSpan.FromSeconds(3.01); + var reclaimTimeout = CanFastReclaim() ? TimeSpan.FromMilliseconds(100) : TimeSpan.FromSeconds(3.01); // We're only affected by the reclaim timeout if we're switching USB transports. if (_lastActiveTransport == newTransport) @@ -1107,13 +1107,13 @@ private void WaitForReclaimTimeout(Transport newTransport) _lastActiveTransport, newTransport); - TimeSpan timeSinceLastActivation = DateTime.Now - GetLastActiveTime(); + var timeSinceLastActivation = DateTime.Now - GetLastActiveTime(); // If we haven't already waited the duration of the reclaim timeout, we need to do so. // Otherwise, we've already waited and can immediately switch the transport. if (timeSinceLastActivation < reclaimTimeout) { - TimeSpan waitNeeded = reclaimTimeout - timeSinceLastActivation; + var waitNeeded = reclaimTimeout - timeSinceLastActivation; _log.LogInformation( "Reclaim timeout still active. Need to wait {TimeMS} milliseconds.", diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs index f97b548f..11cb2672 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDevice.Static.cs @@ -73,7 +73,7 @@ public partial class YubiKeyDevice /// public static IEnumerable FindByTransport(Transport transport = Transport.All) { - ILogger log = Log.GetLogger(typeof(YubiKeyDeviceListener).FullName!); + var log = Log.GetLogger(typeof(YubiKeyDeviceListener).FullName!); log.LogInformation("FindByTransport {Transport}", transport); diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs index e2ced1be..2ed341fa 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceInfo.cs @@ -130,7 +130,7 @@ internal static bool TryCreateFromResponseData( ReadOnlyMemory responseApduData, [MaybeNullWhen(returnValue: false)] out YubiKeyDeviceInfo deviceInfo) { - Dictionary>? data = + var data = GetDeviceInfoResponseHelper.CreateApduDictionaryFromResponseData(responseApduData); if (data is null) @@ -162,9 +162,9 @@ internal static YubiKeyDeviceInfo CreateFromResponseData(Dictionary> tagValuePair in responseApduData) + foreach (var tagValuePair in responseApduData) { - ReadOnlySpan value = tagValuePair.Value.Span; + var value = tagValuePair.Value.Span; switch (tagValuePair.Key) { case YubikeyDeviceManagementTags.UsbPrePersCapabilitiesTag: diff --git a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceListener.cs b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceListener.cs index 66907d6b..4dc359c6 100644 --- a/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceListener.cs +++ b/Yubico.YubiKey/src/Yubico/YubiKey/YubiKeyDeviceListener.cs @@ -124,19 +124,18 @@ private void Update() ResetCacheMarkers(); - List devicesToProcess = GetDevices(); + var devicesToProcess = GetDevices(); _log.LogInformation("Cache currently aware of {Count} YubiKeys.", _internalCache.Count); var addedYubiKeys = new List(); - foreach (IDevice device in devicesToProcess) + foreach (var device in devicesToProcess) { _log.LogInformation("Processing device {Device}", device); // First check if we've already seen this device (very fast) - IYubiKeyDevice? existingEntry = _internalCache.Keys.FirstOrDefault(k => k.Contains(device)); - + var existingEntry = _internalCache.Keys.FirstOrDefault(k => k.Contains(device)); if (existingEntry != null) { MarkExistingYubiKey(existingEntry); @@ -198,13 +197,13 @@ private void Update() .Select(e => e.Key) .ToList(); - foreach (IYubiKeyDevice removedKey in removedYubiKeys) + foreach (var removedKey in removedYubiKeys) { OnDeviceRemoved(new YubiKeyDeviceEventArgs(removedKey)); _ = _internalCache.Remove(removedKey); } - foreach (IYubiKeyDevice addedKey in addedYubiKeys) + foreach (var addedKey in addedYubiKeys) { OnDeviceArrived(new YubiKeyDeviceEventArgs(addedKey)); } @@ -248,7 +247,7 @@ private List GetDevices() private void ResetCacheMarkers() { // Copy the list of keys as changing a dictionary's value will invalidate any enumerators (i.e. the loop). - foreach (IYubiKeyDevice cacheDevice in _internalCache.Keys.ToList()) + foreach (var cacheDevice in _internalCache.Keys.ToList()) { _internalCache[cacheDevice] = false; } diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs index 2e12dfb2..6216e6d1 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/Oath/GetLargeData.cs @@ -38,7 +38,7 @@ private static string RandomString(int length) private IEnumerable FillWithRandCreds(IYubiKeyDevice testDevice) { - List creds = new List(); + var creds = new List(); using (var oathSession = new OathSession(testDevice)) { diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs index aa5ba1f4..5249cc4e 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionCredentialTests.cs @@ -77,7 +77,7 @@ public void TryDeleteCredentialKeyCollector_MgmtKeyRetry_AppContainsZeroCreds() using (var yubiHsmAuthSession = new YubiHsmAuthSession(testDevice)) { - SimpleKeyCollector keyCollector = new SimpleKeyCollector + var keyCollector = new SimpleKeyCollector { // Start with the incorrect management key, forcing a retry UseDefaultValue = false @@ -222,7 +222,7 @@ public void TryAddCredentialKeyCollector_MgmtKeyRetry_AppContainsNewCred() // Preconditions IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); - SimpleKeyCollector simpleKeyCollector = new SimpleKeyCollector + var simpleKeyCollector = new SimpleKeyCollector { // Start with the incorrect management key, forcing a retry UseDefaultValue = false, diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs index 897b41b5..41880595 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionGetAes128SessionKeysTests.cs @@ -203,7 +203,7 @@ public void TryGetAes128SessionKeys_CredPasswordRetry_ReturnsTrueAndSessionKeys( using (var yubiHsmAuthSession = new YubiHsmAuthSession(testDevice)) { - SimpleKeyCollector keyCollector = new SimpleKeyCollector + var keyCollector = new SimpleKeyCollector { // Start with the incorrect cred password, forcing a retry UseDefaultValue = false diff --git a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs index 3f387663..e3404e8a 100644 --- a/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs +++ b/Yubico.YubiKey/tests/integration/Yubico/YubiKey/YubiHsmAuth/SessionManagementKeyTests.cs @@ -265,7 +265,7 @@ public void TryChangeManagementKeyKeyCollector_ValidKeys_ManagementKeyChanged() { // Preconditions IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); - SimpleKeyCollector keyCollector = new SimpleKeyCollector(); + var keyCollector = new SimpleKeyCollector(); using (var yubiHsmAuthSession = new YubiHsmAuthSession(testDevice)) { @@ -285,7 +285,7 @@ public void TryChangeMgmtKeyKeyCollector_WrongCurrentKey_RetrySuccess() { // Preconditions IYubiKeyDevice testDevice = YhaTestUtilities.GetCleanDevice(); - SimpleKeyCollector keyCollector = new SimpleKeyCollector + var keyCollector = new SimpleKeyCollector { UseDefaultValue = false, }; diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs index 7d4b52c6..6e399504 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/DavidPlugin.cs @@ -119,7 +119,7 @@ private bool ListCredentials() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { - ListCredentialsCommand cmd = new ListCredentialsCommand(); + var cmd = new ListCredentialsCommand(); ListCredentialsResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { @@ -178,7 +178,7 @@ public bool AddCredential() bool touchRequired = false; var aesCred = new Aes128CredentialWithSecrets(password, encKey, macKey, label, touchRequired); - AddCredentialCommand cmd = new AddCredentialCommand(mgmtKey, aesCred); + var cmd = new AddCredentialCommand(mgmtKey, aesCred); AddCredentialResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) @@ -325,7 +325,7 @@ private void LabelTesting(IYubiKeyConnection hsmAuthConnection, byte[] label) return; } - AddCredentialCommand addCmd = new AddCredentialCommand(mgmtKey, aesCred); + var addCmd = new AddCredentialCommand(mgmtKey, aesCred); AddCredentialResponse response = hsmAuthConnection.SendCommand(addCmd); if (response.Status != ResponseStatus.Success) @@ -343,7 +343,7 @@ private void LabelTesting(IYubiKeyConnection hsmAuthConnection, byte[] label) private bool HelperListCreds(IYubiKeyConnection hsmAuthConnection) { - ListCredentialsCommand listCmd = new ListCredentialsCommand(); + var listCmd = new ListCredentialsCommand(); ListCredentialsResponse listResponse = hsmAuthConnection.SendCommand(listCmd); if (listResponse.Status != ResponseStatus.Success) { @@ -397,7 +397,7 @@ public bool TestCredLimit() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { - ListCredentialsCommand listCmd = new ListCredentialsCommand(); + var listCmd = new ListCredentialsCommand(); ListCredentialsResponse listResponse = hsmAuthConnection.SendCommand(listCmd); if (listResponse.Status != ResponseStatus.Success) { @@ -414,7 +414,7 @@ public bool TestCredLimit() Output.WriteLine($"Adding cred #{i}"); aesCred.Label = $"Test Cred {i}"; - AddCredentialCommand cmd = new AddCredentialCommand(mgmtKey, aesCred); + var cmd = new AddCredentialCommand(mgmtKey, aesCred); AddCredentialResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) @@ -476,7 +476,7 @@ private bool DeleteCredential() CredentialRetryPair credRetryPair = credRetryPairs.First(); - DeleteCredentialCommand cmd = + var cmd = new DeleteCredentialCommand(mgmtKey, credRetryPair.Credential.Label); Output.WriteLine($"\nAttempting to delete credential \"{cmd.Label}\"..."); @@ -529,7 +529,7 @@ private bool HelperWriteCreds(IYubiKeyConnection hsmAuthConnection) private List? HelperGetCreds(IYubiKeyConnection hsmAuthConnection) { - ListCredentialsCommand listCmd = new ListCredentialsCommand(); + var listCmd = new ListCredentialsCommand(); ListCredentialsResponse listResponse = hsmAuthConnection.SendCommand(listCmd); if (listResponse.Status != ResponseStatus.Success) { @@ -560,7 +560,7 @@ private bool GetMgmtRetries() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { - GetManagementKeyRetriesCommand cmd = new GetManagementKeyRetriesCommand(); + var cmd = new GetManagementKeyRetriesCommand(); GetManagementKeyRetriesResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { @@ -600,7 +600,7 @@ private bool GetAppVersion() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { - GetApplicationVersionCommand cmd = new GetApplicationVersionCommand(); + var cmd = new GetApplicationVersionCommand(); GetApplicationVersionResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) @@ -648,7 +648,7 @@ private bool ChangeManagementKey() byte[] currentManagementKey = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] newManagementKey = new byte[16] { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 }; - ChangeManagementKeyCommand cmd = new ChangeManagementKeyCommand(currentManagementKey, newManagementKey); + var cmd = new ChangeManagementKeyCommand(currentManagementKey, newManagementKey); ChangeManagementKeyResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) @@ -703,7 +703,7 @@ private bool TestMgmtRetries() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { // Get initial mgmt key retries remaining - GetManagementKeyRetriesCommand cmdRetries = new GetManagementKeyRetriesCommand(); + var cmdRetries = new GetManagementKeyRetriesCommand(); GetManagementKeyRetriesResponse responseRetries = hsmAuthConnection.SendCommand(cmdRetries); if (responseRetries.Status != ResponseStatus.Success) { @@ -719,7 +719,7 @@ private bool TestMgmtRetries() byte[] currentManagementKey = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] newManagementKey = new byte[16] { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 }; - ChangeManagementKeyCommand cmdChangeMgmt = new ChangeManagementKeyCommand(newManagementKey, currentManagementKey); + var cmdChangeMgmt = new ChangeManagementKeyCommand(newManagementKey, currentManagementKey); ChangeManagementKeyResponse responseChangeMgmt = hsmAuthConnection.SendCommand(cmdChangeMgmt); if (responseChangeMgmt.Status != ResponseStatus.Success) @@ -795,11 +795,11 @@ private bool ResetYubiHsmAuth() Output.WriteLine($"\n{deviceCount++}) Using YubiKey v{device.FirmwareVersion} S/N {device.SerialNumber}..."); - using (YubiHsmAuthSession yhaSession = new YubiHsmAuthSession(device)) + using (var yhaSession = new YubiHsmAuthSession(device)) { if (!HelperGetCreds(yhaSession.Connection)!.Any()) { - AddCredentialCommand cmdAddCred = new AddCredentialCommand(mgmtKey, aesCred); + var cmdAddCred = new AddCredentialCommand(mgmtKey, aesCred); AddCredentialResponse responseAddCred = yhaSession.Connection.SendCommand(cmdAddCred); if (responseAddCred.Status != ResponseStatus.Success) @@ -865,7 +865,7 @@ private bool GetSessionKeys() using (IYubiKeyConnection hsmAuthConnection = device.Connect(YubiKeyApplication.YubiHsmAuth)) { // Reset app - ResetApplicationCommand cmd = new ResetApplicationCommand(); + var cmd = new ResetApplicationCommand(); ResetApplicationResponse response = hsmAuthConnection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { @@ -878,7 +878,7 @@ private bool GetSessionKeys() } // Add cred - AddCredentialCommand cmdAddCred = new AddCredentialCommand(mgmtKey, aesCred); + var cmdAddCred = new AddCredentialCommand(mgmtKey, aesCred); AddCredentialResponse responseAddCred = hsmAuthConnection.SendCommand(cmdAddCred); if (responseAddCred.Status != ResponseStatus.Success) @@ -892,7 +892,7 @@ private bool GetSessionKeys() } // Get session keys - GetAes128SessionKeysCommand cmdGetSessionKeys = new GetAes128SessionKeysCommand(strLabel, password, hostChallenge, hsmDeviceChallenge); + var cmdGetSessionKeys = new GetAes128SessionKeysCommand(strLabel, password, hostChallenge, hsmDeviceChallenge); GetAes128SessionKeysResponse rspGetSessionKeys = hsmAuthConnection.SendCommand(cmdGetSessionKeys); if (responseAddCred.Status != ResponseStatus.Success) @@ -950,7 +950,7 @@ private bool SessionAppMethods() Output.WriteLine($"\n{deviceCount++}) Using YubiKey v{device.FirmwareVersion} S/N {device.SerialNumber}..."); - using (YubiHsmAuthSession yhaSession = new YubiHsmAuthSession(device)) + using (var yhaSession = new YubiHsmAuthSession(device)) { Output.WriteLine("Resetting YubiHSM Auth application..."); yhaSession.ResetApplication(); @@ -1055,7 +1055,7 @@ private bool SessionAppMethods() string targetCredLabel = creds[0].Credential.Label; Output.WriteLine($"Reducing {targetCredLabel} retries to 6..."); int? retriesRemaining = creds.First(cred => cred.Credential.Label == targetCredLabel).Retries; - GetAes128SessionKeysCommand getSessionKeys = new GetAes128SessionKeysCommand(targetCredLabel, newMgmtKey, hostChallenge, hsmDeviceChallenge); + var getSessionKeys = new GetAes128SessionKeysCommand(targetCredLabel, newMgmtKey, hostChallenge, hsmDeviceChallenge); GetAes128SessionKeysResponse responseSessionKeys; while (retriesRemaining > 6) { @@ -1085,7 +1085,7 @@ private bool SessionAppMethods() //Output.WriteLine(); Output.WriteLine("Attempting to change mgmt key (correct current mgmt key)..."); - ChangeManagementKeyCommand cmdChangeMgmt = new ChangeManagementKeyCommand(currentMgmtKey, newMgmtKey); + var cmdChangeMgmt = new ChangeManagementKeyCommand(currentMgmtKey, newMgmtKey); ChangeManagementKeyResponse responseChangeMgmt = yhaSession.Connection.SendCommand(cmdChangeMgmt); Output.WriteLine($"Response status: {responseChangeMgmt.Status}, {responseChangeMgmt.StatusMessage}; retries = {responseChangeMgmt.RetriesRemaining}"); Output.WriteLine(); diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs index f92a2c37..6b969a59 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/HidCodeTablePlugin.cs @@ -83,7 +83,7 @@ public HidCodeTablePlugin(IOutput output) : base(output) public override void HandleParameters() { // If none were specified, print them all. - IEnumerable keyboards = (IEnumerable)(Parameters["keyboardids"].Value ?? Array.Empty()); + var keyboards = (IEnumerable)(Parameters["keyboardids"].Value ?? Array.Empty()); _keyboards = keyboards.Any() ? keyboards : _keyboardLayouts.Keys; diff --git a/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs b/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs index 2ef226c3..f62cd008 100644 --- a/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs +++ b/Yubico.YubiKey/tests/sandbox/Plugins/YubiKeyFeaturePlugin.cs @@ -166,7 +166,7 @@ private YubiKeyFeature GetOtpFeature() Output.Write("Select an option and press ENTER. Press any other key to exit: "); ConsoleKeyInfo inputKey = Console.ReadKey(true); - StringBuilder inputStr = new StringBuilder(inputKey.KeyChar.ToString()); + var inputStr = new StringBuilder(inputKey.KeyChar.ToString()); Console.Write(inputStr); while (inputKey.Key != ConsoleKey.Enter) diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobArrayTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobArrayTests.cs index c9a1728c..83a99afd 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobArrayTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobArrayTests.cs @@ -137,7 +137,7 @@ private static void AddFixedEntry(SerializedLargeBlobArray array) // The code will generate a random nonce. So to guarantee the nonce // we want, use the fixed byte RNG. - RandomObjectUtility nonceGenerator = + var nonceGenerator = RandomObjectUtility.SetRandomProviderFixedBytes(nonceBytes); try diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobEntryTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobEntryTests.cs index 467d016c..7c7624a4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobEntryTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Fido2/LargeBlobEntryTests.cs @@ -71,7 +71,7 @@ public void Encode_Succeeds() // The code will generate a random nonce. So to guarantee the nonce // we want, use the fixed byte RNG. - RandomObjectUtility nonceGenerator = + var nonceGenerator = RandomObjectUtility.SetRandomProviderFixedBytes(nonceBytes); bool isValid = false; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommandTests.cs index 27ed52d6..e053dbb5 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateAllCredentialsCommandTests.cs @@ -76,7 +76,7 @@ public void CreateCommandApdu_GetNe_ReturnsZero() [Fact] public void CreateCommandApdu_ReturnsCorrectLength() { - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -100,7 +100,7 @@ public void CreateCommandApdu_ReturnsCorrectLength() [Fact] public void CreateCommandApdu_ReturnsCorrectData() { - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs index 5c50f5bb..150637f1 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/CalculateCredentialCommandTests.cs @@ -77,7 +77,7 @@ public void CreateCommandApdu_GetNe_ReturnsZero() [Fact] public void CreateCommandApdu_TotpCredential_ReturnsCorrectLength() { - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -105,7 +105,7 @@ public void CreateCommandApdu_TotpCredential_ReturnsCorrectLength() [Fact] public void CreateCommandApdu_TotpCredential_ReturnsCorrectData() { - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs index b4e4127d..f054b91e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/SetPasswordCommandTests.cs @@ -82,7 +82,7 @@ public void CreateCommandApdu_GetNcProperty_ReturnsCorrectLengthOfData() { var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -111,7 +111,7 @@ public void CreateCommandApdu_GetDataProperty_ReturnsCorrectData() { var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs index d7ff0a69..948add24 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateCommandTests.cs @@ -81,8 +81,8 @@ public void CreateCommandApdu_GetP2Property_ReturnsZero() public void CreateCommandApdu_GetNcProperty_ReturnsCorrectLength() { var selectOathResponse = new SelectOathResponse(selectResponseApdu); - OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var oathData = selectOathResponse.GetData(); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -109,7 +109,7 @@ public void CreateCommandApdu_GetDataProperty_ReturnsCorrectData() { var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs index 6d064843..9755e2d9 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/Commands/ValidateResponseTests.cs @@ -43,7 +43,7 @@ public void Status_SuccessResponseApdu_ReturnsSuccess() var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -75,7 +75,7 @@ public void Status_AuthNotEnabledResponseApdu_ReturnsFailed() var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { @@ -104,7 +104,7 @@ public void SuccessResponseApdu_PasswordIsSet_OathResponseInfoCorrect() { var selectOathResponse = new SelectOathResponse(selectResponseApdu); OathApplicationData oathData = selectOathResponse.GetData(); - RandomObjectUtility utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); + var utility = RandomObjectUtility.SetRandomProviderFixedBytes(_fixedBytes); try { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs index f64beb37..c9b9d030 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Oath/CredentialTests.cs @@ -27,7 +27,7 @@ public class CredentialTests [Fact] public void Issuer_GetDefaultValue_ReturnsNull() { - Credential cred = new Credential(); + var cred = new Credential(); Assert.Null(cred.Issuer); } @@ -35,7 +35,7 @@ public void Issuer_GetDefaultValue_ReturnsNull() [Fact] public void Issuer_SetToTestString_ReturnsTestString() { - Credential cred = new Credential + var cred = new Credential { Issuer = DefaultTestIssuer }; @@ -47,7 +47,7 @@ public void Issuer_SetToTestString_ReturnsTestString() [Fact] public void Issuer_SetToTestStringWithLeadingTrailingWhiteSpace_ReturnsTestString() { - Credential cred = new Credential(); + var cred = new Credential(); string? expectedIssuer = " " + DefaultTestIssuer + " \t "; cred.Issuer = expectedIssuer; @@ -59,7 +59,7 @@ public void Issuer_SetToTestStringWithLeadingTrailingWhiteSpace_ReturnsTestStrin [Fact] public void Issuer_SetToNull_ReturnsNull() { - Credential cred = new Credential + var cred = new Credential { Issuer = null }; @@ -71,7 +71,7 @@ public void Issuer_SetToNull_ReturnsNull() [Fact] public void Issuer_SetToEmptyString_ReturnsNull() { - Credential cred = new Credential + var cred = new Credential { Issuer = string.Empty }; @@ -86,7 +86,7 @@ public void Issuer_SetToEmptyString_ReturnsNull() [InlineData("\u2000\u2000\u2000")] public void Issuer_SetToWhiteSpace_ReturnsNull(string? issuerValue) { - Credential cred = new Credential + var cred = new Credential { Issuer = issuerValue }; @@ -102,7 +102,7 @@ public void Issuer_SetToWhiteSpace_ReturnsNull(string? issuerValue) [Fact] public void Name_Totp15sIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period15, @@ -119,7 +119,7 @@ public void Name_Totp15sIssuerAccount_ReturnsCorrectName() [Fact] public void Name_Totp30sIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period30, @@ -136,7 +136,7 @@ public void Name_Totp30sIssuerAccount_ReturnsCorrectName() [Fact] public void Name_HotpIssuerAccount_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Hotp, Issuer = DefaultTestIssuer, @@ -155,7 +155,7 @@ public void Name_HotpIssuerAccount_ReturnsCorrectName() [InlineData(" ")] public void Name_Totp15sAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period15, @@ -172,7 +172,7 @@ public void Name_Totp15sAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_Totp15sAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period15, @@ -191,7 +191,7 @@ public void Name_Totp15sAccountDefaultIssuer_ReturnsCorrectName() [InlineData(" ")] public void Name_Totp30sAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period30, @@ -208,7 +208,7 @@ public void Name_Totp30sAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_Totp30sAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period30, @@ -227,7 +227,7 @@ public void Name_Totp30sAccountDefaultIssuer_ReturnsCorrectName() [InlineData(" ")] public void Name_HotpAccount_ReturnsCorrectName(string? issuerValue) { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Hotp, Issuer = issuerValue, @@ -243,7 +243,7 @@ public void Name_HotpAccount_ReturnsCorrectName(string? issuerValue) [Fact] public void Name_HotpAccountDefaultIssuer_ReturnsCorrectName() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Hotp, AccountName = DefaultTestAccount @@ -265,7 +265,7 @@ public void Name_HotpAccountDefaultIssuer_ReturnsCorrectName() [InlineData(CredentialType.Hotp, CredentialPeriod.Undefined, null, "1234567890123456789012345678901234567890123456789012345678901234")] public void Name_64ByteNameLength_ReturnsCorrectName(CredentialType credType, CredentialPeriod credPeriod, string? issuer, string account) { - Credential cred = new Credential + var cred = new Credential { Type = credType, Period = credPeriod, @@ -291,7 +291,7 @@ public void Name_64ByteNameLength_ReturnsCorrectName(CredentialType credType, Cr [InlineData(CredentialType.Hotp, CredentialPeriod.Undefined, null, "12345678901234567890123456789012345678901234567890123456789012345")] public void Name_65ByteNameLength_ThrowsInvalidOperationException(CredentialType credType, CredentialPeriod credPeriod, string? issuer, string account) { - Credential cred = new Credential + var cred = new Credential { Type = credType, Period = credPeriod, @@ -305,7 +305,7 @@ public void Name_65ByteNameLength_ThrowsInvalidOperationException(CredentialType [Fact] public void Name_CredTypeDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Issuer = DefaultTestIssuer, AccountName = DefaultTestAccount @@ -317,7 +317,7 @@ public void Name_CredTypeDefault_ThrowsInvalidOperationException() [Fact] public void Name_CredTypeNone_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.None, Issuer = DefaultTestIssuer, @@ -330,7 +330,7 @@ public void Name_CredTypeNone_ThrowsInvalidOperationException() [Fact] public void Name_TotpCredPeriodDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Issuer = DefaultTestIssuer, @@ -343,7 +343,7 @@ public void Name_TotpCredPeriodDefault_ThrowsInvalidOperationException() [Fact] public void Name_TotpCredPeriodUndefined_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Period = CredentialPeriod.Undefined, Type = CredentialType.Totp, @@ -357,7 +357,7 @@ public void Name_TotpCredPeriodUndefined_ThrowsInvalidOperationException() [Fact] public void Name_Totp30sAccountDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Totp, Period = CredentialPeriod.Period30, @@ -370,7 +370,7 @@ public void Name_Totp30sAccountDefault_ThrowsInvalidOperationException() [Fact] public void Name_HotpAccountDefault_ThrowsInvalidOperationException() { - Credential cred = new Credential + var cred = new Credential { Type = CredentialType.Hotp, Issuer = DefaultTestIssuer diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs index 3ad5f2d0..d734ed3c 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/Piv/KeyTests.cs @@ -76,7 +76,7 @@ public void DesWeak() byte[] encryptedData = new byte[8]; byte[] encryptCipher = new byte[8]; - TripleDES desObject = TripleDES.Create(); + var desObject = TripleDES.Create(); desObject.Mode = CipherMode.ECB; desObject.Padding = PaddingMode.None; ICryptoTransform encryptor = desObject.CreateEncryptor(keyData, null); @@ -122,7 +122,7 @@ public void DesWeak_Matching() byte[] result3 = new byte[8]; byte[] result4 = new byte[8]; - TripleDES tDesObject = TripleDES.Create(); + var tDesObject = TripleDES.Create(); tDesObject.Mode = CipherMode.ECB; tDesObject.Padding = PaddingMode.None; @@ -166,7 +166,7 @@ public void TDes_Double() byte[] result2 = new byte[8]; byte[] result3 = new byte[8]; - TripleDES tDesObject = TripleDES.Create(); + var tDesObject = TripleDES.Create(); tDesObject.Mode = CipherMode.ECB; tDesObject.Padding = PaddingMode.None; tDesObject.KeySize = 128; @@ -212,7 +212,7 @@ public void DesReplace() byte[] part1 = new byte[8]; byte[] part2 = new byte[8]; - TripleDES tDesObject = TripleDES.Create(); + var tDesObject = TripleDES.Create(); tDesObject.Mode = CipherMode.ECB; tDesObject.Padding = PaddingMode.None; @@ -224,7 +224,7 @@ public void DesReplace() eLen = encryptor1.TransformBlock(dataToEncrypt, 0, 8, part1, 0); Assert.Equal(8, eLen); - DES desObject = DES.Create(); + var desObject = DES.Create(); desObject.Mode = CipherMode.ECB; desObject.Padding = PaddingMode.None; diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Aes128CredentialWithSecretsTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Aes128CredentialWithSecretsTests.cs index 76e39d05..4ddd85e4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Aes128CredentialWithSecretsTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Aes128CredentialWithSecretsTests.cs @@ -78,7 +78,7 @@ public void Constructor_InvalidMacKeyLength_ThrowsArgException(int len) [Fact] public void Constructor_SetGetLabel() { - Aes128CredentialWithSecrets aes128Cred = new Aes128CredentialWithSecrets( + var aes128Cred = new Aes128CredentialWithSecrets( _password, _encKey, _macKey, @@ -91,7 +91,7 @@ public void Constructor_SetGetLabel() [Fact] public void Constructor_SetGetTouchRequired() { - Aes128CredentialWithSecrets aes128Cred = new Aes128CredentialWithSecrets( + var aes128Cred = new Aes128CredentialWithSecrets( _password, _encKey, _macKey, diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs index d5df2033..5a3e87b4 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialCommandTests.cs @@ -44,7 +44,7 @@ public class AddCredentialCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); } @@ -52,7 +52,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void CreateCommandApdu_Cla0() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Cla); @@ -61,7 +61,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x01() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0x01, apdu.Ins); @@ -70,7 +70,7 @@ public void CreateCommandApdu_Ins0x01() [Fact] public void CreateCommandApdu_P1Is0() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P1); @@ -79,7 +79,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P2); @@ -88,10 +88,10 @@ public void CreateCommandApdu_P2Is0() [Fact] public void CreateCommandApdu_DataContainsMgmtKeyTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7b) { @@ -105,10 +105,10 @@ public void CreateCommandApdu_DataContainsMgmtKeyTag() [Fact] public void CreateCommandApdu_DataContainsMgmtKeyValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7b) { @@ -124,10 +124,10 @@ public void CreateCommandApdu_DataContainsMgmtKeyValue() [Fact] public void CreateCommandApdu_DataContainsLabelTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { @@ -141,10 +141,10 @@ public void CreateCommandApdu_DataContainsLabelTag() [Fact] public void CreateCommandApdu_DataContainsLabelValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { @@ -160,10 +160,10 @@ public void CreateCommandApdu_DataContainsLabelValue() [Fact] public void CreateCommandApdu_DataContainsTouchRequiredTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7a) { @@ -177,10 +177,10 @@ public void CreateCommandApdu_DataContainsTouchRequiredTag() [Fact] public void CreateCommandApdu_DataContainsTouchRequiredValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7a) { @@ -196,10 +196,10 @@ public void CreateCommandApdu_DataContainsTouchRequiredValue() [Fact] public void CreateCommandApdu_DataContainsKeyTypeTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x74) { @@ -213,10 +213,10 @@ public void CreateCommandApdu_DataContainsKeyTypeTag() [Fact] public void CreateCommandApdu_DataContainsKeyTypeValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x74) { @@ -232,10 +232,10 @@ public void CreateCommandApdu_DataContainsKeyTypeValue() [Fact] public void CreateCommandApdu_DataContainsCredPasswordTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x73) { @@ -249,10 +249,10 @@ public void CreateCommandApdu_DataContainsCredPasswordTag() [Fact] public void CreateCommandApdu_DataContainsCredPasswordValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x73) { @@ -268,10 +268,10 @@ public void CreateCommandApdu_DataContainsCredPasswordValue() [Fact] public void CreateCommandApdu_GivenAes128Credential_DataContainsEncKeyTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x75) { @@ -285,10 +285,10 @@ public void CreateCommandApdu_GivenAes128Credential_DataContainsEncKeyTag() [Fact] public void CreateCommandApdu_GivenAes128Credential_DataContainsEncKeyValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x75) { @@ -304,10 +304,10 @@ public void CreateCommandApdu_GivenAes128Credential_DataContainsEncKeyValue() [Fact] public void CreateCommandApdu_GivenAes128Credential_DataContainsMacKeyTag() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x76) { @@ -321,10 +321,10 @@ public void CreateCommandApdu_GivenAes128Credential_DataContainsMacKeyTag() [Fact] public void CreateCommandApdu_GivenAes128Credential_DataContainsMacKeyValue() { - AddCredentialCommand command = new AddCredentialCommand(_mgmtKey, _aes128Cred); + var command = new AddCredentialCommand(_mgmtKey, _aes128Cred); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x76) { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialResponseTests.cs index b7fed25d..fa8814a7 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/AddCredentialResponseTests.cs @@ -22,9 +22,9 @@ public class AddCredentialResponseTests [Fact] public void Constructor_ReturnsObject() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.Success); + var apdu = new ResponseApdu(new byte[0], SWConstants.Success); - AddCredentialResponse response = new AddCredentialResponse(apdu); + var response = new AddCredentialResponse(apdu); Assert.NotNull(response); } @@ -32,9 +32,9 @@ public void Constructor_ReturnsObject() [Fact] public void ResponseStatus_GivenStatusWord0x6983_ReturnsFailed() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - AddCredentialResponse response = new AddCredentialResponse(apdu); + var response = new AddCredentialResponse(apdu); Assert.Equal(ResponseStatus.Failed, response.Status); } @@ -44,9 +44,9 @@ public void StatusMessage_GivenStatusWord0x6983_ReturnsCorrectMessage() { string expectedMessage = "A credential with that label already exists."; - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - AddCredentialResponse response = new AddCredentialResponse(apdu); + var response = new AddCredentialResponse(apdu); Assert.Equal(expectedMessage, response.StatusMessage); } @@ -55,9 +55,9 @@ public void StatusMessage_GivenStatusWord0x6983_ReturnsCorrectMessage() [Fact] public void ResponseStatus_GivenStatusWord0x63C0_ReturnsAuthenticationRequired() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.VerifyFail); + var apdu = new ResponseApdu(new byte[0], SWConstants.VerifyFail); - AddCredentialResponse response = new AddCredentialResponse(apdu); + var response = new AddCredentialResponse(apdu); Assert.Equal(ResponseStatus.AuthenticationRequired, response.Status); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseTests.cs index e722c01b..23b70b01 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseTests.cs @@ -36,7 +36,7 @@ public void Constructor_GivenSuccessApdu_SetsCorrectStatusWord() { short expectedSW = SWConstants.Success; - SampleYubiHsmAuthResponse response = new SampleYubiHsmAuthResponse( + var response = new SampleYubiHsmAuthResponse( new ResponseApdu(new byte[] { }, expectedSW)); Assert.Equal(expectedSW, response.StatusWord); @@ -49,7 +49,7 @@ public void Constructor_GivenSuccessApdu_SetsCorrectStatusWord() [InlineData(SWConstants.Success, ResponseStatus.Success)] public void Status_GivenStatusWord_ReturnsCorrectResponseStatus(short responseSw, ResponseStatus expectedStatus) { - SampleYubiHsmAuthResponse response = new SampleYubiHsmAuthResponse( + var response = new SampleYubiHsmAuthResponse( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedStatus, response.Status); @@ -62,7 +62,7 @@ public void Status_GivenStatusWord_ReturnsCorrectResponseStatus(short responseSw [InlineData(SWConstants.Success, SuccessStatusMessage)] public void Status_GivenStatusWord_ReturnsCorrectResponseMessage(short responseSw, string expectedMessage) { - SampleYubiHsmAuthResponse response = new SampleYubiHsmAuthResponse( + var response = new SampleYubiHsmAuthResponse( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedMessage, response.StatusMessage); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseWithRetriesTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseWithRetriesTests.cs index 01a46426..4d1e9b5f 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseWithRetriesTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/BaseYubiHsmAuthResponseWithRetriesTests.cs @@ -36,7 +36,7 @@ public SampleYubiHsmAuthResponseWithRetries(ResponseApdu responseApdu) : base(re [InlineData(0x63cf, ResponseStatus.AuthenticationRequired)] public void Status_GivenStatusWord_ReturnsCorrectResponseStatus(short responseSw, ResponseStatus expectedStatus) { - SampleYubiHsmAuthResponseWithRetries response = new SampleYubiHsmAuthResponseWithRetries( + var response = new SampleYubiHsmAuthResponseWithRetries( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedStatus, response.Status); @@ -47,7 +47,7 @@ public void Status_GivenStatusWord_ReturnsCorrectResponseStatus(short responseSw [InlineData(0x63cf, AuthenticationRequired15RetriesStatusMessage)] public void Status_GivenStatusWord_ReturnsCorrectResponseMessage(short responseSw, string expectedMessage) { - SampleYubiHsmAuthResponseWithRetries response = new SampleYubiHsmAuthResponseWithRetries( + var response = new SampleYubiHsmAuthResponseWithRetries( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedMessage, response.StatusMessage); @@ -60,7 +60,7 @@ public void Status_GivenStatusWord_ReturnsCorrectResponseMessage(short responseS [InlineData(SWConstants.InvalidParameter, false)] public void SwContainsRetries_GivenSw_ReturnsTrueWhenRetriesPresent(short responseSw, bool expectedResponse) { - SampleYubiHsmAuthResponseWithRetries response = new SampleYubiHsmAuthResponseWithRetries( + var response = new SampleYubiHsmAuthResponseWithRetries( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedResponse, response.HasRetries); @@ -71,7 +71,7 @@ public void SwContainsRetries_GivenSw_ReturnsTrueWhenRetriesPresent(short respon [InlineData(0x63cf, 15)] public void RetriesRemaining_GivenSwWithRetryCount_ReturnsCorrectRetryCount(short responseSw, int? expectedCount) { - SampleYubiHsmAuthResponseWithRetries response = new SampleYubiHsmAuthResponseWithRetries( + var response = new SampleYubiHsmAuthResponseWithRetries( new ResponseApdu(new byte[] { }, responseSw)); Assert.Equal(expectedCount, response.RetriesRemaining); @@ -82,7 +82,7 @@ public void RetriesRemaining_GivenSwWithRetryCount_ReturnsCorrectRetryCount(shor [InlineData(SWConstants.InvalidParameter)] public void RetriesRemaining_GivenSwNoRetryCount_ReturnsNull(short responseSw) { - SampleYubiHsmAuthResponseWithRetries response = new SampleYubiHsmAuthResponseWithRetries( + var response = new SampleYubiHsmAuthResponseWithRetries( new ResponseApdu(new byte[] { }, responseSw)); Assert.True(!response.RetriesRemaining.HasValue); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs index 2ffdcdf6..6c2c9f27 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ChangeManagementKeyCommandTests.cs @@ -80,7 +80,7 @@ public void CreateCommandApdu_DataContainsTwoMgmtKeyTags() ChangeManagementKeyCommand command = _command; CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int mgmtKeyTagCount = 0; @@ -104,7 +104,7 @@ public void CreateCommandApdu_DataContainsCurrentMgmtKeyValue() ChangeManagementKeyCommand command = _command; CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int mgmtKeyTagCount = 0; byte[] value = Array.Empty(); @@ -129,7 +129,7 @@ public void CreateCommandApdu_DataContainsNewMgmtKeyValue() ChangeManagementKeyCommand command = _command; CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int mgmtKeyTagCount = 0; byte[] value = Array.Empty(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommandTests.cs index cb2c8d78..6d3d34f2 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/DeleteCredentialCommandTests.cs @@ -46,7 +46,7 @@ public void CtorMgmtKey_GivenInvalidLength_ThrowsArgException(int length) [Fact] public void ConstructorMgmtKeyLabel_ValidInputs_LabelMatchesInput() { - DeleteCredentialCommand cmd = + var cmd = new DeleteCredentialCommand(_mgmtKey, _label); Assert.Equal(_label, cmd.Label); @@ -77,7 +77,7 @@ public void CtorMgmtKeyLabel_InvalidLabelLength_ThrowsArgException(int length) [Fact] public void Label_SetGetValidString_ReturnsMatchingString() { - DeleteCredentialCommand cmd = new DeleteCredentialCommand(_mgmtKey) + var cmd = new DeleteCredentialCommand(_mgmtKey) { Label = _label }; @@ -92,7 +92,7 @@ public void Label_SetInvalidLabelLength_ThrowsArgException(int length) { string invalidLabel = new string('a', length); - DeleteCredentialCommand cmd = new DeleteCredentialCommand(_mgmtKey); + var cmd = new DeleteCredentialCommand(_mgmtKey); _ = Assert.ThrowsAny(() => cmd.Label = invalidLabel); } @@ -100,7 +100,7 @@ public void Label_SetInvalidLabelLength_ThrowsArgException(int length) [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); @@ -109,7 +109,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void CreateCommandApdu_Cla0() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); @@ -119,7 +119,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x02() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); @@ -129,7 +129,7 @@ public void CreateCommandApdu_Ins0x02() [Fact] public void CreateCommandApdu_P1Is0() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); @@ -139,7 +139,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); @@ -149,11 +149,11 @@ public void CreateCommandApdu_P2Is0() [Fact] public void CreateCommandApdu_DataContainsMgmtKeyTag() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7b) { @@ -167,11 +167,11 @@ public void CreateCommandApdu_DataContainsMgmtKeyTag() [Fact] public void CreateCommandApdu_DataContainsMgmtKeyValue() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x7b) { @@ -187,11 +187,11 @@ public void CreateCommandApdu_DataContainsMgmtKeyValue() [Fact] public void CreateCommandApdu_DataContainsLabelTag() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { @@ -205,11 +205,11 @@ public void CreateCommandApdu_DataContainsLabelTag() [Fact] public void CreateCommandApdu_DataContainsLabelValue() { - DeleteCredentialCommand command = + var command = new DeleteCredentialCommand(_mgmtKey, _label); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs index 88ff6bdf..3973c632 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysCommandTests.cs @@ -33,7 +33,7 @@ public class GetAes128SessionKeysCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, @@ -87,7 +87,7 @@ public void Constructor_GivenInvalidHsmDeviceChallengeLength_ThrowsArgumentExcep [Fact] public void CreateCommandApdu_Cla0() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, @@ -101,7 +101,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x03() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, @@ -115,7 +115,7 @@ public void CreateCommandApdu_Ins0x03() [Fact] public void CreateCommandApdu_P1Is0() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, @@ -129,7 +129,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, @@ -143,14 +143,14 @@ public void CreateCommandApdu_P2Is0() [Fact] public void CreateCommandApdu_DataContainsLabelTag() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { @@ -164,14 +164,14 @@ public void CreateCommandApdu_DataContainsLabelTag() [Fact] public void CreateCommandApdu_DataContainsLabelValue() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x71) { @@ -187,14 +187,14 @@ public void CreateCommandApdu_DataContainsLabelValue() [Fact] public void CreateCommandApdu_DataContainsContextTag() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x77) { @@ -208,14 +208,14 @@ public void CreateCommandApdu_DataContainsContextTag() [Fact] public void CreateCommandApdu_DataContainsContextLength16() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x77) { @@ -231,14 +231,14 @@ public void CreateCommandApdu_DataContainsContextLength16() [Fact] public void CreateCommandApdu_DataContainsContextValue() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x77) { @@ -257,14 +257,14 @@ public void CreateCommandApdu_DataContainsContextValue() [Fact] public void CreateCommandApdu_DataContainsCredPasswordTag() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x73) { @@ -278,14 +278,14 @@ public void CreateCommandApdu_DataContainsCredPasswordTag() [Fact] public void CreateCommandApdu_DataContainsCredPasswordValue() { - GetAes128SessionKeysCommand command = new GetAes128SessionKeysCommand( + var command = new GetAes128SessionKeysCommand( _label, _password, _hostChallenge, _hsmDeviceChallenge); CommandApdu apdu = command.CreateCommandApdu(); - TlvReader reader = new TlvReader(apdu.Data); + var reader = new TlvReader(apdu.Data); int tag = reader.PeekTag(); while (reader.HasData && tag != 0x73) { diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponseTests.cs index 87adb33a..06a7f7e5 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetAes128SessionKeysResponseTests.cs @@ -40,9 +40,9 @@ private byte[] _data() [Fact] public void GetData_NotSuccess_ThrowsInvalidOperationException() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - GetAes128SessionKeysResponse response = new GetAes128SessionKeysResponse(apdu); + var response = new GetAes128SessionKeysResponse(apdu); Action action = () => response.GetData(); @@ -54,9 +54,9 @@ public void GetData_NotSuccess_ThrowsInvalidOperationException() [InlineData(48 + 1)] public void GetData_InvalidDataLength_ThrowsMalformedResponseException(int dataLength) { - ResponseApdu apdu = new ResponseApdu(new byte[dataLength], SWConstants.Success); + var apdu = new ResponseApdu(new byte[dataLength], SWConstants.Success); - GetAes128SessionKeysResponse response = new GetAes128SessionKeysResponse(apdu); + var response = new GetAes128SessionKeysResponse(apdu); Action action = () => response.GetData(); @@ -66,9 +66,9 @@ public void GetData_InvalidDataLength_ThrowsMalformedResponseException(int dataL [Fact] public void GetData_Success_ReturnsExpectedEncryptionSessionKey() { - ResponseApdu apdu = new ResponseApdu(_data(), SWConstants.Success); + var apdu = new ResponseApdu(_data(), SWConstants.Success); - GetAes128SessionKeysResponse response = new GetAes128SessionKeysResponse(apdu); + var response = new GetAes128SessionKeysResponse(apdu); SessionKeys sessionKeys = response.GetData(); Assert.Equal(_encKey, sessionKeys.EncryptionKey.ToArray()); @@ -77,9 +77,9 @@ public void GetData_Success_ReturnsExpectedEncryptionSessionKey() [Fact] public void GetData_Success_ReturnsExpectedMacSessionKey() { - ResponseApdu apdu = new ResponseApdu(_data(), SWConstants.Success); + var apdu = new ResponseApdu(_data(), SWConstants.Success); - GetAes128SessionKeysResponse response = new GetAes128SessionKeysResponse(apdu); + var response = new GetAes128SessionKeysResponse(apdu); SessionKeys sessionKeys = response.GetData(); Assert.Equal(_macKey, sessionKeys.MacKey.ToArray()); @@ -88,9 +88,9 @@ public void GetData_Success_ReturnsExpectedMacSessionKey() [Fact] public void GetData_Success_ReturnsExpectedRmacSessionKey() { - ResponseApdu apdu = new ResponseApdu(_data(), SWConstants.Success); + var apdu = new ResponseApdu(_data(), SWConstants.Success); - GetAes128SessionKeysResponse response = new GetAes128SessionKeysResponse(apdu); + var response = new GetAes128SessionKeysResponse(apdu); SessionKeys sessionKeys = response.GetData(); Assert.Equal(_rmacKey, sessionKeys.RmacKey.ToArray()); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs index f6455a43..ca435ec6 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionCommandTests.cs @@ -22,7 +22,7 @@ public class GetApplicationVersionCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); } @@ -30,7 +30,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void CreateCommandApdu_Cla0() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Cla); @@ -39,7 +39,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x07() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0x07, apdu.Ins); @@ -48,7 +48,7 @@ public void CreateCommandApdu_Ins0x07() [Fact] public void CreateCommandApdu_P1Is0() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P1); @@ -57,7 +57,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P2); @@ -66,7 +66,7 @@ public void CreateCommandApdu_P2Is0() [Fact] public void CreateCommandApdu_DataLength0() { - GetApplicationVersionCommand command = new GetApplicationVersionCommand(); + var command = new GetApplicationVersionCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Data.Length); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponseTests.cs index 6b61a349..44e19bb2 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetApplicationVersionResponseTests.cs @@ -23,9 +23,9 @@ public class GetApplicationVersionResponseTests [Fact] public void Constructor_ReturnsObject() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.Success); + var apdu = new ResponseApdu(new byte[0], SWConstants.Success); - GetApplicationVersionResponse response = new GetApplicationVersionResponse(apdu); + var response = new GetApplicationVersionResponse(apdu); Assert.NotNull(response); } @@ -33,9 +33,9 @@ public void Constructor_ReturnsObject() [Fact] public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - GetApplicationVersionResponse response = new GetApplicationVersionResponse(apdu); + var response = new GetApplicationVersionResponse(apdu); Action action = () => response.GetData(); @@ -45,9 +45,9 @@ public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() [Fact] public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - GetApplicationVersionResponse response = new GetApplicationVersionResponse(apdu); + var response = new GetApplicationVersionResponse(apdu); try { @@ -62,12 +62,12 @@ public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() [Fact] public void GetData_Given1dot2dot3_ReturnsAppV1dot2dot3() { - ApplicationVersion expectedAppVersion = new ApplicationVersion(1, 2, 3); + var expectedAppVersion = new ApplicationVersion(1, 2, 3); byte[] dataWithoutSw = new byte[] { 1, 2, 3 }; - ResponseApdu apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); - GetApplicationVersionResponse response = new GetApplicationVersionResponse(apdu); + var response = new GetApplicationVersionResponse(apdu); ApplicationVersion appVersion = response.GetData(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs index 851aa9e8..65900b7e 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesCommandTests.cs @@ -25,7 +25,7 @@ public class GetManagementKeyRetriesCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - GetManagementKeyRetriesCommand command = + var command = new GetManagementKeyRetriesCommand(); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); @@ -34,7 +34,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void CreateCommandApdu_Cla0() { - GetManagementKeyRetriesCommand command = + var command = new GetManagementKeyRetriesCommand(); CommandApdu apdu = command.CreateCommandApdu(); @@ -44,7 +44,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x09() { - GetManagementKeyRetriesCommand command = + var command = new GetManagementKeyRetriesCommand(); CommandApdu apdu = command.CreateCommandApdu(); @@ -54,7 +54,7 @@ public void CreateCommandApdu_Ins0x09() [Fact] public void CreateCommandApdu_P1Is0() { - GetManagementKeyRetriesCommand command = + var command = new GetManagementKeyRetriesCommand(); CommandApdu apdu = command.CreateCommandApdu(); @@ -64,7 +64,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - GetManagementKeyRetriesCommand command = + var command = new GetManagementKeyRetriesCommand(); CommandApdu apdu = command.CreateCommandApdu(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesResponseTests.cs index 36466b3b..edd6513d 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/GetManagementKeyRetriesResponseTests.cs @@ -23,9 +23,9 @@ public class GetManagementKeyRetriesResponseTests [Fact] public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - GetManagementKeyRetriesResponse response = + var response = new GetManagementKeyRetriesResponse(apdu); Action action = () => response.GetData(); @@ -36,9 +36,9 @@ public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() [Fact] public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - GetManagementKeyRetriesResponse response = + var response = new GetManagementKeyRetriesResponse(apdu); try @@ -55,9 +55,9 @@ public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() public void GetData_SuccessApdu6Retries_Returns6Retries() { byte[] dataWithoutSw = new byte[] { 6 }; - ResponseApdu apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); - GetManagementKeyRetriesResponse response = + var response = new GetManagementKeyRetriesResponse(apdu); int retries = response.GetData(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs index 0bcacb2c..5d8eb761 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsCommandTests.cs @@ -22,7 +22,7 @@ public class ListCredentialsCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); } @@ -30,7 +30,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void Constructor_ReturnsObject() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); Assert.NotNull(command); } @@ -38,7 +38,7 @@ public void Constructor_ReturnsObject() [Fact] public void CreateCommandApdu_Cla0() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Cla); @@ -47,7 +47,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x05() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0x05, apdu.Ins); @@ -56,7 +56,7 @@ public void CreateCommandApdu_Ins0x05() [Fact] public void CreateCommandApdu_P1Is0() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P1); @@ -65,7 +65,7 @@ public void CreateCommandApdu_P1Is0() [Fact] public void CreateCommandApdu_P2Is0() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.P2); @@ -74,7 +74,7 @@ public void CreateCommandApdu_P2Is0() [Fact] public void CreateCommandApdu_DataLength0() { - ListCredentialsCommand command = new ListCredentialsCommand(); + var command = new ListCredentialsCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Data.Length); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs index bd2fc1c6..6292e449 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ListCredentialsResponseTests.cs @@ -25,9 +25,9 @@ public class ListCredentialsResponseTests [Fact] public void Constructor_ReturnsObject() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.Success); + var apdu = new ResponseApdu(new byte[0], SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); Assert.NotNull(response); } @@ -35,9 +35,9 @@ public void Constructor_ReturnsObject() [Fact] public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); Action action = () => response.GetData(); @@ -47,9 +47,9 @@ public void GetData_ResponseStatusFailed_ThrowsInvalidOperationException() [Fact] public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); + var apdu = new ResponseApdu(new byte[0], SWConstants.AuthenticationMethodBlocked); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); try { @@ -65,9 +65,9 @@ public void GetData_ResponseStatusFailed_ExceptionMessageMatchesStatusMessage() public void GetData_DataTagAlgorithm_ThrowsMalformedException() { byte[] dataWithoutSw = new byte[] { DataTagConstants.CryptographicKeyType, 1, 0 }; - ResponseApdu apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); Action action = () => response.GetData(); @@ -81,9 +81,9 @@ public void GetData_DataTagAlgorithm_ExceptionMessageInvalidDataTag() $"a data tag supported by the YubiKey application."; byte[] dataWithoutSw = new byte[] { DataTagConstants.CryptographicKeyType, 1, 0 }; - ResponseApdu apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw, SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); try { @@ -104,7 +104,7 @@ public void GetData_InvalidElementSize_ThrowsMalformedException(int labelLength) // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List + var credRetryData = new List { (byte)CryptographicKeyType.None, 0 @@ -112,16 +112,16 @@ public void GetData_InvalidElementSize_ThrowsMalformedException(int labelLength) credRetryData.AddRange(Encoding.UTF8.GetBytes(new char[labelLength])); credRetryData.Add(0); - List dataWithoutSw = new List + var dataWithoutSw = new List { DataTagConstants.LabelList, (byte)credRetryData.Count }; dataWithoutSw.AddRange(credRetryData); - ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); Action action = () => response.GetData(); @@ -137,7 +137,7 @@ public void GetData_ElementSize3_ExceptionMessageInvalidCredRetryDataLength() // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List + var credRetryData = new List { (byte)CryptographicKeyType.None, 0 @@ -145,16 +145,16 @@ public void GetData_ElementSize3_ExceptionMessageInvalidCredRetryDataLength() credRetryData.AddRange(Encoding.UTF8.GetBytes(new char[0])); credRetryData.Add(0); - List dataWithoutSw = new List + var dataWithoutSw = new List { DataTagConstants.LabelList, (byte)credRetryData.Count }; dataWithoutSw.AddRange(credRetryData); - ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); string actualMessage = ""; try @@ -172,9 +172,9 @@ public void GetData_ElementSize3_ExceptionMessageInvalidCredRetryDataLength() [Fact] public void GetData_ZeroElements_ReturnsEmptyList() { - ResponseApdu apdu = new ResponseApdu(new byte[0], SWConstants.Success); + var apdu = new ResponseApdu(new byte[0], SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); List credentialRetryPairs = response.GetData(); @@ -195,7 +195,7 @@ public void GetData_OneElement_MatchesExpectedCredRetryObject(int labelSize) // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List + var credRetryData = new List { (byte)expectedKeyType, expectedTouch ? (byte)1 : (byte)0 @@ -203,16 +203,16 @@ public void GetData_OneElement_MatchesExpectedCredRetryObject(int labelSize) credRetryData.AddRange(Encoding.UTF8.GetBytes(expectedLabel)); credRetryData.Add(expectedRetryCount); - List dataWithoutSw = new List + var dataWithoutSw = new List { DataTagConstants.LabelList, (byte)credRetryData.Count }; dataWithoutSw.AddRange(credRetryData); - ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); List pairs = response.GetData(); @@ -240,7 +240,7 @@ public void GetData_TwoElements_MatchesExpectedCredRetryObjects() // Touch - false // Label - string of given size // Retries - 0 - List credRetryData = new List + var credRetryData = new List { (byte)expectedKeyType, expectedTouch ? (byte)1 : (byte)0 @@ -248,7 +248,7 @@ public void GetData_TwoElements_MatchesExpectedCredRetryObjects() credRetryData.AddRange(Encoding.UTF8.GetBytes(expectedLabel)); credRetryData.Add(expectedRetryCount); - List dataWithoutSw = new List + var dataWithoutSw = new List { // First element DataTagConstants.LabelList, @@ -261,9 +261,9 @@ public void GetData_TwoElements_MatchesExpectedCredRetryObjects() dataWithoutSw.Add((byte)credRetryData.Count); dataWithoutSw.AddRange(credRetryData); - ResponseApdu apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); + var apdu = new ResponseApdu(dataWithoutSw.ToArray(), SWConstants.Success); - ListCredentialsResponse response = new ListCredentialsResponse(apdu); + var response = new ListCredentialsResponse(apdu); List pairs = response.GetData(); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs index baeaeb61..542ebfb0 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/Commands/ResetApplicationCommandTests.cs @@ -22,7 +22,7 @@ public class ResetApplicationCommandTests [Fact] public void Application_Get_ReturnsYubiHsmAuth() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); Assert.Equal(YubiKeyApplication.YubiHsmAuth, command.Application); } @@ -30,7 +30,7 @@ public void Application_Get_ReturnsYubiHsmAuth() [Fact] public void Constructor_ReturnsObject() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); Assert.NotNull(command); } @@ -38,7 +38,7 @@ public void Constructor_ReturnsObject() [Fact] public void CreateCommandApdu_Cla0() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Cla); @@ -47,7 +47,7 @@ public void CreateCommandApdu_Cla0() [Fact] public void CreateCommandApdu_Ins0x06() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0x06, apdu.Ins); @@ -56,7 +56,7 @@ public void CreateCommandApdu_Ins0x06() [Fact] public void CreateCommandApdu_P1Is0xde() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0xde, apdu.P1); @@ -65,7 +65,7 @@ public void CreateCommandApdu_P1Is0xde() [Fact] public void CreateCommandApdu_P2Is0xad() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0xad, apdu.P2); @@ -74,7 +74,7 @@ public void CreateCommandApdu_P2Is0xad() [Fact] public void CreateCommandApdu_DataLength0() { - ResetApplicationCommand command = new ResetApplicationCommand(); + var command = new ResetApplicationCommand(); CommandApdu apdu = command.CreateCommandApdu(); Assert.Equal(0, apdu.Data.Length); diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs index 05b2a02b..3d1c49ce 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialRetryPairTests.cs @@ -29,14 +29,14 @@ public class CredentialRetryPairTests [Fact] public void Constructor_ReturnsObject() { - CredentialRetryPair pair = new CredentialRetryPair(cred, 0); + var pair = new CredentialRetryPair(cred, 0); Assert.NotNull(pair); } [Fact] public void Constructor_Given2Retries_SetsRetriesTo2() { - CredentialRetryPair pair = new CredentialRetryPair(cred, 2); + var pair = new CredentialRetryPair(cred, 2); Assert.Equal(2, pair.Retries); } diff --git a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs index 03a6db2b..18d0fcc7 100644 --- a/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs +++ b/Yubico.YubiKey/tests/unit/Yubico/YubiKey/YubiHsmAuth/CredentialTests.cs @@ -25,7 +25,7 @@ public void Constructor_KeyTypeAes128_ObjectKeyTypeAes128() { CryptographicKeyType expectedKeyType = CryptographicKeyType.Aes128; - Credential cred = new Credential( + var cred = new Credential( expectedKeyType, "test key", false); @@ -58,7 +58,7 @@ public void Constructor_LabelTestKey_ObjectLabelTestKey() { string expectedLabel = "test key"; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, expectedLabel, false); @@ -84,7 +84,7 @@ public void Constructor_TouchRequiredTrue_ObjectTouchRequiredTrue() { bool expectedTouchRequired = true; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "test key", expectedTouchRequired); @@ -99,7 +99,7 @@ public void KeyType_GetSetAes128_KeyTypeIsAes128() { CryptographicKeyType expectedKeyType = CryptographicKeyType.Aes128; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "test key", false) @@ -113,9 +113,9 @@ public void KeyType_GetSetAes128_KeyTypeIsAes128() [Fact] public void KeyType_SetNegative1_ThrowsArgOutOfRange() { - CryptographicKeyType invalidKeyType = (CryptographicKeyType)(-1); + var invalidKeyType = (CryptographicKeyType)(-1); - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "test key", false); @@ -129,7 +129,7 @@ public void KeyType_SetNone_ThrowsArgOutOfRange() { CryptographicKeyType invalidKeyType = CryptographicKeyType.None; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "test key", false); @@ -159,7 +159,7 @@ public void Label_SetGetLabel_ReturnsMatchingString(int labelLength) { string expectedLabel = new string('a', labelLength); - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "old label", false) @@ -175,7 +175,7 @@ public void Label_SetNonUtf8Character_ThrowsArgException() { string expectedLabel = "abc\uD801\uD802d"; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "old label", false); @@ -191,7 +191,7 @@ public void Label_SetInvalidLabelLength_ThrowsArgOutOfRangeException(int labelLe { string expectedLabel = new string('a', labelLength); - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "old label", false); @@ -207,7 +207,7 @@ public void TouchRequired_SetGetTrue_ReturnsTrue() { bool expectedTouch = true; - Credential cred = new Credential( + var cred = new Credential( CryptographicKeyType.Aes128, "test key", false)