From 6343b7c43e3d23bfc7e1b4fd409a50c97b78918f Mon Sep 17 00:00:00 2001 From: Matthew Layton <9935122+MrMatthewLayton@users.noreply.github.com> Date: Sun, 24 Jul 2022 06:31:43 +0100 Subject: [PATCH] Upgrade/v5 (#7) Updated .NET 6, C# 10, license headers and readme. Introduced file-scoped namespaces and added multiple code improvements and tests. --- .editorconfig | 4 + .github/workflows/dotnet.yml | 2 +- OnixLabs.Core.UnitTests/Base16Tests.cs | 69 -- .../Base32Base32HexAlphabetTests.cs | 85 --- .../Base32CrockfordAlphabetTests.cs | 85 --- .../Base32DefaultAlphabetTests.cs | 85 --- .../Base32ZBase32AlphabetTests.cs | 85 --- .../Base58DefaultAlphabetTests.cs | 69 -- .../Base58FlickrAlphabetTests.cs | 69 -- .../Base58RippleAlphabetTests.cs | 69 -- OnixLabs.Core.UnitTests/Base64Tests.cs | 69 -- OnixLabs.Core.UnitTests/EnumerationTests.cs | 161 +++-- OnixLabs.Core.UnitTests/MockData/Color.cs | 19 +- .../OnixLabs.Core.UnitTests.csproj | 4 +- OnixLabs.Core.UnitTests/PreconditionTests.cs | 34 + .../StringExtensionTests.cs | 218 ++++--- OnixLabs.Core.UnitTests/Text/Base16Tests.cs | 68 ++ .../Text/Base32Base32HexAlphabetTests.cs | 84 +++ .../Text/Base32CrockfordAlphabetTests.cs | 84 +++ .../Text/Base32DefaultAlphabetTests.cs | 84 +++ .../Text/Base32ZBase32AlphabetTests.cs | 84 +++ .../Text/Base58DefaultAlphabetTests.cs | 68 ++ .../Text/Base58FlickrAlphabetTests.cs | 68 ++ .../Text/Base58RippleAlphabetTests.cs | 68 ++ OnixLabs.Core.UnitTests/Text/Base64Tests.cs | 68 ++ OnixLabs.Core/ArrayExtensions.cs | 87 ++- OnixLabs.Core/Enumeration.Comparable.cs | 49 +- OnixLabs.Core/Enumeration.Equatable.cs | 105 ++- OnixLabs.Core/Enumeration.From.cs | 82 +-- OnixLabs.Core/Enumeration.Get.cs | 85 ++- OnixLabs.Core/Enumeration.To.cs | 34 +- OnixLabs.Core/Enumeration.cs | 47 +- OnixLabs.Core/HashCodeExtensions.cs | 57 +- OnixLabs.Core/Linq/IEnumerableExtensions.cs | 262 ++++---- OnixLabs.Core/OnixLabs.Core.csproj | 10 +- OnixLabs.Core/Preconditions.cs | 59 ++ OnixLabs.Core/StringExtensions.cs | 375 ++++++----- OnixLabs.Core/Text/Base16.Empty.cs | 29 +- OnixLabs.Core/Text/Base16.Equatable.cs | 97 ++- OnixLabs.Core/Text/Base16.From.cs | 143 +++-- OnixLabs.Core/Text/Base16.Parse.cs | 65 +- OnixLabs.Core/Text/Base16.To.cs | 71 +-- OnixLabs.Core/Text/Base16.cs | 33 +- OnixLabs.Core/Text/Base32.Codec.cs | 213 +++---- OnixLabs.Core/Text/Base32.Empty.cs | 29 +- OnixLabs.Core/Text/Base32.Equatable.cs | 99 ++- OnixLabs.Core/Text/Base32.From.cs | 603 +++++++++--------- OnixLabs.Core/Text/Base32.Parse.cs | 127 ++-- OnixLabs.Core/Text/Base32.To.cs | 71 +-- OnixLabs.Core/Text/Base32.cs | 57 +- OnixLabs.Core/Text/Base32Alphabet.cs | 89 ++- OnixLabs.Core/Text/Base58.Checksum.cs | 125 ++-- OnixLabs.Core/Text/Base58.Codec.cs | 113 ++-- OnixLabs.Core/Text/Base58.Empty.cs | 29 +- OnixLabs.Core/Text/Base58.Equatable.cs | 98 ++- OnixLabs.Core/Text/Base58.From.cs | 315 +++++---- OnixLabs.Core/Text/Base58.Parse.cs | 275 ++++---- OnixLabs.Core/Text/Base58.To.cs | 89 ++- OnixLabs.Core/Text/Base58.cs | 45 +- OnixLabs.Core/Text/Base58Alphabet.cs | 69 +- OnixLabs.Core/Text/Base64.Empty.cs | 29 +- OnixLabs.Core/Text/Base64.Equatable.cs | 97 ++- OnixLabs.Core/Text/Base64.From.cs | 143 +++-- OnixLabs.Core/Text/Base64.Parse.cs | 65 +- OnixLabs.Core/Text/Base64.To.cs | 71 +-- OnixLabs.Core/Text/Base64.cs | 33 +- .../OnixLabs.Playground.csproj | 3 +- OnixLabs.Playground/Program.cs | 11 +- .../EcdsaEncryptedPkcs8Tests.cs | 153 +++-- .../EcdsaKeyPkcs8Tests.cs | 137 ++-- .../EcdsaKeyTests.cs | 167 +++-- .../HashAsyncTests.cs | 41 +- .../HashTests.cs | 115 ++-- .../HmacAsyncTests.cs | 69 +- .../HmacTests.cs | 107 ++-- .../KeyTestBase.cs | 19 +- .../MerkleTreeTests.cs | 81 ++- ...abs.Security.Cryptography.UnitTests.csproj | 4 +- .../RsaKeyEncryptedPkcs8Tests.cs | 159 +++-- .../RsaKeyPkcs8Tests.cs | 143 +++-- .../RsaKeyTests.cs | 179 +++--- .../Sha3Hash224Tests.cs | 39 +- .../Sha3Hash256Tests.cs | 39 +- .../Sha3Hash384Tests.cs | 65 +- .../Sha3Hash512Tests.cs | 59 +- .../Sha3HashTestBase.cs | 41 +- .../Sha3Shake128Tests.cs | 69 +- .../Sha3Shake256Tests.cs | 69 +- .../Sha3ShakeTestBase.cs | 41 +- .../DigitalSignature.Empty.cs | 29 +- .../DigitalSignature.Equatable.cs | 97 ++- .../DigitalSignature.From.cs | 103 ++- .../DigitalSignature.To.cs | 137 ++-- .../DigitalSignature.Validation.cs | 133 ++-- .../DigitalSignature.cs | 33 +- .../EcdsaPrivateKey.Export.cs | 59 +- .../EcdsaPrivateKey.From.cs | 113 ++-- .../EcdsaPrivateKey.Get.cs | 27 +- .../EcdsaPrivateKey.Import.cs | 204 +++--- .../EcdsaPrivateKey.Sign.cs | 65 +- .../EcdsaPrivateKey.cs | 23 +- .../EcdsaPublicKey.From.cs | 113 ++-- .../EcdsaPublicKey.Verify.cs | 69 +- .../EcdsaPublicKey.cs | 23 +- .../Hash.AllOneHash.cs | 73 +-- .../Hash.AllZeroHash.cs | 71 +-- .../Hash.Compute.Md5Hash.cs | 63 +- .../Hash.Compute.Sha1Hash.cs | 63 +- .../Hash.Compute.Sha2Hash256.cs | 63 +- .../Hash.Compute.Sha2Hash384.cs | 63 +- .../Hash.Compute.Sha2Hash512.cs | 63 +- .../Hash.Compute.Sha3Hash224.cs | 63 +- .../Hash.Compute.Sha3Hash256.cs | 63 +- .../Hash.Compute.Sha3Hash384.cs | 63 +- .../Hash.Compute.Sha3Hash512.cs | 63 +- .../Hash.Compute.Sha3Shake128.cs | 69 +- .../Hash.Compute.Sha3Shake256.cs | 69 +- .../Hash.Compute.cs | 143 +++-- .../Hash.ComputeAsync.Md5Hash.cs | 63 +- .../Hash.ComputeAsync.Sha1Hash.cs | 63 +- .../Hash.ComputeAsync.Sha2Hash256.cs | 63 +- .../Hash.ComputeAsync.Sha2Hash384.cs | 63 +- .../Hash.ComputeAsync.Sha2Hash512.cs | 63 +- .../Hash.ComputeAsync.Sha3Hash224.cs | 63 +- .../Hash.ComputeAsync.Sha3Hash256.cs | 63 +- .../Hash.ComputeAsync.Sha3Hash384.cs | 63 +- .../Hash.ComputeAsync.Sha3Hash512.cs | 63 +- .../Hash.ComputeAsync.Sha3Shake128.cs | 69 +- .../Hash.ComputeAsync.Sha3Shake256.cs | 69 +- .../Hash.ComputeAsync.cs | 151 +++-- .../Hash.ComputeTwice.cs | 147 +++-- .../Hash.ComputeTwiceAsync.cs | 159 +++-- .../Hash.Concantenate.cs | 109 ++-- OnixLabs.Security.Cryptography/Hash.Empty.cs | 29 +- .../Hash.Equatable.cs | 98 ++- OnixLabs.Security.Cryptography/Hash.From.cs | 125 ++-- OnixLabs.Security.Cryptography/Hash.Parse.cs | 137 ++-- OnixLabs.Security.Cryptography/Hash.To.cs | 153 +++-- OnixLabs.Security.Cryptography/Hash.cs | 47 +- .../HashAlgorithmType.Enumerations.cs | 177 +++-- .../HashAlgorithmType.Equatable.cs | 35 - .../HashAlgorithmType.Get.cs | 141 ++-- .../HashAlgorithmType.Verify.cs | 45 +- .../HashAlgorithmType.cs | 64 +- .../Hmac.Compute.Md5Hmac.cs | 73 ++- .../Hmac.Compute.Sha1Hmac.cs | 73 ++- .../Hmac.Compute.Sha2Hmac256.cs | 73 ++- .../Hmac.Compute.Sha2Hmac384.cs | 73 ++- .../Hmac.Compute.Sha2Hmac512.cs | 73 ++- .../Hmac.Compute.cs | 83 ++- .../Hmac.ComputeAsync.Md5Hmac.cs | 73 ++- .../Hmac.ComputeAsync.Sha1Hmac.cs | 73 ++- .../Hmac.ComputeAsync.Sha2Hmac256.cs | 73 ++- .../Hmac.ComputeAsync.Sha2Hmac384.cs | 73 ++- .../Hmac.ComputeAsync.Sha2Hmac512.cs | 73 ++- .../Hmac.ComputeAsync.cs | 89 ++- OnixLabs.Security.Cryptography/Hmac.Create.cs | 25 +- OnixLabs.Security.Cryptography/Hmac.Empty.cs | 29 +- .../Hmac.Equatable.cs | 98 ++- OnixLabs.Security.Cryptography/Hmac.Parse.cs | 69 +- OnixLabs.Security.Cryptography/Hmac.To.cs | 37 +- OnixLabs.Security.Cryptography/Hmac.Verify.cs | 117 ++-- OnixLabs.Security.Cryptography/Hmac.cs | 55 +- .../KeyPair.Create.cs | 200 +++--- .../KeyPair.Equatable.cs | 103 ++- .../KeyPair.From.cs | 56 +- OnixLabs.Security.Cryptography/KeyPair.cs | 57 +- .../MerkleTree.Equatable.cs | 99 ++- OnixLabs.Security.Cryptography/MerkleTree.cs | 202 +++--- .../MerkleTreeBranchNode.cs | 53 +- .../MerkleTreeLeafNode.cs | 65 +- .../OnixLabs.Security.Cryptography.csproj | 9 +- .../PrivateKey.Equatable.cs | 105 ++- .../PrivateKey.Export.cs | 75 ++- .../PrivateKey.Get.cs | 19 +- .../PrivateKey.Sign.cs | 51 +- .../PrivateKey.To.cs | 137 ++-- OnixLabs.Security.Cryptography/PrivateKey.cs | 47 +- .../PublicKey.Equatable.cs | 105 ++- .../PublicKey.To.cs | 137 ++-- .../PublicKey.Verify.cs | 123 ++-- OnixLabs.Security.Cryptography/PublicKey.cs | 47 +- .../RsaPrivateKey.Equatable.cs | 25 +- .../RsaPrivateKey.Export.cs | 59 +- .../RsaPrivateKey.From.cs | 123 ++-- .../RsaPrivateKey.Get.cs | 27 +- .../RsaPrivateKey.Import.cs | 268 ++++---- .../RsaPrivateKey.Sign.cs | 67 +- .../RsaPrivateKey.cs | 37 +- .../RsaPublicKey.Equatable.cs | 25 +- .../RsaPublicKey.From.cs | 123 ++-- .../RsaPublicKey.Verify.cs | 71 +-- .../RsaPublicKey.cs | 37 +- OnixLabs.Security.Cryptography/Sha3.Create.cs | 105 ++- .../Sha3.Permute.cs | 241 ++++--- OnixLabs.Security.Cryptography/Sha3.cs | 251 ++++---- OnixLabs.Security.Cryptography/Sha3Hash224.cs | 37 +- OnixLabs.Security.Cryptography/Sha3Hash256.cs | 37 +- OnixLabs.Security.Cryptography/Sha3Hash384.cs | 37 +- OnixLabs.Security.Cryptography/Sha3Hash512.cs | 39 +- .../Sha3Shake128.cs | 39 +- .../Sha3Shake256.cs | 39 +- README.md | 2 +- 203 files changed, 8674 insertions(+), 8766 deletions(-) create mode 100644 .editorconfig delete mode 100644 OnixLabs.Core.UnitTests/Base16Tests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base32Base32HexAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base32CrockfordAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base32DefaultAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base32ZBase32AlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base58DefaultAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base58FlickrAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base58RippleAlphabetTests.cs delete mode 100644 OnixLabs.Core.UnitTests/Base64Tests.cs create mode 100644 OnixLabs.Core.UnitTests/PreconditionTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base16Tests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base32Base32HexAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base32CrockfordAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base32DefaultAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base32ZBase32AlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base58DefaultAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base58FlickrAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base58RippleAlphabetTests.cs create mode 100644 OnixLabs.Core.UnitTests/Text/Base64Tests.cs create mode 100644 OnixLabs.Core/Preconditions.cs delete mode 100644 OnixLabs.Security.Cryptography/HashAlgorithmType.Equatable.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..df8f9a8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +root = true + +[*] +max_line_length = 140 diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index f6f6de0..fdee6ea 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -19,7 +19,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: 5.0.x + dotnet-version: 6.0.x - name: Restore dependencies run: dotnet restore - name: Build diff --git a/OnixLabs.Core.UnitTests/Base16Tests.cs b/OnixLabs.Core.UnitTests/Base16Tests.cs deleted file mode 100644 index b5851f4..0000000 --- a/OnixLabs.Core.UnitTests/Base16Tests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base16Tests - { - [Fact(DisplayName = "Identical Base16 values produce identical hash codes.")] - public void IdenticalBase16ValuesProduceIdenticalHashCodes() - { - // Arrange - Base16 a = Base16.FromString("abcdefghijklmnopqrstuvwxyz"); - Base16 b = Base16.FromString("abcdefghijklmnopqrstuvwxyz"); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base16_FromString should produce the expected Base-16 value.")] - [InlineData("31323334353637383930", "1234567890")] - [InlineData("4142434445464748494a4b4c4d4e4f505152535455565758595a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("6162636465666768696a6b6c6d6e6f707172737475767778797a", "abcdefghijklmnopqrstuvwxyz")] - public void Base16FromStringShouldProduceTheExpectedBase16Value(string expected, string value) - { - // Arrange - Base16 candidate = Base16.FromString(value); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base16_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "31323334353637383930")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "4142434445464748494a4b4c4d4e4f505152535455565758595a")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "6162636465666768696a6b6c6d6e6f707172737475767778797a")] - public void Base16ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base16 candidate = Base16.Parse(value); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base32Base32HexAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base32Base32HexAlphabetTests.cs deleted file mode 100644 index afb428d..0000000 --- a/OnixLabs.Core.UnitTests/Base32Base32HexAlphabetTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base32Base32HexAlphabetTests - { - [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] - public void IdenticalBase32ValuesProduceIdenticalHashCodes() - { - // Arrange - Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Base32Hex); - Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Base32Hex); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("64P36D1L6ORJGE9G", "1234567890")] - [InlineData("85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8======", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Base32Hex, true); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("64P36D1L6ORJGE9G", "1234567890")] - [InlineData("85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Base32Hex, false); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "64P36D1L6ORJGE9G")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8")] - public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base32 candidate = Base32.Parse(value, Base32Alphabet.Base32Hex); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base32CrockfordAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base32CrockfordAlphabetTests.cs deleted file mode 100644 index 21a1ab6..0000000 --- a/OnixLabs.Core.UnitTests/Base32CrockfordAlphabetTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base32CrockfordAlphabetTests - { - [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] - public void IdenticalBase32ValuesProduceIdenticalHashCodes() - { - // Arrange - Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Crockford); - Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Crockford); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("64S36D1N6RVKGE9G", "1234567890")] - [InlineData("85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8======", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Crockford, true); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("64S36D1N6RVKGE9G", "1234567890")] - [InlineData("85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Crockford, false); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "64S36D1N6RVKGE9G")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8")] - public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base32 candidate = Base32.Parse(value, Base32Alphabet.Crockford); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base32DefaultAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base32DefaultAlphabetTests.cs deleted file mode 100644 index 9a45319..0000000 --- a/OnixLabs.Core.UnitTests/Base32DefaultAlphabetTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base32DefaultAlphabetTests - { - [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] - public void IdenticalBase32ValuesProduceIdenticalHashCodes() - { - // Arrange - Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Default); - Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Default); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("GEZDGNBVGY3TQOJQ", "1234567890")] - [InlineData("IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI======", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Default, true); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("GEZDGNBVGY3TQOJQ", "1234567890")] - [InlineData("IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.Default, false); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "GEZDGNBVGY3TQOJQ")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI")] - public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base32 candidate = Base32.Parse(value, Base32Alphabet.Default); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base32ZBase32AlphabetTests.cs b/OnixLabs.Core.UnitTests/Base32ZBase32AlphabetTests.cs deleted file mode 100644 index f897eb1..0000000 --- a/OnixLabs.Core.UnitTests/Base32ZBase32AlphabetTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base32ZBase32AlphabetTests - { - [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] - public void IdenticalBase32ValuesProduceIdenticalHashCodes() - { - // Arrange - Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.ZBase32); - Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.ZBase32); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("gr3dgpbiga5uoqjo", "1234567890")] - [InlineData("efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe======", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.ZBase32, true); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] - [InlineData("gr3dgpbiga5uoqjo", "1234567890")] - [InlineData("efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe", "abcdefghijklmnopqrstuvwxyz")] - public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) - { - // Arrange - Base32 candidate = Base32.FromString(value, Base32Alphabet.ZBase32, false); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "gr3dgpbiga5uoqjo")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe")] - public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base32 candidate = Base32.Parse(value, Base32Alphabet.ZBase32); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base58DefaultAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base58DefaultAlphabetTests.cs deleted file mode 100644 index 7f81e2b..0000000 --- a/OnixLabs.Core.UnitTests/Base58DefaultAlphabetTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base58DefaultAlphabetTests - { - [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] - public void IdenticalBase58ValuesProduceIdenticalHashCodes() - { - // Arrange - Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Default); - Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Default); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] - [InlineData("3mJr7AoUCHxNqd", "1234567890")] - [InlineData("2zuFXTJSTRK6ESktqhM2QDBkCnH1U46CnxaD", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f", "abcdefghijklmnopqrstuvwxyz")] - public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) - { - // Arrange - Base58 candidate = Base58.FromString(value, Base58Alphabet.Default); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "3mJr7AoUCHxNqd")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "2zuFXTJSTRK6ESktqhM2QDBkCnH1U46CnxaD")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f")] - public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base58 candidate = Base58.Parse(value, Base58Alphabet.Default); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base58FlickrAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base58FlickrAlphabetTests.cs deleted file mode 100644 index 6377e0a..0000000 --- a/OnixLabs.Core.UnitTests/Base58FlickrAlphabetTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base58FlickrAlphabetTests - { - [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] - public void IdenticalBase58ValuesProduceIdenticalHashCodes() - { - // Arrange - Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Flickr); - Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Flickr); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] - [InlineData("3LiR7aNtchXnQC", "1234567890")] - [InlineData("2ZUfwsirsqj6erKTQGm2pdbKcMh1t46cMXzd", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("3YXt3U1HFx8vKFTJj92EAipcC4byHHs1V25E", "abcdefghijklmnopqrstuvwxyz")] - public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) - { - // Arrange - Base58 candidate = Base58.FromString(value, Base58Alphabet.Flickr); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "3LiR7aNtchXnQC")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "2ZUfwsirsqj6erKTQGm2pdbKcMh1t46cMXzd")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "3YXt3U1HFx8vKFTJj92EAipcC4byHHs1V25E")] - public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base58 candidate = Base58.Parse(value, Base58Alphabet.Flickr); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base58RippleAlphabetTests.cs b/OnixLabs.Core.UnitTests/Base58RippleAlphabetTests.cs deleted file mode 100644 index 347334c..0000000 --- a/OnixLabs.Core.UnitTests/Base58RippleAlphabetTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base58RippleAlphabetTests - { - [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] - public void IdenticalBase58ValuesProduceIdenticalHashCodes() - { - // Arrange - Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Ripple); - Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Ripple); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] - [InlineData("smJifwo7UHx4qd", "1234567890")] - [InlineData("pzuEXTJSTRKaNSktq6MpQDBkU8Hr7haU8x2D", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("syx7sur5gY3WkgtjK9pCbJQUdhBZ55TrvpnC", "abcdefghijklmnopqrstuvwxyz")] - public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) - { - // Arrange - Base58 candidate = Base58.FromString(value, Base58Alphabet.Ripple); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "smJifwo7UHx4qd")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "pzuEXTJSTRKaNSktq6MpQDBkU8Hr7haU8x2D")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "syx7sur5gY3WkgtjK9pCbJQUdhBZ55TrvpnC")] - public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base58 candidate = Base58.Parse(value, Base58Alphabet.Ripple); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/Base64Tests.cs b/OnixLabs.Core.UnitTests/Base64Tests.cs deleted file mode 100644 index 6b3b45f..0000000 --- a/OnixLabs.Core.UnitTests/Base64Tests.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using OnixLabs.Core.Text; -using Xunit; - -namespace OnixLabs.Core.UnitTests -{ - public sealed class Base64Tests - { - [Fact(DisplayName = "Identical Base64 values produce identical hash codes.")] - public void IdenticalBase64ValuesProduceIdenticalHashCodes() - { - // Arrange - Base64 a = Base64.FromString("abcdefghijklmnopqrstuvwxyz"); - Base64 b = Base64.FromString("abcdefghijklmnopqrstuvwxyz"); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Theory(DisplayName = "Base64_FromString should produce the expected Base-64 value.")] - [InlineData("MTIzNDU2Nzg5MA==", "1234567890")] - [InlineData("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", "abcdefghijklmnopqrstuvwxyz")] - public void Base64FromStringShouldProduceTheExpectedBase64Value(string expected, string value) - { - // Arrange - Base64 candidate = Base64.FromString(value); - - // Act - string actual = candidate.ToString(); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "Base64_Parse should produce the expected plain text value.")] - [InlineData("1234567890", "MTIzNDU2Nzg5MA==")] - [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=")] - [InlineData("abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] - public void Base64ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) - { - // Arrange - Base64 candidate = Base64.Parse(value); - - // Act - string actual = candidate.ToPlainTextString(); - - // Assert - Assert.Equal(expected, actual); - } - } -} diff --git a/OnixLabs.Core.UnitTests/EnumerationTests.cs b/OnixLabs.Core.UnitTests/EnumerationTests.cs index 21ddc73..4d3dfd2 100644 --- a/OnixLabs.Core.UnitTests/EnumerationTests.cs +++ b/OnixLabs.Core.UnitTests/EnumerationTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,62 +16,109 @@ using OnixLabs.Core.UnitTests.MockData; using Xunit; -namespace OnixLabs.Core.UnitTests +namespace OnixLabs.Core.UnitTests; + +public sealed class EnumerationTests { - public sealed class EnumerationTests + [Fact(DisplayName = "Enumerations should be equal")] + public void EnumerationsShouldBeEqual() + { + // Arrange + Color a = Color.Red; + Color b = Color.Red; + + // Assert + Assert.Equal(a, b); + } + + [Fact(DisplayName = "Enumerations should not be equal")] + public void EnumerationsShouldNotBeEqual() + { + // Arrange + Color a = Color.Red; + Color b = Color.Blue; + + // Assert + Assert.NotEqual(a, b); + } + + [Fact(DisplayName = "Enumeration should return all enumeration instances")] + public void EnumerationsShouldReturnAllEnumerationInstances() + { + // Arrange + IEnumerable colors = Color.GetAll(); + + // Assert + Assert.Contains(colors, item => item == Color.Red); + Assert.Contains(colors, item => item == Color.Green); + Assert.Contains(colors, item => item == Color.Blue); + } + + [Fact(DisplayName = "Enumeration.FromName should return the expected enumeration entry")] + public void EnumerationFromNameShouldReturnTheExpectedEnumerationEntry() + { + // Arrange + Color color = Color.FromName("Green"); + + // Assert + Assert.Equal(Color.Green, color); + } + + [Fact(DisplayName = "Enumeration.FromValue should return the expected enumeration entry")] + public void EnumerationFromValueShouldReturnTheExpectedEnumerationEntry() { - [Fact(DisplayName = "Enumerations should be equal")] - public void EnumerationsShouldBeEqual() - { - // Arrange - Color a = Color.Red; - Color b = Color.Red; - - // Assert - Assert.Equal(a, b); - } - - [Fact(DisplayName = "Enumerations should not be equal")] - public void EnumerationsShouldNotBeEqual() - { - // Arrange - Color a = Color.Red; - Color b = Color.Blue; - - // Assert - Assert.NotEqual(a, b); - } - - [Fact(DisplayName = "Enumeration should return all enumeration instances")] - public void EnumerationsShouldReturnAllEnumerationInstances() - { - // Arrange - IEnumerable colors = Color.GetAll(); - - // Assert - Assert.Contains(colors, item => item == Color.Red); - Assert.Contains(colors, item => item == Color.Green); - Assert.Contains(colors, item => item == Color.Blue); - } - - [Fact(DisplayName = "Enumeration_FromName should return the expected enumeration entry")] - public void EnumerationFromNameShouldReturnTheExpectedEnumerationEntry() - { - // Arrange - Color color = Color.FromName("Green"); - - // Assert - Assert.Equal(Color.Green, color); - } - - [Fact(DisplayName = "Enumeration_FromValue should return the expected enumeration entry")] - public void EnumerationFromValueShouldReturnTheExpectedEnumerationEntry() - { - // Arrange - Color color = Color.FromValue(2); - - // Assert - Assert.Equal(Color.Green, color); - } + // Arrange + Color color = Color.FromValue(2); + + // Assert + Assert.Equal(Color.Green, color); + } + + [Fact(DisplayName = "Enumeration.GetAll should return all enumeration entries")] + public void EnumerationGetAllShouldReturnAllEnumerationEntries() + { + // Arrange + IEnumerable entries = Color.GetAll(); + + // Assert + Assert.Contains(Color.Blue, entries); + Assert.Contains(Color.Green, entries); + Assert.Contains(Color.Red, entries); + } + + [Fact(DisplayName = "Enumeration.GetEntries should return all enumeration entries")] + public void EnumerationGetEntriesShouldReturnAllEnumerationEntries() + { + // Arrange + IEnumerable<(int Value, string Name)> entries = Color.GetEntries(); + + // Assert + Assert.Contains(Color.Blue.ToEntry(), entries); + Assert.Contains(Color.Green.ToEntry(), entries); + Assert.Contains(Color.Red.ToEntry(), entries); + } + + [Fact(DisplayName = "Enumeration.GetNames should return all enumeration names")] + public void EnumerationGetNamesShouldReturnAllEnumerationNames() + { + // Arrange + IEnumerable entries = Color.GetNames(); + + // Assert + Assert.Contains(Color.Blue.Name, entries); + Assert.Contains(Color.Green.Name, entries); + Assert.Contains(Color.Red.Name, entries); + } + + [Fact(DisplayName = "Enumeration.GetValues should return all enumeration values")] + public void EnumerationGetValuesShouldReturnAllEnumerationValues() + { + // Arrange + IEnumerable entries = Color.GetValues(); + + // Assert + Assert.Contains(Color.Blue.Value, entries); + Assert.Contains(Color.Green.Value, entries); + Assert.Contains(Color.Red.Value, entries); } -} +} \ No newline at end of file diff --git a/OnixLabs.Core.UnitTests/MockData/Color.cs b/OnixLabs.Core.UnitTests/MockData/Color.cs index 014b9da..891e675 100644 --- a/OnixLabs.Core.UnitTests/MockData/Color.cs +++ b/OnixLabs.Core.UnitTests/MockData/Color.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,16 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.UnitTests.MockData +namespace OnixLabs.Core.UnitTests.MockData; + +public sealed class Color : Enumeration { - public sealed class Color : Enumeration - { - public static readonly Color Red = new(1, nameof(Red)); - public static readonly Color Green = new(2, nameof(Green)); - public static readonly Color Blue = new(3, nameof(Blue)); + public static readonly Color Red = new(1, nameof(Red)); + public static readonly Color Green = new(2, nameof(Green)); + public static readonly Color Blue = new(3, nameof(Blue)); - private Color(int value, string name) : base(value, name) - { - } + private Color(int value, string name) : base(value, name) + { } } diff --git a/OnixLabs.Core.UnitTests/OnixLabs.Core.UnitTests.csproj b/OnixLabs.Core.UnitTests/OnixLabs.Core.UnitTests.csproj index 67e2add..0ec43ac 100644 --- a/OnixLabs.Core.UnitTests/OnixLabs.Core.UnitTests.csproj +++ b/OnixLabs.Core.UnitTests/OnixLabs.Core.UnitTests.csproj @@ -1,9 +1,11 @@ - net5.0 + net6.0 false + + 10 diff --git a/OnixLabs.Core.UnitTests/PreconditionTests.cs b/OnixLabs.Core.UnitTests/PreconditionTests.cs new file mode 100644 index 0000000..8331dc2 --- /dev/null +++ b/OnixLabs.Core.UnitTests/PreconditionTests.cs @@ -0,0 +1,34 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using Xunit; +using static OnixLabs.Core.Preconditions; + +namespace OnixLabs.Core.UnitTests; + +public sealed class PreconditionTests +{ + [Fact(DisplayName = "Check should throw an ArgumentException when the condition is false")] + public void CheckShouldThrowAnArgumentExceptionWhenTheConditionIsFalse() + { + Assert.Throws(() => Check(false)); + } + + [Fact(DisplayName = "CheckNotNull should throw an ArgumentNullException when the condition is null")] + public void CheckNotNullShouldThrowAnArgumentNullExceptionWhenTheConditionIsNull() + { + Assert.Throws(() => CheckNotNull(null)); + } +} diff --git a/OnixLabs.Core.UnitTests/StringExtensionTests.cs b/OnixLabs.Core.UnitTests/StringExtensionTests.cs index 614d237..2908b43 100644 --- a/OnixLabs.Core.UnitTests/StringExtensionTests.cs +++ b/OnixLabs.Core.UnitTests/StringExtensionTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,104 +14,126 @@ using Xunit; -namespace OnixLabs.Core.UnitTests +namespace OnixLabs.Core.UnitTests; + +public sealed class StringExtensionTests { - public sealed class StringExtensionTests + [Theory(DisplayName = "SubstringBefore should return the expected result (char)")] + [InlineData("First:Second", "First", ':')] + [InlineData("12345+678910", "12345", '+')] + public void SubstringBeforeShouldReturnTheExpectedResultChar(string value, string expected, char delimiter) + { + // Arrange / Act + string actual = value.SubstringBefore(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringBefore should return the expected result (string)")] + [InlineData("First:Second", "First", ":")] + [InlineData("12345+678910", "12345", "+")] + public void SubstringBeforeShouldReturnTheExpectedResultString(string value, string expected, string delimiter) + { + // Arrange / Act + string actual = value.SubstringBefore(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringBeforeLast should return the expected result (char)")] + [InlineData("First:Second:Third", "First:Second", ':')] + [InlineData("12345+678910+12345", "12345+678910", '+')] + public void SubstringBeforeLastShouldReturnTheExpectedResultChar(string value, string expected, char delimiter) + { + // Arrange / Act + string actual = value.SubstringBeforeLast(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringBeforeLast should return the expected result (string)")] + [InlineData("First:Second:Third", "First:Second", ":")] + [InlineData("12345+678910+12345", "12345+678910", "+")] + public void SubstringBeforeLastShouldReturnTheExpectedResultString(string value, string expected, string delimiter) + { + // Arrange / Act + string actual = value.SubstringBeforeLast(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringAfter should return the expected result (char)")] + [InlineData("First:Second", "Second", ':')] + [InlineData("12345+678910", "678910", '+')] + public void SubstringAfterShouldReturnTheExpectedResultChar(string value, string expected, char delimiter) + { + // Arrange / Act + string actual = value.SubstringAfter(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringAfter should return the expected result (string)")] + [InlineData("First:Second", "Second", ":")] + [InlineData("12345+678910", "678910", "+")] + public void SubstringAfterShouldReturnTheExpectedResultString(string value, string expected, string delimiter) + { + // Arrange / Act + string actual = value.SubstringAfter(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringAfterLast should return the expected result (char)")] + [InlineData("First:Second:Third", "Third", ':')] + [InlineData("12345+678910+12345", "12345", '+')] + public void SubstringAfterLastShouldReturnTheExpectedResultChar(string value, string expected, char delimiter) + { + // Arrange / Act + string actual = value.SubstringAfterLast(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "SubstringAfterLast should return the expected result (string)")] + [InlineData("First:Second:Third", "Third", ":")] + [InlineData("12345+678910+12345", "12345", "+")] + public void SubstringAfterLastShouldReturnTheExpectedResultString(string value, string expected, string delimiter) { - [Theory(DisplayName = "SubstringBefore should return the expected result (char)")] - [InlineData("First:Second", "First", ':')] - [InlineData("12345+678910", "12345", '+')] - public void SubstringBeforeShouldReturnTheExpectedResultC(string value, string expected, char delimiter) - { - // Arrange / Act - string actual = value.SubstringBefore(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringBefore should return the expected result (string)")] - [InlineData("First:Second", "First", ":")] - [InlineData("12345+678910", "12345", "+")] - public void SubstringBeforeShouldReturnTheExpectedResultS(string value, string expected, string delimiter) - { - // Arrange / Act - string actual = value.SubstringBefore(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringBeforeLast should return the expected result (char)")] - [InlineData("First:Second:Third", "First:Second", ':')] - [InlineData("12345+678910+12345", "12345+678910", '+')] - public void SubstringBeforeLastShouldReturnTheExpectedResultC(string value, string expected, char delimiter) - { - // Arrange / Act - string actual = value.SubstringBeforeLast(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringBeforeLast should return the expected result (string)")] - [InlineData("First:Second:Third", "First:Second", ":")] - [InlineData("12345+678910+12345", "12345+678910", "+")] - public void SubstringBeforeLastShouldReturnTheExpectedResultS(string value, string expected, string delimiter) - { - // Arrange / Act - string actual = value.SubstringBeforeLast(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringAfter should return the expected result (char)")] - [InlineData("First:Second", "Second", ':')] - [InlineData("12345+678910", "678910", '+')] - public void SubstringAfterShouldReturnTheExpectedResultC(string value, string expected, char delimiter) - { - // Arrange / Act - string actual = value.SubstringAfter(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringAfter should return the expected result (string)")] - [InlineData("First:Second", "Second", ":")] - [InlineData("12345+678910", "678910", "+")] - public void SubstringAfterShouldReturnTheExpectedResultS(string value, string expected, string delimiter) - { - // Arrange / Act - string actual = value.SubstringAfter(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringAfterLast should return the expected result (char)")] - [InlineData("First:Second:Third", "Third", ':')] - [InlineData("12345+678910+12345", "12345", '+')] - public void SubstringAfterLastShouldReturnTheExpectedResultC(string value, string expected, char delimiter) - { - // Arrange / Act - string actual = value.SubstringAfterLast(delimiter); - - // Assert - Assert.Equal(expected, actual); - } - - [Theory(DisplayName = "SubstringAfterLast should return the expected result (string)")] - [InlineData("First:Second:Third", "Third", ":")] - [InlineData("12345+678910+12345", "12345", "+")] - public void SubstringAfterLastShouldReturnTheExpectedResultS(string value, string expected, string delimiter) - { - // Arrange / Act - string actual = value.SubstringAfterLast(delimiter); - - // Assert - Assert.Equal(expected, actual); - } + // Arrange / Act + string actual = value.SubstringAfterLast(delimiter); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "ToByteArray should return the expected result")] + [InlineData("Hello, World!", new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21})] + public void ToByteArrayShouldReturnTheExpectedResult(string value, byte[] expected) + { + // Arrange / Act + byte[] actual = value.ToByteArray(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Wrap should return the expected result")] + [InlineData("<", "value", ">", "")] + [InlineData("BEFORE:", "value", ":AFTER", "BEFORE:value:AFTER")] + public void WrapShouldReturnTheExpectedResult(string before, string value, string after, string expected) + { + // Arrange / Act + string actual = value.Wrap(before, after); + + // Assert + Assert.Equal(expected, actual); } } diff --git a/OnixLabs.Core.UnitTests/Text/Base16Tests.cs b/OnixLabs.Core.UnitTests/Text/Base16Tests.cs new file mode 100644 index 0000000..2d5cc56 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base16Tests.cs @@ -0,0 +1,68 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base16Tests +{ + [Fact(DisplayName = "Identical Base16 values produce identical hash codes.")] + public void IdenticalBase16ValuesProduceIdenticalHashCodes() + { + // Arrange + Base16 a = Base16.FromString("abcdefghijklmnopqrstuvwxyz"); + Base16 b = Base16.FromString("abcdefghijklmnopqrstuvwxyz"); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base16_FromString should produce the expected Base-16 value.")] + [InlineData("31323334353637383930", "1234567890")] + [InlineData("4142434445464748494a4b4c4d4e4f505152535455565758595a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("6162636465666768696a6b6c6d6e6f707172737475767778797a", "abcdefghijklmnopqrstuvwxyz")] + public void Base16FromStringShouldProduceTheExpectedBase16Value(string expected, string value) + { + // Arrange + Base16 candidate = Base16.FromString(value); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base16_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "31323334353637383930")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "4142434445464748494a4b4c4d4e4f505152535455565758595a")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "6162636465666768696a6b6c6d6e6f707172737475767778797a")] + public void Base16ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base16 candidate = Base16.Parse(value); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base32Base32HexAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base32Base32HexAlphabetTests.cs new file mode 100644 index 0000000..0754051 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base32Base32HexAlphabetTests.cs @@ -0,0 +1,84 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base32Base32HexAlphabetTests +{ + [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] + public void IdenticalBase32ValuesProduceIdenticalHashCodes() + { + // Arrange + Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Base32Hex); + Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Base32Hex); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("64P36D1L6ORJGE9G", "1234567890")] + [InlineData("85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8======", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Base32Hex, true); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("64P36D1L6ORJGE9G", "1234567890")] + [InlineData("85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Base32Hex, false); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "64P36D1L6ORJGE9G")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "85146H258P3KGIAA9D64QJIFA18L4KQKALB5EM2PB8")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "C5H66P35CPJMGQBADDM6QRJFE1ON4SRKELR7EU3PF8")] + public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base32 candidate = Base32.Parse(value, Base32Alphabet.Base32Hex); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base32CrockfordAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base32CrockfordAlphabetTests.cs new file mode 100644 index 0000000..ad3c782 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base32CrockfordAlphabetTests.cs @@ -0,0 +1,84 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base32CrockfordAlphabetTests +{ + [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] + public void IdenticalBase32ValuesProduceIdenticalHashCodes() + { + // Arrange + Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Crockford); + Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Crockford); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("64S36D1N6RVKGE9G", "1234567890")] + [InlineData("85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8======", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Crockford, true); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("64S36D1N6RVKGE9G", "1234567890")] + [InlineData("85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Crockford, false); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "64S36D1N6RVKGE9G")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "85146H258S3MGJAA9D64TKJFA18N4MTMANB5EP2SB8")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "C5H66S35CSKPGTBADDP6TVKFE1RQ4WVMENV7EY3SF8")] + public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base32 candidate = Base32.Parse(value, Base32Alphabet.Crockford); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base32DefaultAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base32DefaultAlphabetTests.cs new file mode 100644 index 0000000..64be871 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base32DefaultAlphabetTests.cs @@ -0,0 +1,84 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base32DefaultAlphabetTests +{ + [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] + public void IdenticalBase32ValuesProduceIdenticalHashCodes() + { + // Arrange + Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Default); + Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.Default); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("GEZDGNBVGY3TQOJQ", "1234567890")] + [InlineData("IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI======", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Default, true); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("GEZDGNBVGY3TQOJQ", "1234567890")] + [InlineData("IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.Default, false); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "GEZDGNBVGY3TQOJQ")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "IFBEGRCFIZDUQSKKJNGE2TSPKBIVEU2UKVLFOWCZLI")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPI")] + public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base32 candidate = Base32.Parse(value, Base32Alphabet.Default); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base32ZBase32AlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base32ZBase32AlphabetTests.cs new file mode 100644 index 0000000..9fcf4a5 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base32ZBase32AlphabetTests.cs @@ -0,0 +1,84 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base32ZBase32AlphabetTests +{ + [Fact(DisplayName = "Identical Base32 values produce identical hash codes.")] + public void IdenticalBase32ValuesProduceIdenticalHashCodes() + { + // Arrange + Base32 a = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.ZBase32); + Base32 b = Base32.FromString("abcdefghijklmnopqrstuvwxyz", Base32Alphabet.ZBase32); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("gr3dgpbiga5uoqjo", "1234567890")] + [InlineData("efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me======", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe======", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.ZBase32, true); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_FromString without padding should produce the expected Base-32 value.")] + [InlineData("gr3dgpbiga5uoqjo", "1234567890")] + [InlineData("efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe", "abcdefghijklmnopqrstuvwxyz")] + public void Base32FromStringWithoutPaddingShouldProduceTheExpectedBase32Value(string expected, string value) + { + // Arrange + Base32 candidate = Base32.FromString(value, Base32Alphabet.ZBase32, false); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base32_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "gr3dgpbiga5uoqjo")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "efbrgtnfe3dwo1kkjpgr4u1xkbeirw4wkimfqsn3me")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "cftgg3dfc3uso4mkppsg45uxqbazrh5wqi58q6d3xe")] + public void Base32ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base32 candidate = Base32.Parse(value, Base32Alphabet.ZBase32); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base58DefaultAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base58DefaultAlphabetTests.cs new file mode 100644 index 0000000..f59cb61 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base58DefaultAlphabetTests.cs @@ -0,0 +1,68 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base58DefaultAlphabetTests +{ + [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] + public void IdenticalBase58ValuesProduceIdenticalHashCodes() + { + // Arrange + Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Default); + Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Default); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] + [InlineData("3mJr7AoUCHxNqd", "1234567890")] + [InlineData("2zuFXTJSTRK6ESktqhM2QDBkCnH1U46CnxaD", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f", "abcdefghijklmnopqrstuvwxyz")] + public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) + { + // Arrange + Base58 candidate = Base58.FromString(value, Base58Alphabet.Default); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "3mJr7AoUCHxNqd")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "2zuFXTJSTRK6ESktqhM2QDBkCnH1U46CnxaD")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f")] + public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base58 candidate = Base58.Parse(value, Base58Alphabet.Default); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base58FlickrAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base58FlickrAlphabetTests.cs new file mode 100644 index 0000000..64cc7e2 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base58FlickrAlphabetTests.cs @@ -0,0 +1,68 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base58FlickrAlphabetTests +{ + [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] + public void IdenticalBase58ValuesProduceIdenticalHashCodes() + { + // Arrange + Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Flickr); + Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Flickr); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] + [InlineData("3LiR7aNtchXnQC", "1234567890")] + [InlineData("2ZUfwsirsqj6erKTQGm2pdbKcMh1t46cMXzd", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("3YXt3U1HFx8vKFTJj92EAipcC4byHHs1V25E", "abcdefghijklmnopqrstuvwxyz")] + public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) + { + // Arrange + Base58 candidate = Base58.FromString(value, Base58Alphabet.Flickr); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "3LiR7aNtchXnQC")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "2ZUfwsirsqj6erKTQGm2pdbKcMh1t46cMXzd")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "3YXt3U1HFx8vKFTJj92EAipcC4byHHs1V25E")] + public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base58 candidate = Base58.Parse(value, Base58Alphabet.Flickr); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base58RippleAlphabetTests.cs b/OnixLabs.Core.UnitTests/Text/Base58RippleAlphabetTests.cs new file mode 100644 index 0000000..381776c --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base58RippleAlphabetTests.cs @@ -0,0 +1,68 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base58RippleAlphabetTests +{ + [Fact(DisplayName = "Identical Base58 values produce identical hash codes.")] + public void IdenticalBase58ValuesProduceIdenticalHashCodes() + { + // Arrange + Base58 a = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Ripple); + Base58 b = Base58.FromString("abcdefghijklmnopqrstuvwxyz", Base58Alphabet.Ripple); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base58_FromString should produce the expected Base-58 value.")] + [InlineData("smJifwo7UHx4qd", "1234567890")] + [InlineData("pzuEXTJSTRKaNSktq6MpQDBkU8Hr7haU8x2D", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("syx7sur5gY3WkgtjK9pCbJQUdhBZ55TrvpnC", "abcdefghijklmnopqrstuvwxyz")] + public void Base58FromStringShouldProduceTheExpectedBase58Value(string expected, string value) + { + // Arrange + Base58 candidate = Base58.FromString(value, Base58Alphabet.Ripple); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base58_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "smJifwo7UHx4qd")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "pzuEXTJSTRKaNSktq6MpQDBkU8Hr7haU8x2D")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "syx7sur5gY3WkgtjK9pCbJQUdhBZ55TrvpnC")] + public void Base58ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base58 candidate = Base58.Parse(value, Base58Alphabet.Ripple); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core.UnitTests/Text/Base64Tests.cs b/OnixLabs.Core.UnitTests/Text/Base64Tests.cs new file mode 100644 index 0000000..d9da9b7 --- /dev/null +++ b/OnixLabs.Core.UnitTests/Text/Base64Tests.cs @@ -0,0 +1,68 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using OnixLabs.Core.Text; +using Xunit; + +namespace OnixLabs.Core.UnitTests.Text; + +public sealed class Base64Tests +{ + [Fact(DisplayName = "Identical Base64 values produce identical hash codes.")] + public void IdenticalBase64ValuesProduceIdenticalHashCodes() + { + // Arrange + Base64 a = Base64.FromString("abcdefghijklmnopqrstuvwxyz"); + Base64 b = Base64.FromString("abcdefghijklmnopqrstuvwxyz"); + + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); + + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } + + [Theory(DisplayName = "Base64_FromString should produce the expected Base-64 value.")] + [InlineData("MTIzNDU2Nzg5MA==", "1234567890")] + [InlineData("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", "abcdefghijklmnopqrstuvwxyz")] + public void Base64FromStringShouldProduceTheExpectedBase64Value(string expected, string value) + { + // Arrange + Base64 candidate = Base64.FromString(value); + + // Act + string actual = candidate.ToString(); + + // Assert + Assert.Equal(expected, actual); + } + + [Theory(DisplayName = "Base64_Parse should produce the expected plain text value.")] + [InlineData("1234567890", "MTIzNDU2Nzg5MA==")] + [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=")] + [InlineData("abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] + public void Base64ParseShouldProduceTheExpectedPlainTextValue(string expected, string value) + { + // Arrange + Base64 candidate = Base64.Parse(value); + + // Act + string actual = candidate.ToPlainTextString(); + + // Assert + Assert.Equal(expected, actual); + } +} diff --git a/OnixLabs.Core/ArrayExtensions.cs b/OnixLabs.Core/ArrayExtensions.cs index bce2240..67d6b4c 100644 --- a/OnixLabs.Core/ArrayExtensions.cs +++ b/OnixLabs.Core/ArrayExtensions.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,57 +15,56 @@ using System; using System.ComponentModel; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +/// +/// Provides extension methods for arrays. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public static class ArrayExtensions { /// - /// Provides extension methods for arrays. + /// Copies this array. /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class ArrayExtensions + /// The array to copy. + /// The underlying type of the array. + /// Returns an exact copy of this array. + public static T[] Copy(this T[] array) { - /// - /// Copies this array. - /// - /// The array to copy. - /// The underlying type of the array. - /// Returns an exact copy of this array. - public static T[] Copy(this T[] array) - { - return Copy(array, 0, array.Length); - } + return Copy(array, 0, array.Length); + } - /// - /// Copies this array. - /// - /// The array to copy. - /// The index of the array to begin copying from. - /// The number of elements of the array to copy. - /// The underlying type of the array. - /// Returns an exact copy of this array. - public static T[] Copy(this T[] array, int index, int count) - { - T[] result = new T[count]; - Array.Copy(array, index, result, 0, count); + /// + /// Copies this array. + /// + /// The array to copy. + /// The index of the array to begin copying from. + /// The number of elements of the array to copy. + /// The underlying type of the array. + /// Returns an exact copy of this array. + public static T[] Copy(this T[] array, int index, int count) + { + T[] result = new T[count]; + Array.Copy(array, index, result, 0, count); - return result; - } + return result; + } - /// - /// Concatenates this array with another array. - /// - /// The source array to concatenate with the other array. - /// The other array to concatenate with the source array. - /// The underlying type of the array. - /// Returns this array concatenated with the other array. - public static T[] ConcatenateWith(this T[] array, T[] other) - { - int length = array.Length + other.Length; - T[] result = new T[length]; + /// + /// Concatenates this array with another array. + /// + /// The source array to concatenate with the other array. + /// The other array to concatenate with the source array. + /// The underlying type of the array. + /// Returns this array concatenated with the other array. + public static T[] ConcatenateWith(this T[] array, T[] other) + { + int length = array.Length + other.Length; + T[] result = new T[length]; - Array.Copy(array, 0, result, 0, array.Length); - Array.Copy(other, 0, result, array.Length, other.Length); + Array.Copy(array, 0, result, 0, array.Length); + Array.Copy(other, 0, result, array.Length, other.Length); - return result; - } + return result; } } diff --git a/OnixLabs.Core/Enumeration.Comparable.cs b/OnixLabs.Core/Enumeration.Comparable.cs index 7c2985d..964c534 100644 --- a/OnixLabs.Core/Enumeration.Comparable.cs +++ b/OnixLabs.Core/Enumeration.Comparable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,32 +14,31 @@ using System; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +public abstract partial class Enumeration : IComparable, IComparable { - public abstract partial class Enumeration : IComparable, IComparable + /// + /// Compares the current instance with another object of the same type and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the + /// other object. + /// + /// An object to compare with this instance. + /// Returns a value that indicates the relative order of the objects being compared. + public int CompareTo(object? obj) { - /// - /// Compares the current instance with another object of the same type and returns an integer that indicates - /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the - /// other object. - /// - /// An object to compare with this instance. - /// Returns a value that indicates the relative order of the objects being compared. - public virtual int CompareTo(object? obj) - { - return CompareTo(obj as T); - } + return CompareTo(obj as T); + } - /// - /// Compares the current instance with another object of the same type and returns an integer that indicates - /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the - /// other object. - /// - /// An object to compare with this instance. - /// Returns a value that indicates the relative order of the objects being compared. - public virtual int CompareTo(T? other) - { - return Value.CompareTo(other?.Value); - } + /// + /// Compares the current instance with another object of the same type and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the + /// other object. + /// + /// An object to compare with this instance. + /// Returns a value that indicates the relative order of the objects being compared. + public int CompareTo(T? other) + { + return Value.CompareTo(other?.Value); } } diff --git a/OnixLabs.Core/Enumeration.Equatable.cs b/OnixLabs.Core/Enumeration.Equatable.cs index e6fdee5..93b2602 100644 --- a/OnixLabs.Core/Enumeration.Equatable.cs +++ b/OnixLabs.Core/Enumeration.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,63 +14,62 @@ using System; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +public abstract partial class Enumeration : IEquatable { - public abstract partial class Enumeration : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Enumeration a, Enumeration b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Enumeration a, Enumeration b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Enumeration a, Enumeration b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Enumeration a, Enumeration b) + { + return !Equals(a, b); + } - /// - /// Indicates whether the current object is equal to another object of the same type. - /// - /// An object to compare with this object. - /// Returns true if the current object is equal to the other parameter; otherwise, false. - public virtual bool Equals(T? other) - { - return ReferenceEquals(this, other) - || other is not null - && other.GetType() == GetType() - && other.Value == Value - && other.Name == Name; - } + /// + /// Indicates whether the current object is equal to another object of the same type. + /// + /// An object to compare with this object. + /// Returns true if the current object is equal to the other parameter; otherwise, false. + public bool Equals(T? other) + { + return ReferenceEquals(this, other) + || other is not null + && other.GetType() == GetType() + && other.Value == Value + && other.Name == Name; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return Equals(obj as T); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public sealed override bool Equals(object? obj) + { + return Equals(obj as T); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(GetType(), Name, Value); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(GetType(), Name, Value); } } diff --git a/OnixLabs.Core/Enumeration.From.cs b/OnixLabs.Core/Enumeration.From.cs index 79ace01..ea7c1d9 100644 --- a/OnixLabs.Core/Enumeration.From.cs +++ b/OnixLabs.Core/Enumeration.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,66 +13,44 @@ // limitations under the License. using System; -using System.Collections.Immutable; +using System.Collections.Generic; using System.Linq; using OnixLabs.Core.Linq; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +public abstract partial class Enumeration { - public abstract partial class Enumeration + /// + /// Gets an enumeration entry for the specified name. + /// + /// The name of the enumeration entry. + /// Returns an enumeration entry for the specified name. + /// If a single enumeration entry for the specified name does not exist. + public static T FromName(string name) { - /// - /// Gets an enumeration entry for the specified name. - /// - /// The name of the enumeration entry. - /// Returns an enumeration entry for the specified name. - /// If a single enumeration entry for the specified name does not exist. - public static T FromName(string name) - { - IImmutableList results = GetAll() - .Where(entry => entry.Name == name) - .ToImmutableArray(); - - if (results.IsEmpty()) - { - string type = typeof(T).Name; - throw new ArgumentException($"Enumeration entry for name '{name}' not found in {type}."); - } - - if (!results.IsSingle()) - { - string type = typeof(T).Name; - throw new ArgumentException($"Multiple enumeration entries for name '{name}' found in {type}."); - } + IEnumerable results = GetAll().Where(entry => entry.Name == name).ToArray(); - return results.Single(); - } + Check(results.IsNotEmpty(), $"Enumeration entry for name '{name}' not found in {typeof(T).Name}."); + Check(results.IsSingle(), $"Multiple enumeration entries for name '{name}' found in {typeof(T).Name}."); - /// - /// Gets an enumeration entry for the specified value. - /// - /// The value of the enumeration entry. - /// Returns an enumeration entry for the specified value. - /// If a single enumeration entry for the specified value does not exist. - public static T FromValue(int value) - { - IImmutableList results = GetAll() - .Where(entry => entry.Value == value) - .ToImmutableArray(); + return results.Single(); + } - if (results.IsEmpty()) - { - string type = typeof(T).Name; - throw new ArgumentException($"Enumeration entry for value '{value}' not found in {type}."); - } + /// + /// Gets an enumeration entry for the specified value. + /// + /// The value of the enumeration entry. + /// Returns an enumeration entry for the specified value. + /// If a single enumeration entry for the specified value does not exist. + public static T FromValue(int value) + { + IEnumerable results = GetAll().Where(entry => entry.Value == value).ToArray(); - if (!results.IsSingle()) - { - string type = typeof(T).Name; - throw new ArgumentException($"Multiple enumeration entries for value '{value}' found in {type}."); - } + Check(results.IsNotEmpty(), $"Enumeration entry for value '{value}' not found in {typeof(T).Name}."); + Check(results.IsSingle(), $"Multiple enumeration entries for value '{value}' found in {typeof(T).Name}."); - return results.Single(); - } + return results.Single(); } } diff --git a/OnixLabs.Core/Enumeration.Get.cs b/OnixLabs.Core/Enumeration.Get.cs index 960cdc0..7261703 100644 --- a/OnixLabs.Core/Enumeration.Get.cs +++ b/OnixLabs.Core/Enumeration.Get.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,54 +17,47 @@ using System.Reflection; using OnixLabs.Core.Linq; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +public abstract partial class Enumeration { - public abstract partial class Enumeration + /// + /// Gets all of the enumeration entries for the current type. + /// + /// Returns all of the enumeration entries for the current type. + public static ImmutableHashSet GetAll() { - /// - /// Gets all of the enumeration entries for the current type. - /// - /// Returns all of the enumeration entries for the current type. - public static IImmutableList GetAll() - { - return typeof(T) - .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) - .Select(field => field.GetValue(null)) - .WhereInstanceOf() - .ToImmutableList(); - } + return typeof(T) + .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Select(field => field.GetValue(null)) + .WhereIs() + .ToImmutableHashSet(); + } - /// - /// Gets all of the enumeration entries for the current type. - /// - /// Returns all of the enumeration entries for the current type. - public static IImmutableList<(int Value, string Name)> GetEntries() - { - return GetAll() - .Select(entry => (entry.Value, entry.Name)) - .ToImmutableList(); - } + /// + /// Gets all of the enumeration entries for the current type. + /// + /// Returns all of the enumeration entries for the current type. + public static ImmutableHashSet<(int Value, string Name)> GetEntries() + { + return GetAll().Select(entry => entry.ToEntry()).ToImmutableHashSet(); + } - /// - /// Gets all of the enumeration names for the current type. - /// - /// Returns all of the enumeration names for the current type. - public static IImmutableList GetNames() - { - return GetAll() - .Select(entry => entry.Name) - .ToImmutableList(); - } + /// + /// Gets all of the enumeration names for the current type. + /// + /// Returns all of the enumeration names for the current type. + public static ImmutableHashSet GetNames() + { + return GetAll().Select(entry => entry.Name).ToImmutableHashSet(); + } - /// - /// Gets all of the enumeration values for the current type. - /// - /// Returns all of the enumeration values for the current type. - public static IImmutableList GetValues() - { - return GetAll() - .Select(entry => entry.Value) - .ToImmutableList(); - } + /// + /// Gets all of the enumeration values for the current type. + /// + /// Returns all of the enumeration values for the current type. + public static ImmutableHashSet GetValues() + { + return GetAll().Select(entry => entry.Value).ToImmutableHashSet(); } -} +} \ No newline at end of file diff --git a/OnixLabs.Core/Enumeration.To.cs b/OnixLabs.Core/Enumeration.To.cs index 81af7d3..5432deb 100644 --- a/OnixLabs.Core/Enumeration.To.cs +++ b/OnixLabs.Core/Enumeration.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,17 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core +using System; + +namespace OnixLabs.Core; + +public abstract partial class Enumeration { - public abstract partial class Enumeration + /// + /// Returns a that represents the current object. + /// + /// Returns a tuple that represents the current object. + public (int Value, string Name) ToEntry() + { + return (Value, Name); + } + + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() { - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Name; - } + return Name; } -} +} \ No newline at end of file diff --git a/OnixLabs.Core/Enumeration.cs b/OnixLabs.Core/Enumeration.cs index 3af4439..cf98ae2 100644 --- a/OnixLabs.Core/Enumeration.cs +++ b/OnixLabs.Core/Enumeration.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,33 +12,32 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core +namespace OnixLabs.Core; + +/// +/// Represents the base class for implementing enumeration classes. +/// +/// The underlying enumeration type. +public abstract partial class Enumeration where T : Enumeration { /// - /// Represents the base class for implementing enumeration classes. + /// Initializes a new instance of the class. /// - /// The underlying enumeration type. - public abstract partial class Enumeration where T : Enumeration + /// The value of the enumeration entry. + /// The name of the enumeration entry. + protected Enumeration(int value, string name) { - /// - /// Initializes a new instance of the class. - /// - /// The value of the enumeration entry. - /// The name of the enumeration entry. - protected Enumeration(int value, string name) - { - Value = value; - Name = name; - } + Value = value; + Name = name; + } - /// - /// Gets the name of the enumeration entry. - /// - public string Name { get; } + /// + /// Gets the name of the enumeration entry. + /// + public string Name { get; } - /// - /// Gets the value of the enumeration entry. - /// - public int Value { get; } - } + /// + /// Gets the value of the enumeration entry. + /// + public int Value { get; } } diff --git a/OnixLabs.Core/HashCodeExtensions.cs b/OnixLabs.Core/HashCodeExtensions.cs index 796bb36..b22c40f 100644 --- a/OnixLabs.Core/HashCodeExtensions.cs +++ b/OnixLabs.Core/HashCodeExtensions.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,38 +17,37 @@ using System.ComponentModel; using OnixLabs.Core.Linq; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +/// +/// Provides extension methods for hash codes. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public static class HashCodeExtensions { /// - /// Provides extension methods for hash codes. + /// Adds an item to be hashed into a instance. /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class HashCodeExtensions + /// The which will receive the item to hash. + /// The item to hash into the . + /// The underlying type of the item to hash. + /// Returns the containing the added item. + public static HashCode AddItem(this HashCode hashCode, T item) { - /// - /// Adds an item to be hashed into a instance. - /// - /// The which will receive the item to hash. - /// The item to hash into the . - /// The underlying type of the item to hash. - /// Returns the containing the added item. - public static HashCode AddItem(this HashCode hashCode, T item) - { - hashCode.Add(item); - return hashCode; - } + hashCode.Add(item); + return hashCode; + } - /// - /// Adds the items to be hashed into a instance. - /// - /// The which will receive the items to hash. - /// The items to hash into the . - /// The underlying type of the items to hash. - /// Returns the containing the added items. - public static HashCode AddItems(this HashCode hashCode, IEnumerable items) - { - items.ForEach(hashCode.Add); - return hashCode; - } + /// + /// Adds the items to be hashed into a instance. + /// + /// The which will receive the items to hash. + /// The items to hash into the . + /// The underlying type of the items to hash. + /// Returns the containing the added items. + public static HashCode AddItems(this HashCode hashCode, IEnumerable items) + { + items.ForEach(hashCode.Add); + return hashCode; } } diff --git a/OnixLabs.Core/Linq/IEnumerableExtensions.cs b/OnixLabs.Core/Linq/IEnumerableExtensions.cs index bbb930d..d082232 100644 --- a/OnixLabs.Core/Linq/IEnumerableExtensions.cs +++ b/OnixLabs.Core/Linq/IEnumerableExtensions.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,168 +16,162 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.ComponentModel; using System.Linq; -namespace OnixLabs.Core.Linq +namespace OnixLabs.Core.Linq; + +/// +/// Provides LINQ-like extension methods for . +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public static class IEnumerableExtensions { /// - /// Provides LINQ-like extension methods for . + /// Determines whether all elements of this are equal by a specified property. /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class IEnumerableExtensions + /// The on which to perform the operation. + /// The selector function which will be used to select each property from each element. + /// The underlying type of the . + /// The underlying type of each selected element. + /// Returns true if all selected element properties are equal; otherwise false. + public static bool AllEqualBy(this IEnumerable enumerable, Func selector) { - /// - /// Determines whether all elements of this are equal by a specified property. - /// - /// The on which to perform the operation. - /// The selector function which will be used to select each property from each element. - /// The underlying type of the . - /// The underlying type of each selected element. - /// Returns true if all selected element properties are equal; otherwise false. - public static bool AllEqualBy( - this IEnumerable enumerable, - Func selector) - { - IImmutableList elements = enumerable.ToImmutableList(); - - if (elements.IsEmpty()) - { - return false; - } + IEnumerable elements = enumerable.ToArray(); - if (elements.IsSingle()) - { - return true; - } - - TProperty first = selector(elements[0]); - return elements.All(element => Equals(first, selector(element))); + if (elements.IsEmpty()) + { + return false; } - /// - /// Determines whether any elements of this are equal by a specified property. - /// - /// The on which to perform the operation. - /// The selector function which will be used to select each property from each element. - /// The underlying type of the . - /// The underlying type of each selected element. - /// Returns true if any selected element properties are equal; otherwise false. - public static bool AnyEqualBy( - this IEnumerable enumerable, - Func selector) + if (elements.IsSingle()) { - IImmutableList elements = enumerable.ToImmutableList(); - - if (elements.IsEmpty()) - { - return false; - } + return true; + } - if (elements.IsSingle()) - { - return true; - } + TProperty first = selector(elements.First()); + return elements.All(element => Equals(first, selector(element))); + } - TProperty first = selector(elements[0]); - return elements.Any(element => Equals(first, selector(element))); - } + /// + /// Determines whether any elements of this are equal by a specified property. + /// + /// The on which to perform the operation. + /// The selector function which will be used to select each property from each element. + /// The underlying type of the . + /// The underlying type of each selected element. + /// Returns true if any selected element properties are equal; otherwise false. + public static bool AnyEqualBy(this IEnumerable enumerable, Func selector) + { + IEnumerable elements = enumerable.ToArray(); - /// - /// Computes the content hash code of the elements of this . - /// - /// The from which to compute a content hash code. - /// The underlying type of the . - /// Returns the computed content hash code of this . - public static int ComputeContentHashCode(this IEnumerable enumerable) + if (elements.IsEmpty()) { - return new HashCode().AddItems(enumerable).ToHashCode(); + return false; } - /// - /// Performs the specified for each element of this . - /// - /// The over which to iterate. - /// The to perform for each element. - /// The underlying type of the . - public static void ForEach(this IEnumerable enumerable, Action action) + if (elements.IsSingle()) { - foreach (T element in enumerable) - { - action(element); - } + return true; } - /// - /// Determines whether this is empty. - /// - /// The on which to perform the operation. - /// he underlying type of the . - /// Returns true if the is empty; otherwise, false. - public static bool IsEmpty(this IEnumerable enumerable) - { - return !enumerable.Any(); - } + TProperty first = selector(elements.First()); + return elements.Any(element => Equals(first, selector(element))); + } - /// - /// Determines whether this is not empty. - /// - /// The on which to perform the operation. - /// The underlying type of the . - /// Returns true if the is not empty; otherwise, false. - public static bool IsNotEmpty(this IEnumerable enumerable) + /// + /// Performs the specified for each element of this . + /// + /// The over which to iterate. + /// The to perform for each element. + /// The underlying type of the . + public static void ForEach(this IEnumerable enumerable, Action action) + { + foreach (T element in enumerable) { - return enumerable.Any(); + action(element); } + } - /// - /// Determines whether this contains a single element. - /// - /// The on which to perform the operation. - /// The underlying type of the . - /// Returns true if the contains a single element; otherwise, false. - public static bool IsSingle(this IEnumerable enumerable) - { - return enumerable.LongCount() == 1; - } + /// + /// Gets the content hash code of the elements of this . + /// + /// The from which to compute a content hash code. + /// The underlying type of the . + /// Returns the computed content hash code of this . + public static int GetContentHashCode(this IEnumerable enumerable) + { + return new HashCode().AddItems(enumerable).ToHashCode(); + } - /// - /// Determines whether this contains an even number of elements. - /// - /// The on which to perform the operation. - /// The underlying type of the . - /// Returns true if the contains an even number of elements; otherwise, false. - public static bool IsEvenCount(this IEnumerable enumerable) - { - return enumerable.LongCount() % 2 == 0; - } + /// + /// Determines whether this is empty. + /// + /// The on which to perform the operation. + /// he underlying type of the . + /// Returns true if the is empty; otherwise, false. + public static bool IsEmpty(this IEnumerable enumerable) + { + return !enumerable.Any(); + } - /// - /// Determines whether this contains an odd number of elements. - /// - /// The on which to perform the operation. - /// The underlying type of the . - /// Returns true if the contains an odd number of elements; otherwise, false. - public static bool IsOddCount(this IEnumerable enumerable) - { - return enumerable.LongCount() % 2 != 0; - } + /// + /// Determines whether this is not empty. + /// + /// The on which to perform the operation. + /// The underlying type of the . + /// Returns true if the is not empty; otherwise, false. + public static bool IsNotEmpty(this IEnumerable enumerable) + { + return !enumerable.IsEmpty(); + } + + /// + /// Determines whether this contains a single element. + /// + /// The on which to perform the operation. + /// The underlying type of the . + /// Returns true if the contains a single element; otherwise, false. + public static bool IsSingle(this IEnumerable enumerable) + { + return enumerable.LongCount() == 1; + } + + /// + /// Determines whether this contains an even number of elements. + /// + /// The on which to perform the operation. + /// The underlying type of the . + /// Returns true if the contains an even number of elements; otherwise, false. + public static bool IsCountEven(this IEnumerable enumerable) + { + return enumerable.LongCount() % 2 == 0; + } - /// - /// Filters this to only elements of the specified type. - /// - /// The on which to perform the operation. - /// The underlying type of the . - /// Returns a new containing only elements of the specified type. - public static IEnumerable WhereInstanceOf(this IEnumerable enumerable) + /// + /// Determines whether this contains an odd number of elements. + /// + /// The on which to perform the operation. + /// The underlying type of the . + /// Returns true if the contains an odd number of elements; otherwise, false. + public static bool IsCountOdd(this IEnumerable enumerable) + { + return !enumerable.IsCountEven(); + } + + /// + /// Filters this to only elements of the specified type. + /// + /// The on which to perform the operation. + /// The underlying type of the . + /// Returns a new containing only elements of the specified type. + public static IEnumerable WhereIs(this IEnumerable enumerable) + { + foreach (object? element in enumerable) { - foreach (object? element in enumerable) + if (element is T elementOfType) { - if (element is T elementOfType) - { - yield return elementOfType; - } + yield return elementOfType; } } } diff --git a/OnixLabs.Core/OnixLabs.Core.csproj b/OnixLabs.Core/OnixLabs.Core.csproj index fff7382..69d849f 100644 --- a/OnixLabs.Core/OnixLabs.Core.csproj +++ b/OnixLabs.Core/OnixLabs.Core.csproj @@ -1,18 +1,18 @@ - net5.0 - 9 + net6.0 + 10 enable true OnixLabs.Core ONIXLabs ONIXLabs Core API for .NET - 4.0.0 + 5.0.0 en - Copyright © ONIXLabs 2020-2021 + Copyright © ONIXLabs 2020-2022 https://github.com/onix-labs/onixlabs-dotnet - 4.0.0 + 5.0.0 diff --git a/OnixLabs.Core/Preconditions.cs b/OnixLabs.Core/Preconditions.cs new file mode 100644 index 0000000..e38c4ac --- /dev/null +++ b/OnixLabs.Core/Preconditions.cs @@ -0,0 +1,59 @@ +// Copyright 2020-2022 ONIXLabs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using System.Runtime.CompilerServices; + +namespace OnixLabs.Core; + +/// +/// Provides methods for performing pre-conditions and guard clauses. +/// +public static class Preconditions +{ + /// + /// Performs a general pre-condition check, which fails if the condition returns false. + /// + /// The condition to check. + /// The exception message to throw in the event that the condition fails. + /// The name of the parameter which is invalid. + /// If the condition fails. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static void Check(bool value, string message = "Argument check failed.", string? paramName = null) + { + if (!value) + { + throw new ArgumentException(message, paramName); + } + } + + /// + /// Performs a general pre-condition check that the specified value is not null, which fails if the value is null. + /// + /// The nullable value to check. + /// The exception message to throw in the event that the condition fails. + /// The underlying type of the value to check. + /// Returns the specified value as non-nullable in the event that the value is not null. + /// If the condition fails and the value is null. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public static T CheckNotNull(T? value, string message = "Argument null checked failed.") where T : notnull + { + if (value is null) + { + throw new ArgumentNullException(message); + } + + return value; + } +} diff --git a/OnixLabs.Core/StringExtensions.cs b/OnixLabs.Core/StringExtensions.cs index e0c208a..6be0262 100644 --- a/OnixLabs.Core/StringExtensions.cs +++ b/OnixLabs.Core/StringExtensions.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,194 +14,215 @@ using System; using System.ComponentModel; +using System.Text; -namespace OnixLabs.Core +namespace OnixLabs.Core; + +/// +/// Provides extension methods for strings. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public static class StringExtensions { /// - /// Provides extension methods for strings. + /// The value of an index not found. + /// + private const int IndexNotFound = -1; + + /// + /// Returns a substring before the first occurrence of the specified delimiter. /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class StringExtensions + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Returns a substring before the first occurrence of the specified delimiter. + public static string SubstringBefore(this string value, char delimiter, string? defaultValue = null) { - /// - /// The value of an index not found. - /// - private const int IndexNotFound = -1; - - /// - /// Returns a substring before the first occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Returns a substring before the first occurrence of the specified delimiter. - public static string SubstringBefore( - this string value, - char delimiter, - string? defaultValue = null) + int index = value.IndexOf(delimiter); + + return index switch { - int index = value.IndexOf(delimiter); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[..index] - }; - } - - /// - /// Returns a substring before the first occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Specifies the string comparison rule for the search. - /// Returns a substring before the first occurrence of the specified delimiter. - public static string SubstringBefore( - this string value, - string delimiter, - string? defaultValue = null, - StringComparison comparison = StringComparison.Ordinal) + IndexNotFound => defaultValue ?? value, + _ => value[..index] + }; + } + + /// + /// Returns a substring before the first occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Specifies the string comparison rule for the search. + /// Returns a substring before the first occurrence of the specified delimiter. + public static string SubstringBefore( + this string value, + string delimiter, + string? defaultValue = null, + StringComparison comparison = StringComparison.Ordinal) + { + int index = value.IndexOf(delimiter, comparison); + + return index switch { - int index = value.IndexOf(delimiter, comparison); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[..index] - }; - } - - /// - /// Returns a substring before the last occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Returns a substring before the last occurrence of the specified delimiter. - public static string SubstringBeforeLast( - this string value, - char delimiter, - string? defaultValue = null) + IndexNotFound => defaultValue ?? value, + _ => value[..index] + }; + } + + /// + /// Returns a substring before the last occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Returns a substring before the last occurrence of the specified delimiter. + public static string SubstringBeforeLast(this string value, char delimiter, string? defaultValue = null) + { + int index = value.LastIndexOf(delimiter); + + return index switch { - int index = value.LastIndexOf(delimiter); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[..index] - }; - } - - /// - /// Returns a substring before the last occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Specifies the string comparison rule for the search. - /// Returns a substring before the last occurrence of the specified delimiter. - public static string SubstringBeforeLast( - this string value, - string delimiter, - string? defaultValue = null, - StringComparison comparison = StringComparison.Ordinal) + IndexNotFound => defaultValue ?? value, + _ => value[..index] + }; + } + + /// + /// Returns a substring before the last occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Specifies the string comparison rule for the search. + /// Returns a substring before the last occurrence of the specified delimiter. + public static string SubstringBeforeLast( + this string value, + string delimiter, + string? defaultValue = null, + StringComparison comparison = StringComparison.Ordinal) + { + int index = value.LastIndexOf(delimiter, comparison); + + return index switch { - int index = value.LastIndexOf(delimiter, comparison); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[..index] - }; - } - - /// - /// Returns a substring after the first occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Returns a substring after the first occurrence of the specified delimiter. - public static string SubstringAfter( - this string value, - char delimiter, - string? defaultValue = null) + IndexNotFound => defaultValue ?? value, + _ => value[..index] + }; + } + + /// + /// Returns a substring after the first occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Returns a substring after the first occurrence of the specified delimiter. + public static string SubstringAfter(this string value, char delimiter, string? defaultValue = null) + { + int index = value.IndexOf(delimiter); + + return index switch { - int index = value.IndexOf(delimiter); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[(index + 1)..value.Length] - }; - } - - /// - /// Returns a substring after the first occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Specifies the string comparison rule for the search. - /// Returns a substring after the first occurrence of the specified delimiter. - public static string SubstringAfter( - this string value, - string delimiter, - string? defaultValue = null, - StringComparison comparison = StringComparison.Ordinal) + IndexNotFound => defaultValue ?? value, + _ => value[(index + 1)..value.Length] + }; + } + + /// + /// Returns a substring after the first occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Specifies the string comparison rule for the search. + /// Returns a substring after the first occurrence of the specified delimiter. + public static string SubstringAfter( + this string value, + string delimiter, + string? defaultValue = null, + StringComparison comparison = StringComparison.Ordinal) + { + int index = value.IndexOf(delimiter, comparison); + + return index switch { - int index = value.IndexOf(delimiter, comparison); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[(index + delimiter.Length)..value.Length] - }; - } - - /// - /// Returns a substring after the last occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Returns a substring after the last occurrence of the specified delimiter. - public static string SubstringAfterLast( - this string value, - char delimiter, - string? defaultValue = null) + IndexNotFound => defaultValue ?? value, + _ => value[(index + delimiter.Length)..value.Length] + }; + } + + /// + /// Returns a substring after the last occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Returns a substring after the last occurrence of the specified delimiter. + public static string SubstringAfterLast(this string value, char delimiter, string? defaultValue = null) + { + int index = value.LastIndexOf(delimiter); + + return index switch { - int index = value.LastIndexOf(delimiter); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[(index + 1)..value.Length] - }; - } - - /// - /// Returns a substring after the last occurrence of the specified delimiter. - /// - /// The original from which to obtain a sub-string. - /// The delimiter to find within the original string. - /// The value to return if the delimiter is not found, which defaults to the original string. - /// Specifies the string comparison rule for the search. - /// Returns a substring after the last occurrence of the specified delimiter. - public static string SubstringAfterLast( - this string value, - string delimiter, - string? defaultValue = null, - StringComparison comparison = StringComparison.Ordinal) + IndexNotFound => defaultValue ?? value, + _ => value[(index + 1)..value.Length] + }; + } + + /// + /// Returns a substring after the last occurrence of the specified delimiter. + /// + /// The original from which to obtain a sub-string. + /// The delimiter to find within the original string. + /// The value to return if the delimiter is not found, which defaults to the original string. + /// Specifies the string comparison rule for the search. + /// Returns a substring after the last occurrence of the specified delimiter. + public static string SubstringAfterLast( + this string value, + string delimiter, + string? defaultValue = null, + StringComparison comparison = StringComparison.Ordinal) + { + int index = value.LastIndexOf(delimiter, comparison); + + return index switch { - int index = value.LastIndexOf(delimiter, comparison); - - return index switch - { - IndexNotFound => defaultValue ?? value, - _ => value[(index + delimiter.Length)..value.Length] - }; - } + IndexNotFound => defaultValue ?? value, + _ => value[(index + delimiter.Length)..value.Length] + }; + } + + /// + /// Converts the current to a array using the default . + /// + /// The original from which to obtain a byte array. + /// Returns a array using the default . + public static byte[] ToByteArray(this string value) + { + return ToByteArray(value, Encoding.Default); + } + + /// + /// Converts the current to a array using the specified . + /// + /// The original from which to obtain a byte array. + /// The which will be used to convert the current to a array. + /// Returns a array using the specified . + public static byte[] ToByteArray(this string value, Encoding encoding) + { + return encoding.GetBytes(value); + } + + /// + /// Converts the current between the specified before and after values. + /// + /// The current value to wrap. + /// The that should precede the current value. + /// The that should succeed the current value. + /// Returns the current wrapped between the specified before and after values. + public static string Wrap(this string value, string before, string after) + { + return $"{before}{value}{after}"; } } diff --git a/OnixLabs.Core/Text/Base16.Empty.cs b/OnixLabs.Core/Text/Base16.Empty.cs index 2412b4e..c059b38 100644 --- a/OnixLabs.Core/Text/Base16.Empty.cs +++ b/OnixLabs.Core/Text/Base16.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base16 { - public readonly partial struct Base16 - { - /// - /// Gets an empty Base-16 value. - /// - public static readonly Base16 Empty; + /// + /// Gets an empty Base-16 value. + /// + public static readonly Base16 Empty; - /// - /// Initializes static members of the class. - /// - static Base16() - { - Empty = FromByteArray(Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static Base16() + { + Empty = FromByteArray(Array.Empty()); } } diff --git a/OnixLabs.Core/Text/Base16.Equatable.cs b/OnixLabs.Core/Text/Base16.Equatable.cs index 1a00e2d..e4d923f 100644 --- a/OnixLabs.Core/Text/Base16.Equatable.cs +++ b/OnixLabs.Core/Text/Base16.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,59 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base16 : IEquatable { - public readonly partial struct Base16 : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Base16 a, Base16 b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Base16 a, Base16 b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Base16 a, Base16 b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Base16 a, Base16 b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Base16 other) - { - return other.Value.SequenceEqual(Value); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Base16 other) + { + return other.Value.SequenceEqual(Value); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Base16 other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Base16 other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Value.GetContentHashCode()); } } diff --git a/OnixLabs.Core/Text/Base16.From.cs b/OnixLabs.Core/Text/Base16.From.cs index 2cc67fd..361de10 100644 --- a/OnixLabs.Core/Text/Base16.From.cs +++ b/OnixLabs.Core/Text/Base16.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,84 +16,83 @@ using System.Linq; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base16 { - public readonly partial struct Base16 + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base16 FromByteArray(byte[] value) { - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base16 FromByteArray(byte[] value) - { - return new Base16(value); - } + return new Base16(value); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base16 FromCharArray(char[] value) - { - return FromCharArray(value, Encoding.Default); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base16 FromCharArray(char[] value) + { + return FromCharArray(value, Encoding.Default); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base16 FromCharArray(char[] value, Encoding encoding) - { - byte[] bytes = encoding.GetBytes(value); - return FromByteArray(bytes); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base16 FromCharArray(char[] value, Encoding encoding) + { + byte[] bytes = encoding.GetBytes(value); + return FromByteArray(bytes); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base16 FromSpan(ReadOnlySpan value) - { - return FromSpan(value, Encoding.Default); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base16 FromSpan(ReadOnlySpan value) + { + return FromSpan(value, Encoding.Default); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base16 FromSpan(ReadOnlySpan value, Encoding encoding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base16 FromSpan(ReadOnlySpan value, Encoding encoding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base16 FromString(string value) - { - return FromString(value, Encoding.Default); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base16 FromString(string value) + { + return FromString(value, Encoding.Default); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base16 FromString(string value, Encoding encoding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base16 FromString(string value, Encoding encoding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding); } } diff --git a/OnixLabs.Core/Text/Base16.Parse.cs b/OnixLabs.Core/Text/Base16.Parse.cs index 4f73646..5ce2028 100644 --- a/OnixLabs.Core/Text/Base16.Parse.cs +++ b/OnixLabs.Core/Text/Base16.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,41 +14,40 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base16 { - public readonly partial struct Base16 + /// + /// Parses a Base-16 (hexadecimal) value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base16 Parse(string value) { - /// - /// Parses a Base-16 (hexadecimal) value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base16 Parse(string value) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters); - } + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters); + } - /// - /// Parses a Base-16 (hexadecimal) value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base16 Parse(char[] value) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters); - } + /// + /// Parses a Base-16 (hexadecimal) value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base16 Parse(char[] value) + { + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters); + } - /// - /// Parses a Base-16 (hexadecimal) value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base16 Parse(ReadOnlySpan value) - { - byte[] bytes = Convert.FromHexString(value); - return FromByteArray(bytes); - } + /// + /// Parses a Base-16 (hexadecimal) value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base16 Parse(ReadOnlySpan value) + { + byte[] bytes = Convert.FromHexString(value); + return FromByteArray(bytes); } } diff --git a/OnixLabs.Core/Text/Base16.To.cs b/OnixLabs.Core/Text/Base16.To.cs index 45ea537..f26ab6b 100644 --- a/OnixLabs.Core/Text/Base16.To.cs +++ b/OnixLabs.Core/Text/Base16.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,45 +15,44 @@ using System; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base16 { - public readonly partial struct Base16 + /// + /// Returns a array that represents the current object. + /// + /// Returns a array that represents the current object. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the current object. - /// - /// Returns a array that represents the current object. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// Returns a that represents the current object in plain text. - public string ToPlainTextString() - { - return ToPlainTextString(Encoding.Default); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// Returns a that represents the current object in plain text. + public string ToPlainTextString() + { + return ToPlainTextString(Encoding.Default); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// The encoding to use to obtain the underlying value. - /// Returns a that represents the current object in plain text. - public string ToPlainTextString(Encoding encoding) - { - return encoding.GetString(Value); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// The encoding to use to obtain the underlying value. + /// Returns a that represents the current object in plain text. + public string ToPlainTextString(Encoding encoding) + { + return encoding.GetString(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToHexString(Value).ToLower(); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToHexString(Value).ToLower(); } } diff --git a/OnixLabs.Core/Text/Base16.cs b/OnixLabs.Core/Text/Base16.cs index 1dde93f..bf6bbcc 100644 --- a/OnixLabs.Core/Text/Base16.cs +++ b/OnixLabs.Core/Text/Base16.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Represents a Base-16 (hexadecimal) value. +/// +public readonly partial struct Base16 { /// - /// Represents a Base-16 (hexadecimal) value. + /// Initializes a new instance of the struct. /// - public readonly partial struct Base16 + /// The underlying value. + private Base16(byte[] value) { - /// - /// Initializes a new instance of the struct. - /// - /// The underlying value. - private Base16(byte[] value) - { - Value = value; - } - - /// - /// Gets the underlying value. - /// - private byte[] Value { get; } + Value = value; } + + /// + /// Gets the underlying value. + /// + private byte[] Value { get; } } diff --git a/OnixLabs.Core/Text/Base32.Codec.cs b/OnixLabs.Core/Text/Base32.Codec.cs index 8ab592b..254c197 100644 --- a/OnixLabs.Core/Text/Base32.Codec.cs +++ b/OnixLabs.Core/Text/Base32.Codec.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,143 +15,142 @@ using System; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 { - public readonly partial struct Base32 + /// + /// The Base-32 input data size. + /// + private const int InputSize = 8; + + /// + /// The Base-32 output data size. + /// + private const int OutputSize = 5; + + /// + /// Encode a byte array into a Base-32 string. + /// + /// The value to encode. + /// The Base-32 alphabet to use for encoding. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a Base-32 encoded string. + private static string Encode(byte[] value, string alphabet, bool padding) { - /// - /// The Base-32 input data size. - /// - private const int InputSize = 8; - - /// - /// The Base-32 output data size. - /// - private const int OutputSize = 5; - - /// - /// Encode a byte array into a Base-32 string. - /// - /// The value to encode. - /// The Base-32 alphabet to use for encoding. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a Base-32 encoded string. - private static string Encode(byte[] value, string alphabet, bool padding) + if (value.Length == 0) { - if (value.Length == 0) - { - return string.Empty; - } - - StringBuilder builder = new(value.Length * InputSize / OutputSize); - - int inputPosition = 0; - int inputSubPosition = 0; - byte outputPosition = 0; - int outputSubPosition = 0; - - while (inputPosition < value.Length) - { - int availableBits = Math.Min(InputSize - inputSubPosition, OutputSize - outputSubPosition); + return string.Empty; + } - outputPosition <<= availableBits; - outputPosition |= (byte) (value[inputPosition] >> (InputSize - (inputSubPosition + availableBits))); - inputSubPosition += availableBits; + StringBuilder builder = new(value.Length * InputSize / OutputSize); - if (inputSubPosition >= InputSize) - { - inputPosition++; - inputSubPosition = 0; - } + int inputPosition = 0; + int inputSubPosition = 0; + byte outputPosition = 0; + int outputSubPosition = 0; - outputSubPosition += availableBits; + while (inputPosition < value.Length) + { + int availableBits = Math.Min(InputSize - inputSubPosition, OutputSize - outputSubPosition); - if (outputSubPosition < OutputSize) continue; + outputPosition <<= availableBits; + outputPosition |= (byte) (value[inputPosition] >> (InputSize - (inputSubPosition + availableBits))); + inputSubPosition += availableBits; - outputPosition &= 0x1F; - builder.Append(alphabet[outputPosition]); - outputSubPosition = 0; + if (inputSubPosition >= InputSize) + { + inputPosition++; + inputSubPosition = 0; } - if (outputSubPosition <= 0) return builder.ToString(); + outputSubPosition += availableBits; + + if (outputSubPosition < OutputSize) continue; - outputPosition <<= (OutputSize - outputSubPosition); outputPosition &= 0x1F; builder.Append(alphabet[outputPosition]); + outputSubPosition = 0; + } - while (padding && builder.Length % InputSize != 0) - { - builder.Append('='); - } + if (outputSubPosition <= 0) return builder.ToString(); - return builder.ToString(); - } + outputPosition <<= (OutputSize - outputSubPosition); + outputPosition &= 0x1F; + builder.Append(alphabet[outputPosition]); - /// - /// Decodes a Base-32 into a byte array. - /// - /// The value to decode. - /// The Base-32 alphabet to use for decoding. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a byte array. - /// If the Base-32 string format is invalid. - private static byte[] Decode(ReadOnlySpan value, string alphabet, bool padding) + while (padding && builder.Length % InputSize != 0) { - if (value == string.Empty) - { - return Array.Empty(); - } - - if (padding && value.Length % InputSize != 0) - { - throw new FormatException("Base-23 string is invalid. Insufficient padding has been applied."); - } + builder.Append('='); + } - ReadOnlySpan valueWithoutPadding = padding ? value.TrimEnd('=') : value; + return builder.ToString(); + } - byte[] outputBytes = new byte[valueWithoutPadding.Length * OutputSize / InputSize]; + /// + /// Decodes a Base-32 into a byte array. + /// + /// The value to decode. + /// The Base-32 alphabet to use for decoding. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a byte array. + /// If the Base-32 string format is invalid. + private static byte[] Decode(ReadOnlySpan value, string alphabet, bool padding) + { + if (value == string.Empty) + { + return Array.Empty(); + } - if (outputBytes.Length == 0) - { - throw new FormatException("Base-23 string is invalid. Not enough data to construct byte array."); - } + if (padding && value.Length % InputSize != 0) + { + throw new FormatException("Base32 string is invalid. Insufficient padding has been applied."); + } - int inputPosition = 0; - int inputSubPosition = 0; - int outputPosition = 0; - int outputSubPosition = 0; + ReadOnlySpan valueWithoutPadding = padding ? value.TrimEnd('=') : value; - while (outputPosition < outputBytes.Length) - { - char character = valueWithoutPadding[inputPosition]; - int index = alphabet.IndexOf(character); + byte[] outputBytes = new byte[valueWithoutPadding.Length * OutputSize / InputSize]; - if (index < 0) - { - throw new FormatException($"Invalid Base58 character '{character}' at position {inputPosition}"); - } + if (outputBytes.Length == 0) + { + throw new FormatException("Base32 string is invalid. Not enough data to construct byte array."); + } - int availableBits = Math.Min(OutputSize - inputSubPosition, InputSize - outputSubPosition); + int inputPosition = 0; + int inputSubPosition = 0; + int outputPosition = 0; + int outputSubPosition = 0; - outputBytes[outputPosition] <<= availableBits; - outputBytes[outputPosition] |= (byte) (index >> (OutputSize - (inputSubPosition + availableBits))); - outputSubPosition += availableBits; + while (outputPosition < outputBytes.Length) + { + char character = valueWithoutPadding[inputPosition]; + int index = alphabet.IndexOf(character); - if (outputSubPosition >= InputSize) - { - outputPosition++; - outputSubPosition = 0; - } + if (index < 0) + { + throw new FormatException($"Invalid Base32 character '{character}' at position {inputPosition}"); + } - inputSubPosition += availableBits; + int availableBits = Math.Min(OutputSize - inputSubPosition, InputSize - outputSubPosition); - if (inputSubPosition < OutputSize) continue; + outputBytes[outputPosition] <<= availableBits; + outputBytes[outputPosition] |= (byte) (index >> (OutputSize - (inputSubPosition + availableBits))); + outputSubPosition += availableBits; - inputPosition++; - inputSubPosition = 0; + if (outputSubPosition >= InputSize) + { + outputPosition++; + outputSubPosition = 0; } - return outputBytes; + inputSubPosition += availableBits; + + if (inputSubPosition < OutputSize) continue; + + inputPosition++; + inputSubPosition = 0; } + + return outputBytes; } } diff --git a/OnixLabs.Core/Text/Base32.Empty.cs b/OnixLabs.Core/Text/Base32.Empty.cs index 26730c1..6f5006d 100644 --- a/OnixLabs.Core/Text/Base32.Empty.cs +++ b/OnixLabs.Core/Text/Base32.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 { - public readonly partial struct Base32 - { - /// - /// Gets an empty Base-32 value. - /// - public static readonly Base32 Empty; + /// + /// Gets an empty Base-32 value. + /// + public static readonly Base32 Empty; - /// - /// Initializes static members of the class. - /// - static Base32() - { - Empty = FromByteArray(Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static Base32() + { + Empty = FromByteArray(Array.Empty()); } } diff --git a/OnixLabs.Core/Text/Base32.Equatable.cs b/OnixLabs.Core/Text/Base32.Equatable.cs index 65b904f..ebdd552 100644 --- a/OnixLabs.Core/Text/Base32.Equatable.cs +++ b/OnixLabs.Core/Text/Base32.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,61 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 : IEquatable { - public readonly partial struct Base32 : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Base32 a, Base32 b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Base32 a, Base32 b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Base32 a, Base32 b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Base32 a, Base32 b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Base32 other) - { - return other.Value.SequenceEqual(Value) - && other.Alphabet == Alphabet - && other.Padding == Padding; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Base32 other) + { + return other.Value.SequenceEqual(Value) && other.Alphabet == Alphabet && other.Padding == Padding; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Base32 other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Base32 other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Value.GetContentHashCode()); } } diff --git a/OnixLabs.Core/Text/Base32.From.cs b/OnixLabs.Core/Text/Base32.From.cs index 34fed69..0105180 100644 --- a/OnixLabs.Core/Text/Base32.From.cs +++ b/OnixLabs.Core/Text/Base32.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,335 +16,334 @@ using System.Linq; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 { - public readonly partial struct Base32 + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base32 FromByteArray(byte[] value) { - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base32 FromByteArray(byte[] value) - { - return FromByteArray(value, Base32Alphabet.Default); - } + return FromByteArray(value, Base32Alphabet.Default); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromByteArray(byte[] value, Base32Alphabet alphabet) - { - return FromByteArray(value, alphabet, true); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromByteArray(byte[] value, Base32Alphabet alphabet) + { + return FromByteArray(value, alphabet, true); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromByteArray(byte[] value, bool padding) - { - return FromByteArray(value, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromByteArray(byte[] value, bool padding) + { + return FromByteArray(value, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromByteArray(byte[] value, Base32Alphabet alphabet, bool padding) - { - return new Base32(value, alphabet, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromByteArray(byte[] value, Base32Alphabet alphabet, bool padding) + { + return new Base32(value, alphabet, padding); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value) - { - return FromCharArray(value, Encoding.Default, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value) + { + return FromCharArray(value, Encoding.Default, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Encoding encoding) - { - return FromCharArray(value, encoding, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Encoding encoding) + { + return FromCharArray(value, encoding, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, bool padding) - { - return FromCharArray(value, Encoding.Default, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, bool padding) + { + return FromCharArray(value, Encoding.Default, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Encoding encoding, bool padding) - { - return FromCharArray(value, encoding, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Encoding encoding, bool padding) + { + return FromCharArray(value, encoding, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Base32Alphabet alphabet) - { - return FromCharArray(value, Encoding.Default, alphabet); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Base32Alphabet alphabet) + { + return FromCharArray(value, Encoding.Default, alphabet); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Encoding encoding, Base32Alphabet alphabet) - { - byte[] bytes = encoding.GetBytes(value); - return FromByteArray(bytes, alphabet); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Encoding encoding, Base32Alphabet alphabet) + { + byte[] bytes = encoding.GetBytes(value); + return FromByteArray(bytes, alphabet); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Base32Alphabet alphabet, bool padding) - { - return FromCharArray(value, Encoding.Default, alphabet, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Base32Alphabet alphabet, bool padding) + { + return FromCharArray(value, Encoding.Default, alphabet, padding); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromCharArray(char[] value, Encoding encoding, Base32Alphabet alphabet, bool padding) - { - byte[] bytes = encoding.GetBytes(value); - return FromByteArray(bytes, alphabet, padding); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromCharArray(char[] value, Encoding encoding, Base32Alphabet alphabet, bool padding) + { + byte[] bytes = encoding.GetBytes(value); + return FromByteArray(bytes, alphabet, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value) - { - return FromSpan(value, Encoding.Default, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value) + { + return FromSpan(value, Encoding.Default, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding) - { - return FromSpan(value, encoding, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding) + { + return FromSpan(value, encoding, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, bool padding) - { - return FromSpan(value, Encoding.Default, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, bool padding) + { + return FromSpan(value, Encoding.Default, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, bool padding) - { - return FromSpan(value, encoding, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, bool padding) + { + return FromSpan(value, encoding, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Base32Alphabet alphabet) - { - return FromSpan(value, Encoding.Default, alphabet); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Base32Alphabet alphabet) + { + return FromSpan(value, Encoding.Default, alphabet); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, Base32Alphabet alphabet) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, Base32Alphabet alphabet) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Base32Alphabet alphabet, bool padding) - { - return FromSpan(value, Encoding.Default, alphabet, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Base32Alphabet alphabet, bool padding) + { + return FromSpan(value, Encoding.Default, alphabet, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, Base32Alphabet alphabet, - bool padding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromSpan(ReadOnlySpan value, Encoding encoding, Base32Alphabet alphabet, + bool padding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base32 FromString(string value) - { - return FromString(value, Encoding.Default, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base32 FromString(string value) + { + return FromString(value, Encoding.Default, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base32 FromString(string value, Encoding encoding) - { - return FromString(value, encoding, Base32Alphabet.Default, true); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base32 FromString(string value, Encoding encoding) + { + return FromString(value, encoding, Base32Alphabet.Default, true); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, bool padding) - { - return FromString(value, Encoding.Default, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, bool padding) + { + return FromString(value, Encoding.Default, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, Encoding encoding, bool padding) - { - return FromString(value, encoding, Base32Alphabet.Default, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, Encoding encoding, bool padding) + { + return FromString(value, encoding, Base32Alphabet.Default, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, Base32Alphabet alphabet) - { - return FromString(value, Encoding.Default, alphabet); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, Base32Alphabet alphabet) + { + return FromString(value, Encoding.Default, alphabet); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, Encoding encoding, Base32Alphabet alphabet) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, Encoding encoding, Base32Alphabet alphabet) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, Base32Alphabet alphabet, bool padding) - { - return FromString(value, Encoding.Default, alphabet, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, Base32Alphabet alphabet, bool padding) + { + return FromString(value, Encoding.Default, alphabet, padding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - /// Returns a new instance. - public static Base32 FromString(string value, Encoding encoding, Base32Alphabet alphabet, bool padding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet, padding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + /// Returns a new instance. + public static Base32 FromString(string value, Encoding encoding, Base32Alphabet alphabet, bool padding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet, padding); } } diff --git a/OnixLabs.Core/Text/Base32.Parse.cs b/OnixLabs.Core/Text/Base32.Parse.cs index 9a3cdf9..0b81a7a 100644 --- a/OnixLabs.Core/Text/Base32.Parse.cs +++ b/OnixLabs.Core/Text/Base32.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,75 +14,74 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 { - public readonly partial struct Base32 + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base32 Parse(string value) { - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base32 Parse(string value) - { - return Parse(value, Base32Alphabet.Default); - } + return Parse(value, Base32Alphabet.Default); + } - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// A new instance. - public static Base32 Parse(string value, Base32Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters, alphabet); - } + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// A new instance. + public static Base32 Parse(string value, Base32Alphabet alphabet) + { + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters, alphabet); + } - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base32 Parse(char[] value) - { - return Parse(value, Base32Alphabet.Default); - } + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base32 Parse(char[] value) + { + return Parse(value, Base32Alphabet.Default); + } - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// A new instance. - public static Base32 Parse(char[] value, Base32Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters, alphabet); - } + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// A new instance. + public static Base32 Parse(char[] value, Base32Alphabet alphabet) + { + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters, alphabet); + } - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base32 Parse(ReadOnlySpan value) - { - return Parse(value, Base32Alphabet.Default); - } + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base32 Parse(ReadOnlySpan value) + { + return Parse(value, Base32Alphabet.Default); + } - /// - /// Parses a Base-32 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// A new instance. - public static Base32 Parse(ReadOnlySpan value, Base32Alphabet alphabet) - { - bool padding = value.Contains('='); - byte[] bytes = Decode(value, alphabet.Alphabet, padding); - return FromByteArray(bytes, padding); - } + /// + /// Parses a Base-32 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// A new instance. + public static Base32 Parse(ReadOnlySpan value, Base32Alphabet alphabet) + { + bool padding = value.Contains('='); + byte[] bytes = Decode(value, alphabet.Alphabet, padding); + return FromByteArray(bytes, padding); } } diff --git a/OnixLabs.Core/Text/Base32.To.cs b/OnixLabs.Core/Text/Base32.To.cs index a94ac95..eded14e 100644 --- a/OnixLabs.Core/Text/Base32.To.cs +++ b/OnixLabs.Core/Text/Base32.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,45 +14,44 @@ using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base32 { - public readonly partial struct Base32 + /// + /// Returns a array that represents the current object. + /// + /// Returns a array that represents the current object. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the current object. - /// - /// Returns a array that represents the current object. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// Returns a that represents the current object in plain text. - public string ToPlainTextString() - { - return ToPlainTextString(Encoding.Default); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// Returns a that represents the current object in plain text. + public string ToPlainTextString() + { + return ToPlainTextString(Encoding.Default); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// The encoding to use to obtain the underlying value. - /// Returns a that represents the current object in plain text. - public string ToPlainTextString(Encoding encoding) - { - return encoding.GetString(Value); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// The encoding to use to obtain the underlying value. + /// Returns a that represents the current object in plain text. + public string ToPlainTextString(Encoding encoding) + { + return encoding.GetString(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Encode(Value, Alphabet.Alphabet, Padding); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Encode(Value, Alphabet.Alphabet, Padding); } } diff --git a/OnixLabs.Core/Text/Base32.cs b/OnixLabs.Core/Text/Base32.cs index 1637779..855b754 100644 --- a/OnixLabs.Core/Text/Base32.cs +++ b/OnixLabs.Core/Text/Base32.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,39 +12,38 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Represents a Base-32 value. +/// +public readonly partial struct Base32 { /// - /// Represents a Base-32 value. + /// Initializes a new instance of the struct. /// - public readonly partial struct Base32 + /// The underlying value. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + /// Determines whether padding should be applied for Base-32 encoding and decoding operations. + private Base32(byte[] value, Base32Alphabet alphabet, bool padding) { - /// - /// Initializes a new instance of the struct. - /// - /// The underlying value. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - /// Determines whether padding should be applied for Base-32 encoding and decoding operations. - private Base32(byte[] value, Base32Alphabet alphabet, bool padding) - { - Value = value; - Alphabet = alphabet; - Padding = padding; - } + Value = value; + Alphabet = alphabet; + Padding = padding; + } - /// - /// Gets the underlying value. - /// - private byte[] Value { get; } + /// + /// Gets the underlying value. + /// + private byte[] Value { get; } - /// - /// Gets the alphabet that will be used for Base-32 encoding and decoding operations. - /// - private Base32Alphabet Alphabet { get; } + /// + /// Gets the alphabet that will be used for Base-32 encoding and decoding operations. + /// + private Base32Alphabet Alphabet { get; } - /// - /// Gets a value that determines whether padding should be applied for Base-32 encoding and decoding operations. - /// - private bool Padding { get; } - } + /// + /// Gets a value that determines whether padding should be applied for Base-32 encoding and decoding operations. + /// + private bool Padding { get; } } diff --git a/OnixLabs.Core/Text/Base32Alphabet.cs b/OnixLabs.Core/Text/Base32Alphabet.cs index 6fd845d..b27ca52 100644 --- a/OnixLabs.Core/Text/Base32Alphabet.cs +++ b/OnixLabs.Core/Text/Base32Alphabet.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,57 +12,56 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Specifies the supported Base-32 alphabets. +/// +public sealed class Base32Alphabet : Enumeration { /// - /// Specifies the supported Base-32 alphabets. + /// The default (RFC-4648) Base-32 alphabet. /// - public sealed class Base32Alphabet : Enumeration - { - /// - /// The default (RFC-4648) Base-32 alphabet. - /// - public static readonly Base32Alphabet Default = - new(0, nameof(Default), "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); - - /// - /// The Z-Base-32 alphabet. - /// - public static readonly Base32Alphabet ZBase32 = - new(1, nameof(ZBase32), "ybndrfg8ejkmcpqxot1uwisza345h769"); + public static readonly Base32Alphabet Default = + new(0, nameof(Default), "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); - /// - /// The Geohash Base-32 alphabet. - /// - public static readonly Base32Alphabet GeoHash = - new(2, nameof(GeoHash), "0123456789bcdefghjkmnpqrstuvwxyz"); + /// + /// The Z-Base-32 alphabet. + /// + public static readonly Base32Alphabet ZBase32 = + new(1, nameof(ZBase32), "ybndrfg8ejkmcpqxot1uwisza345h769"); - /// - /// The Crockford Base-32 alphabet. - /// - public static readonly Base32Alphabet Crockford = - new(3, nameof(Crockford), "0123456789ABCDEFGHJKMNPQRSTVWXYZ"); + /// + /// The Geohash Base-32 alphabet. + /// + public static readonly Base32Alphabet GeoHash = + new(2, nameof(GeoHash), "0123456789bcdefghjkmnpqrstuvwxyz"); - /// - /// The Base-32 Hex alphabet. - /// - public static readonly Base32Alphabet Base32Hex = - new(4, nameof(Base32Hex), "0123456789ABCDEFGHIJKLMNOPQRSTUV"); + /// + /// The Crockford Base-32 alphabet. + /// + public static readonly Base32Alphabet Crockford = + new(3, nameof(Crockford), "0123456789ABCDEFGHJKMNPQRSTVWXYZ"); - /// - /// Initializes a new instance of the class. - /// - /// The value of the enumeration entry. - /// The name of the enumeration entry. - /// The alphabet that will be used for Base-32 encoding and decoding operations. - private Base32Alphabet(int value, string name, string alphabet) : base(value, name) - { - Alphabet = alphabet; - } + /// + /// The Base-32 Hex alphabet. + /// + public static readonly Base32Alphabet Base32Hex = + new(4, nameof(Base32Hex), "0123456789ABCDEFGHIJKLMNOPQRSTUV"); - /// - /// Gets the alphabet that will be used for Base-32 encoding and decoding operations. - /// - public string Alphabet { get; } + /// + /// Initializes a new instance of the class. + /// + /// The value of the enumeration entry. + /// The name of the enumeration entry. + /// The alphabet that will be used for Base-32 encoding and decoding operations. + private Base32Alphabet(int value, string name, string alphabet) : base(value, name) + { + Alphabet = alphabet; } + + /// + /// Gets the alphabet that will be used for Base-32 encoding and decoding operations. + /// + public string Alphabet { get; } } diff --git a/OnixLabs.Core/Text/Base58.Checksum.cs b/OnixLabs.Core/Text/Base58.Checksum.cs index 4fa3c11..9222d17 100644 --- a/OnixLabs.Core/Text/Base58.Checksum.cs +++ b/OnixLabs.Core/Text/Base58.Checksum.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,79 +16,78 @@ using System.Linq; using System.Security.Cryptography; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 + /// + /// The size of a Base-58 checksum. + /// + private const int ChecksumSize = 4; + + /// + /// Computes a Base-58 checksum. + /// + /// The value for which to compute a Base-58 checksum. + /// Returns the computed Base-58 checksum. + private static byte[] ComputeChecksum(byte[] value) { - /// - /// The size of a Base-58 checksum. - /// - private const int ChecksumSize = 4; + using HashAlgorithm algorithm = SHA256.Create(); - /// - /// Computes a Base-58 checksum. - /// - /// The value for which to compute a Base-58 checksum. - /// Returns the computed Base-58 checksum. - private static byte[] ComputeChecksum(byte[] value) - { - using HashAlgorithm algorithm = SHA256.Create(); + byte[] hashedValue = algorithm.ComputeHash(value); + byte[] checksum = algorithm.ComputeHash(hashedValue); + byte[] result = new byte[ChecksumSize]; - byte[] hashedValue = algorithm.ComputeHash(value); - byte[] checksum = algorithm.ComputeHash(hashedValue); - byte[] result = new byte[ChecksumSize]; + Buffer.BlockCopy(checksum, 0, result, 0, result.Length); - Buffer.BlockCopy(checksum, 0, result, 0, result.Length); + return result; + } - return result; - } + /// + /// Adds a checksum to the specified byte array. + /// + /// The value for which to add a checksum. + /// Returns the original value with a checksum. + private static byte[] AddChecksum(byte[] value) + { + byte[] checksum = ComputeChecksum(value); + return value.ConcatenateWith(checksum); + } - /// - /// Adds a checksum to the specified byte array. - /// - /// The value for which to add a checksum. - /// Returns the original value with a checksum. - private static byte[] AddChecksum(byte[] value) - { - byte[] checksum = ComputeChecksum(value); - return value.ConcatenateWith(checksum); - } + /// + /// Removes a checksum from the specified byte array. + /// + /// The value for which to remove a checksum. + /// Returns the original value without a checksum. + private static byte[] RemoveChecksum(byte[] value) + { + return value.Copy(0, value.Length - ChecksumSize); + } - /// - /// Removes a checksum from the specified byte array. - /// - /// The value for which to remove a checksum. - /// Returns the original value without a checksum. - private static byte[] RemoveChecksum(byte[] value) - { - return value.Copy(0, value.Length - ChecksumSize); - } + /// + /// Gets a checksum from the specified byte array. + /// + /// The value from which to obtain a checksum. + /// Returns a checksum from the specified byte array. + private static byte[] GetChecksum(byte[] value) + { + return value.Copy(value.Length - ChecksumSize - 1, ChecksumSize); + } - /// - /// Gets a checksum from the specified byte array. - /// - /// The value from which to obtain a checksum. - /// Returns a checksum from the specified byte array. - private static byte[] GetChecksum(byte[] value) - { - return value.Copy(value.Length - ChecksumSize - 1, ChecksumSize); - } + /// + /// Verifies a Base-58 checksum. + /// + /// The value for which to verify its checksum. + /// If the Base-58 checksum is invalid. + private static void VerifyChecksum(byte[] value) + { + byte[] valueWithoutChecksum = RemoveChecksum(value); + byte[] originalChecksum = GetChecksum(value); + byte[] computedChecksum = ComputeChecksum(valueWithoutChecksum); - /// - /// Verifies a Base-58 checksum. - /// - /// The value for which to verify its checksum. - /// If the Base-58 checksum is invalid. - private static void VerifyChecksum(byte[] value) + if (!originalChecksum.SequenceEqual(computedChecksum)) { - byte[] valueWithoutChecksum = RemoveChecksum(value); - byte[] originalChecksum = GetChecksum(value); - byte[] computedChecksum = ComputeChecksum(valueWithoutChecksum); - - if (!originalChecksum.SequenceEqual(computedChecksum)) - { - throw new FormatException("Base-58 checksum is invalid."); - } + throw new FormatException("Base-58 checksum is invalid."); } } } diff --git a/OnixLabs.Core/Text/Base58.Codec.cs b/OnixLabs.Core/Text/Base58.Codec.cs index f850901..36b1146 100644 --- a/OnixLabs.Core/Text/Base58.Codec.cs +++ b/OnixLabs.Core/Text/Base58.Codec.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,76 +18,75 @@ using System.Numerics; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 + /// + /// Encode a byte array into a Base-58 string. + /// + /// The value to encode. + /// The Base-58 alphabet to use for encoding. + /// Returns a Base-58 encoded string. + private static string Encode(byte[] value, string alphabet) { - /// - /// Encode a byte array into a Base-58 string. - /// - /// The value to encode. - /// The Base-58 alphabet to use for encoding. - /// Returns a Base-58 encoded string. - private static string Encode(byte[] value, string alphabet) + BigInteger data = value.Aggregate(BigInteger.Zero, (a, b) => a * 256 + b); + StringBuilder result = new(); + + while (data > 0) { - BigInteger data = value.Aggregate(BigInteger.Zero, (a, b) => a * 256 + b); - StringBuilder result = new(); + BigInteger remainder = data % 58; + data /= 58; + result.Insert(0, alphabet[(int) remainder]); + } - while (data > 0) - { - BigInteger remainder = data % 58; - data /= 58; - result.Insert(0, alphabet[(int) remainder]); - } + for (int index = 0; index < value.Length && value[index] == 0; index++) + { + result.Insert(0, '1'); + } - for (int index = 0; index < value.Length && value[index] == 0; index++) - { - result.Insert(0, '1'); - } + return result.ToString(); + } - return result.ToString(); - } + /// + /// Decodes a Base-58 into a byte array. + /// + /// The value to decode. + /// The Base-58 alphabet to use for decoding. + /// Returns a byte array. + /// If the Base-58 string format is invalid. + private static byte[] Decode(ReadOnlySpan value, string alphabet) + { + BigInteger data = BigInteger.Zero; - /// - /// Decodes a Base-58 into a byte array. - /// - /// The value to decode. - /// The Base-58 alphabet to use for decoding. - /// Returns a byte array. - /// If the Base-58 string format is invalid. - private static byte[] Decode(ReadOnlySpan value, string alphabet) + for (int index = 0; index < value.Length; index++) { - BigInteger data = BigInteger.Zero; + char character = value[index]; + int characterIndex = alphabet.IndexOf(character); - for (int index = 0; index < value.Length; index++) + if (characterIndex < 0) { - char character = value[index]; - int characterIndex = alphabet.IndexOf(character); - - if (characterIndex < 0) - { - throw new FormatException($"Invalid Base58 character '{character}' at position {index}"); - } - - data = data * 58 + characterIndex; + throw new FormatException($"Invalid Base58 character '{character}' at position {index}"); } - int leadingZeroCount = value - .ToArray() - .TakeWhile(character => character == '1') - .Count(); + data = data * 58 + characterIndex; + } + + int leadingZeroCount = value + .ToArray() + .TakeWhile(character => character == '1') + .Count(); - IEnumerable leadingZeros = Enumerable - .Repeat(byte.MinValue, leadingZeroCount); + IEnumerable leadingZeros = Enumerable + .Repeat(byte.MinValue, leadingZeroCount); - IEnumerable bytesWithoutLeadingZeros = data - .ToByteArray() - .Reverse() - .SkipWhile(byteValue => byteValue == 0); + IEnumerable bytesWithoutLeadingZeros = data + .ToByteArray() + .Reverse() + .SkipWhile(byteValue => byteValue == 0); - return leadingZeros - .Concat(bytesWithoutLeadingZeros) - .ToArray(); - } + return leadingZeros + .Concat(bytesWithoutLeadingZeros) + .ToArray(); } } diff --git a/OnixLabs.Core/Text/Base58.Empty.cs b/OnixLabs.Core/Text/Base58.Empty.cs index 4c748af..e6674c0 100644 --- a/OnixLabs.Core/Text/Base58.Empty.cs +++ b/OnixLabs.Core/Text/Base58.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 - { - /// - /// Gets an empty Base-58 value. - /// - public static readonly Base58 Empty; + /// + /// Gets an empty Base-58 value. + /// + public static readonly Base58 Empty; - /// - /// Initializes static members of the class. - /// - static Base58() - { - Empty = FromByteArray(Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static Base58() + { + Empty = FromByteArray(Array.Empty()); } } diff --git a/OnixLabs.Core/Text/Base58.Equatable.cs b/OnixLabs.Core/Text/Base58.Equatable.cs index efba863..d310372 100644 --- a/OnixLabs.Core/Text/Base58.Equatable.cs +++ b/OnixLabs.Core/Text/Base58.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,60 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 : IEquatable { - public readonly partial struct Base58 : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Base58 a, Base58 b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Base58 a, Base58 b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Base58 a, Base58 b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Base58 a, Base58 b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Base58 other) - { - return other.Value.SequenceEqual(Value) - && other.Alphabet == Alphabet; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Base58 other) + { + return other.Value.SequenceEqual(Value) && other.Alphabet == Alphabet; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Base58 other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Base58 other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Value.GetContentHashCode()); } } diff --git a/OnixLabs.Core/Text/Base58.From.cs b/OnixLabs.Core/Text/Base58.From.cs index 368d901..807c59f 100644 --- a/OnixLabs.Core/Text/Base58.From.cs +++ b/OnixLabs.Core/Text/Base58.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,164 +16,163 @@ using System.Linq; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base58 FromByteArray(byte[] value) + { + return new Base58(value, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromByteArray(byte[] value, Base58Alphabet alphabet) + { + return new Base58(value, alphabet); + } + + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base58 FromCharArray(char[] value) + { + return FromCharArray(value, Encoding.Default, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base58 FromCharArray(char[] value, Encoding encoding) + { + return FromCharArray(value, encoding, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromCharArray(char[] value, Base58Alphabet alphabet) + { + return FromCharArray(value, Encoding.Default, alphabet); + } + + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromCharArray(char[] value, Encoding encoding, Base58Alphabet alphabet) + { + byte[] bytes = encoding.GetBytes(value); + return FromByteArray(bytes, alphabet); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base58 FromSpan(ReadOnlySpan value) + { + return FromSpan(value, Encoding.Default, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base58 FromSpan(ReadOnlySpan value, Encoding encoding) + { + return FromSpan(value, encoding, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromSpan(ReadOnlySpan value, Base58Alphabet alphabet) + { + return FromSpan(value, Encoding.Default, alphabet); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromSpan(ReadOnlySpan value, Encoding encoding, Base58Alphabet alphabet) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base58 FromString(string value) + { + return FromString(value, Encoding.Default, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base58 FromString(string value, Encoding encoding) + { + return FromString(value, encoding, Base58Alphabet.Default); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromString(string value, Base58Alphabet alphabet) + { + return FromString(value, Encoding.Default, alphabet); + } + + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// Returns a new instance. + public static Base58 FromString(string value, Encoding encoding, Base58Alphabet alphabet) { - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base58 FromByteArray(byte[] value) - { - return new Base58(value, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromByteArray(byte[] value, Base58Alphabet alphabet) - { - return new Base58(value, alphabet); - } - - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base58 FromCharArray(char[] value) - { - return FromCharArray(value, Encoding.Default, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base58 FromCharArray(char[] value, Encoding encoding) - { - return FromCharArray(value, encoding, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromCharArray(char[] value, Base58Alphabet alphabet) - { - return FromCharArray(value, Encoding.Default, alphabet); - } - - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromCharArray(char[] value, Encoding encoding, Base58Alphabet alphabet) - { - byte[] bytes = encoding.GetBytes(value); - return FromByteArray(bytes, alphabet); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base58 FromSpan(ReadOnlySpan value) - { - return FromSpan(value, Encoding.Default, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base58 FromSpan(ReadOnlySpan value, Encoding encoding) - { - return FromSpan(value, encoding, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromSpan(ReadOnlySpan value, Base58Alphabet alphabet) - { - return FromSpan(value, Encoding.Default, alphabet); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromSpan(ReadOnlySpan value, Encoding encoding, Base58Alphabet alphabet) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base58 FromString(string value) - { - return FromString(value, Encoding.Default, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base58 FromString(string value, Encoding encoding) - { - return FromString(value, encoding, Base58Alphabet.Default); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromString(string value, Base58Alphabet alphabet) - { - return FromString(value, Encoding.Default, alphabet); - } - - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// Returns a new instance. - public static Base58 FromString(string value, Encoding encoding, Base58Alphabet alphabet) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding, alphabet); - } + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding, alphabet); } } diff --git a/OnixLabs.Core/Text/Base58.Parse.cs b/OnixLabs.Core/Text/Base58.Parse.cs index c748035..ef75b70 100644 --- a/OnixLabs.Core/Text/Base58.Parse.cs +++ b/OnixLabs.Core/Text/Base58.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,144 +14,143 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base58 Parse(string value) + { + return Parse(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 Parse(string value, Base58Alphabet alphabet) + { + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters, alphabet); + } + + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base58 Parse(char[] value) + { + return Parse(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 Parse(char[] value, Base58Alphabet alphabet) + { + ReadOnlySpan characters = value.AsSpan(); + return Parse(characters, alphabet); + } + + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// A new instance. + public static Base58 Parse(ReadOnlySpan value) + { + return Parse(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 Parse(ReadOnlySpan value, Base58Alphabet alphabet) + { + byte[] bytes = Decode(value, alphabet.Alphabet); + return FromByteArray(bytes, alphabet); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// A new instance. + public static Base58 ParseWithChecksum(string value) + { + return ParseWithChecksum(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 ParseWithChecksum(string value, Base58Alphabet alphabet) + { + ReadOnlySpan characters = value.AsSpan(); + return ParseWithChecksum(characters, alphabet); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// A new instance. + public static Base58 ParseWithChecksum(char[] value) + { + return ParseWithChecksum(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 ParseWithChecksum(char[] value, Base58Alphabet alphabet) { - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base58 Parse(string value) - { - return Parse(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 Parse(string value, Base58Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters, alphabet); - } - - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base58 Parse(char[] value) - { - return Parse(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 Parse(char[] value, Base58Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return Parse(characters, alphabet); - } - - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// A new instance. - public static Base58 Parse(ReadOnlySpan value) - { - return Parse(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 Parse(ReadOnlySpan value, Base58Alphabet alphabet) - { - byte[] bytes = Decode(value, alphabet.Alphabet); - return FromByteArray(bytes, alphabet); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// A new instance. - public static Base58 ParseWithChecksum(string value) - { - return ParseWithChecksum(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 ParseWithChecksum(string value, Base58Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return ParseWithChecksum(characters, alphabet); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// A new instance. - public static Base58 ParseWithChecksum(char[] value) - { - return ParseWithChecksum(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 ParseWithChecksum(char[] value, Base58Alphabet alphabet) - { - ReadOnlySpan characters = value.AsSpan(); - return ParseWithChecksum(characters, alphabet); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// A new instance. - public static Base58 ParseWithChecksum(ReadOnlySpan value) - { - return ParseWithChecksum(value, Base58Alphabet.Default); - } - - /// - /// Parses a Base-58 value with a checksum into a instance. - /// - /// The Base-16 (hexadecimal) value to ParseWithChecksum. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - /// A new instance. - public static Base58 ParseWithChecksum(ReadOnlySpan value, Base58Alphabet alphabet) - { - byte[] bytes = Decode(value, alphabet.Alphabet); - byte[] bytesWithoutChecksum = RemoveChecksum(bytes); - - VerifyChecksum(bytes); - - return FromByteArray(bytesWithoutChecksum, alphabet); - } + ReadOnlySpan characters = value.AsSpan(); + return ParseWithChecksum(characters, alphabet); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// A new instance. + public static Base58 ParseWithChecksum(ReadOnlySpan value) + { + return ParseWithChecksum(value, Base58Alphabet.Default); + } + + /// + /// Parses a Base-58 value with a checksum into a instance. + /// + /// The Base-16 (hexadecimal) value to ParseWithChecksum. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + /// A new instance. + public static Base58 ParseWithChecksum(ReadOnlySpan value, Base58Alphabet alphabet) + { + byte[] bytes = Decode(value, alphabet.Alphabet); + byte[] bytesWithoutChecksum = RemoveChecksum(bytes); + + VerifyChecksum(bytes); + + return FromByteArray(bytesWithoutChecksum, alphabet); } } diff --git a/OnixLabs.Core/Text/Base58.To.cs b/OnixLabs.Core/Text/Base58.To.cs index c97bc44..767e2f8 100644 --- a/OnixLabs.Core/Text/Base58.To.cs +++ b/OnixLabs.Core/Text/Base58.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,56 +14,55 @@ using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base58 { - public readonly partial struct Base58 + /// + /// Returns a array that represents the current object. + /// + /// Returns a array that represents the current object. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the current object. - /// - /// Returns a array that represents the current object. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a that represents the current object, with a checksum. - /// - /// A that represents the current object, with a checksum. - public string ToStringWithChecksum() - { - byte[] valueWithChecksum = AddChecksum(Value); - return Encode(valueWithChecksum, Alphabet.Alphabet); - } + /// + /// Returns a that represents the current object, with a checksum. + /// + /// A that represents the current object, with a checksum. + public string ToStringWithChecksum() + { + byte[] valueWithChecksum = AddChecksum(Value); + return Encode(valueWithChecksum, Alphabet.Alphabet); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// Returns a that represents the current object in plain text. - public string ToPlainTextString() - { - return ToPlainTextString(Encoding.Default); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// Returns a that represents the current object in plain text. + public string ToPlainTextString() + { + return ToPlainTextString(Encoding.Default); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// The encoding to use to obtain the underlying value. - /// Returns a that represents the current object in plain text. - public string ToPlainTextString(Encoding encoding) - { - return encoding.GetString(Value); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// The encoding to use to obtain the underlying value. + /// Returns a that represents the current object in plain text. + public string ToPlainTextString(Encoding encoding) + { + return encoding.GetString(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Encode(Value, Alphabet.Alphabet); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Encode(Value, Alphabet.Alphabet); } } diff --git a/OnixLabs.Core/Text/Base58.cs b/OnixLabs.Core/Text/Base58.cs index 0e8c674..178bcae 100644 --- a/OnixLabs.Core/Text/Base58.cs +++ b/OnixLabs.Core/Text/Base58.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,32 +12,31 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Represents a Base-58 value. +/// +public readonly partial struct Base58 { /// - /// Represents a Base-58 value. + /// Initializes a new instance of the struct. /// - public readonly partial struct Base58 + /// The underlying value. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + private Base58(byte[] value, Base58Alphabet alphabet) { - /// - /// Initializes a new instance of the struct. - /// - /// The underlying value. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - private Base58(byte[] value, Base58Alphabet alphabet) - { - Value = value; - Alphabet = alphabet; - } + Value = value; + Alphabet = alphabet; + } - /// - /// Gets the underlying value. - /// - private byte[] Value { get; } + /// + /// Gets the underlying value. + /// + private byte[] Value { get; } - /// - /// Gets the alphabet that will be used for Base-58 encoding and decoding operations. - /// - private Base58Alphabet Alphabet { get; } - } + /// + /// Gets the alphabet that will be used for Base-58 encoding and decoding operations. + /// + private Base58Alphabet Alphabet { get; } } diff --git a/OnixLabs.Core/Text/Base58Alphabet.cs b/OnixLabs.Core/Text/Base58Alphabet.cs index 6f8c7a0..6cde86c 100644 --- a/OnixLabs.Core/Text/Base58Alphabet.cs +++ b/OnixLabs.Core/Text/Base58Alphabet.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,45 +12,44 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Specifies the supported Base-58 alphabets. +/// +public sealed class Base58Alphabet : Enumeration { /// - /// Specifies the supported Base-58 alphabets. + /// The default Base-58 alphabet, which is the same as Bitcoin's Base-58 alphabet. /// - public sealed class Base58Alphabet : Enumeration - { - /// - /// The default Base-58 alphabet, which is the same as Bitcoin's Base-58 alphabet. - /// - public static readonly Base58Alphabet Default = - new(0, nameof(Default), "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); + public static readonly Base58Alphabet Default = + new(0, nameof(Default), "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - /// - /// The Ripple Base-58 alphabet. - /// - public static readonly Base58Alphabet Ripple = - new(0, nameof(Ripple), "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - - /// - /// The Flickr Base-58 alphabet. - /// - public static readonly Base58Alphabet Flickr = - new(0, nameof(Flickr), "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); + /// + /// The Ripple Base-58 alphabet. + /// + public static readonly Base58Alphabet Ripple = + new(0, nameof(Ripple), "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - /// - /// Initializes a new instance of the class. - /// - /// The value of the enumeration entry. - /// The name of the enumeration entry. - /// The alphabet that will be used for Base-58 encoding and decoding operations. - private Base58Alphabet(int value, string name, string alphabet) : base(value, name) - { - Alphabet = alphabet; - } + /// + /// The Flickr Base-58 alphabet. + /// + public static readonly Base58Alphabet Flickr = + new(0, nameof(Flickr), "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - /// - /// Gets the alphabet that will be used for Base-58 encoding and decoding operations. - /// - public string Alphabet { get; } + /// + /// Initializes a new instance of the class. + /// + /// The value of the enumeration entry. + /// The name of the enumeration entry. + /// The alphabet that will be used for Base-58 encoding and decoding operations. + private Base58Alphabet(int value, string name, string alphabet) : base(value, name) + { + Alphabet = alphabet; } + + /// + /// Gets the alphabet that will be used for Base-58 encoding and decoding operations. + /// + public string Alphabet { get; } } diff --git a/OnixLabs.Core/Text/Base64.Empty.cs b/OnixLabs.Core/Text/Base64.Empty.cs index 8b0931f..53a24fa 100644 --- a/OnixLabs.Core/Text/Base64.Empty.cs +++ b/OnixLabs.Core/Text/Base64.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base64 { - public readonly partial struct Base64 - { - /// - /// Gets an empty Base-64 value. - /// - public static readonly Base64 Empty; + /// + /// Gets an empty Base-64 value. + /// + public static readonly Base64 Empty; - /// - /// Initializes static members of the class. - /// - static Base64() - { - Empty = FromByteArray(Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static Base64() + { + Empty = FromByteArray(Array.Empty()); } } diff --git a/OnixLabs.Core/Text/Base64.Equatable.cs b/OnixLabs.Core/Text/Base64.Equatable.cs index 46f26c7..a039f08 100644 --- a/OnixLabs.Core/Text/Base64.Equatable.cs +++ b/OnixLabs.Core/Text/Base64.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,59 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base64 : IEquatable { - public readonly partial struct Base64 : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Base64 a, Base64 b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Base64 a, Base64 b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Base64 a, Base64 b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Base64 a, Base64 b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Base64 other) - { - return other.Value.SequenceEqual(Value); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Base64 other) + { + return other.Value.SequenceEqual(Value); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Base64 other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Base64 other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Value.GetContentHashCode()); } } diff --git a/OnixLabs.Core/Text/Base64.From.cs b/OnixLabs.Core/Text/Base64.From.cs index 02c2ff9..f2fe891 100644 --- a/OnixLabs.Core/Text/Base64.From.cs +++ b/OnixLabs.Core/Text/Base64.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,84 +16,83 @@ using System.Linq; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base64 { - public readonly partial struct Base64 + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base64 FromByteArray(byte[] value) { - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base64 FromByteArray(byte[] value) - { - return new Base64(value); - } + return new Base64(value); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// Returns a new instance. - public static Base64 FromCharArray(char[] value) - { - return FromCharArray(value, Encoding.Default); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// Returns a new instance. + public static Base64 FromCharArray(char[] value) + { + return FromCharArray(value, Encoding.Default); + } - /// - /// Creates a instance from the specified array. - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base64 FromCharArray(char[] value, Encoding encoding) - { - byte[] bytes = encoding.GetBytes(value); - return FromByteArray(bytes); - } + /// + /// Creates a instance from the specified array. + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base64 FromCharArray(char[] value, Encoding encoding) + { + byte[] bytes = encoding.GetBytes(value); + return FromByteArray(bytes); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base64 FromSpan(ReadOnlySpan value) - { - return FromSpan(value, Encoding.Default); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base64 FromSpan(ReadOnlySpan value) + { + return FromSpan(value, Encoding.Default); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base64 FromSpan(ReadOnlySpan value, Encoding encoding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base64 FromSpan(ReadOnlySpan value, Encoding encoding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// Returns a new instance. - public static Base64 FromString(string value) - { - return FromString(value, Encoding.Default); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// Returns a new instance. + public static Base64 FromString(string value) + { + return FromString(value, Encoding.Default); + } - /// - /// Creates a instance from the specified . - /// - /// The underlying value. - /// The encoding to use to obtain the underlying value. - /// Returns a new instance. - public static Base64 FromString(string value, Encoding encoding) - { - char[] characters = value.ToArray(); - return FromCharArray(characters, encoding); - } + /// + /// Creates a instance from the specified . + /// + /// The underlying value. + /// The encoding to use to obtain the underlying value. + /// Returns a new instance. + public static Base64 FromString(string value, Encoding encoding) + { + char[] characters = value.ToArray(); + return FromCharArray(characters, encoding); } } diff --git a/OnixLabs.Core/Text/Base64.Parse.cs b/OnixLabs.Core/Text/Base64.Parse.cs index d595bbd..89292d3 100644 --- a/OnixLabs.Core/Text/Base64.Parse.cs +++ b/OnixLabs.Core/Text/Base64.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,41 +14,40 @@ using System; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base64 { - public readonly partial struct Base64 + /// + /// Parses a Base-64 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base64 Parse(string value) { - /// - /// Parses a Base-64 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base64 Parse(string value) - { - char[] characters = value.ToCharArray(); - return Parse(characters); - } + char[] characters = value.ToCharArray(); + return Parse(characters); + } - /// - /// Parses a Base-64 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base64 Parse(char[] value) - { - byte[] bytes = Convert.FromBase64CharArray(value, 0, value.Length); - return FromByteArray(bytes); - } + /// + /// Parses a Base-64 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base64 Parse(char[] value) + { + byte[] bytes = Convert.FromBase64CharArray(value, 0, value.Length); + return FromByteArray(bytes); + } - /// - /// Parses a Base-64 value into a instance. - /// - /// The Base-16 (hexadecimal) value to parse. - /// Returns a new instance. - public static Base64 Parse(ReadOnlySpan value) - { - char[] characters = value.ToArray(); - return Parse(characters); - } + /// + /// Parses a Base-64 value into a instance. + /// + /// The Base-16 (hexadecimal) value to parse. + /// Returns a new instance. + public static Base64 Parse(ReadOnlySpan value) + { + char[] characters = value.ToArray(); + return Parse(characters); } } diff --git a/OnixLabs.Core/Text/Base64.To.cs b/OnixLabs.Core/Text/Base64.To.cs index cde64e9..faea21b 100644 --- a/OnixLabs.Core/Text/Base64.To.cs +++ b/OnixLabs.Core/Text/Base64.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,45 +15,44 @@ using System; using System.Text; -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +public readonly partial struct Base64 { - public readonly partial struct Base64 + /// + /// Returns a array that represents the current object. + /// + /// Returns a array that represents the current object. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the current object. - /// - /// Returns a array that represents the current object. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// Returns a that represents the current object in plain text. - public string ToPlainTextString() - { - return ToPlainTextString(Encoding.Default); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// Returns a that represents the current object in plain text. + public string ToPlainTextString() + { + return ToPlainTextString(Encoding.Default); + } - /// - /// Returns a that represents the current object in plain text. - /// - /// The encoding to use to obtain the underlying value. - /// Returns a that represents the current object in plain text. - public string ToPlainTextString(Encoding encoding) - { - return encoding.GetString(Value); - } + /// + /// Returns a that represents the current object in plain text. + /// + /// The encoding to use to obtain the underlying value. + /// Returns a that represents the current object in plain text. + public string ToPlainTextString(Encoding encoding) + { + return encoding.GetString(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToBase64String(Value); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToBase64String(Value); } } diff --git a/OnixLabs.Core/Text/Base64.cs b/OnixLabs.Core/Text/Base64.cs index 9c99edc..0894e33 100644 --- a/OnixLabs.Core/Text/Base64.cs +++ b/OnixLabs.Core/Text/Base64.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Core.Text +namespace OnixLabs.Core.Text; + +/// +/// Represents a Base-64 value. +/// +public readonly partial struct Base64 { /// - /// Represents a Base-64 value. + /// Initializes a new instance of the struct. /// - public readonly partial struct Base64 + /// The underlying value. + private Base64(byte[] value) { - /// - /// Initializes a new instance of the struct. - /// - /// The underlying value. - private Base64(byte[] value) - { - Value = value; - } - - /// - /// Gets the underlying value. - /// - private byte[] Value { get; } + Value = value; } + + /// + /// Gets the underlying value. + /// + private byte[] Value { get; } } diff --git a/OnixLabs.Playground/OnixLabs.Playground.csproj b/OnixLabs.Playground/OnixLabs.Playground.csproj index c26e393..a5c1a76 100644 --- a/OnixLabs.Playground/OnixLabs.Playground.csproj +++ b/OnixLabs.Playground/OnixLabs.Playground.csproj @@ -2,8 +2,9 @@ Exe - net5.0 + net6.0 enable + 10 diff --git a/OnixLabs.Playground/Program.cs b/OnixLabs.Playground/Program.cs index f16bb30..c7964e3 100644 --- a/OnixLabs.Playground/Program.cs +++ b/OnixLabs.Playground/Program.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,12 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Playground +namespace OnixLabs.Playground; + +internal static class Program { - internal static class Program + private static void Main(string[] args) { - private static void Main(string[] args) - { - } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/EcdsaEncryptedPkcs8Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/EcdsaEncryptedPkcs8Tests.cs index 2c89a96..12ffbbc 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/EcdsaEncryptedPkcs8Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/EcdsaEncryptedPkcs8Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,96 +16,95 @@ using System.Security.Cryptography; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class EcdsaKeyEncryptedPkcs8Tests : KeyTestBase { - public sealed class EcdsaKeyEncryptedPkcs8Tests : KeyTestBase + [Fact(DisplayName = "Two identical ECDSA PKCS #8 private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical ECDSA PKCS #8 private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() - { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - // Act - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); - - // Assert - Assert.Equal(privateKey1, privateKey2); - } + // Act + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); - [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same data")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() - { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + // Assert + Assert.Equal(privateKey1, privateKey2); + } + [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same data")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); } - [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same hash")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); + } + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); + [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same hash")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); + } + + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) + { + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyPkcs8Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyPkcs8Tests.cs index b0b6bc2..72cb3e1 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyPkcs8Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyPkcs8Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,87 +15,86 @@ using System.Collections.Generic; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class EcdsaKeyPkcs8Tests : KeyTestBase { - public sealed class EcdsaKeyPkcs8Tests : KeyTestBase + [Fact(DisplayName = "Two identical ECDSA PKCS #8 private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical ECDSA PKCS #8 private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() - { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; - // Act - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(); - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, type); - - // Assert - Assert.Equal(privateKey1, privateKey2); - } + // Act + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(); + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, type); - [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same data")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() - { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + // Assert + Assert.Equal(privateKey1, privateKey2); + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); + [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same data")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); } - [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same hash")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); + } + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); + [Fact(DisplayName = "Two identical ECDSA PKCS #8 keys should be able to sign and verify the same hash")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = EcdsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); + } + + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) + { + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyTests.cs b/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyTests.cs index c653aa3..dfdbcea 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/EcdsaKeyTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,103 +16,102 @@ using OnixLabs.Core.Text; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class EcdsaKeyTests : KeyTestBase { - public sealed class EcdsaKeyTests : KeyTestBase + [Fact(DisplayName = "Two identical ECDSA private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical ECDSA private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() - { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; - // Act - Base58 base58PrivateKey = privateKey1.ToBase58(); - PrivateKey privateKey2 = EcdsaPrivateKey.FromBase58(base58PrivateKey, type); + // Act + Base58 base58PrivateKey = privateKey1.ToBase58(); + PrivateKey privateKey2 = EcdsaPrivateKey.FromBase58(base58PrivateKey, type); - // Assert - Assert.Equal(privateKey1, privateKey2); - } + // Assert + Assert.Equal(privateKey1, privateKey2); + } + + [Fact(DisplayName = "Two identical ECDSA public keys should be considered equal")] + public void TwoIdenticalPublicKeysShouldBeConsideredEqual() + { + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PublicKey publicKey1 = pair.PublicKey; + + // Act + Base58 base58PublicKey = publicKey1.ToBase58(); + PublicKey publicKey2 = EcdsaPublicKey.FromBase58(base58PublicKey, type); + + // Assert + Assert.Equal(publicKey1, publicKey2); + } - [Fact(DisplayName = "Two identical ECDSA public keys should be considered equal")] - public void TwoIdenticalPublicKeysShouldBeConsideredEqual() + [Fact(DisplayName = "Two identical ECDSA keys should be able to sign and verify the same data")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = EcdsaPrivateKey.FromBase64(privateKey1.ToBase64(), type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); + + // Act + for (int index = 0; index < 5; index++) { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PublicKey publicKey1 = pair.PublicKey; + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); - // Act - Base58 base58PublicKey = publicKey1.ToBase58(); - PublicKey publicKey2 = EcdsaPublicKey.FromBase58(base58PublicKey, type); + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); + } - // Assert - Assert.Equal(publicKey1, publicKey2); + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) + { + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); } + } + + [Fact(DisplayName = "Two identical ECDSA keys should be able to sign and verify the same hash")] + public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = EcdsaPrivateKey.FromBase64(privateKey1.ToBase64(), type); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - [Fact(DisplayName = "Two identical ECDSA keys should be able to sign and verify the same data")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameData() + // Act + for (int index = 0; index < 5; index++) { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = EcdsaPrivateKey.FromBase64(privateKey1.ToBase64(), type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); - - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); - - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } - - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); + + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); } - [Fact(DisplayName = "Two identical ECDSA keys should be able to sign and verify the same hash")] - public void TwoIdenticalEcdsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - KeyPair pair = KeyPair.CreateEcdsaKeyPair(type); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = EcdsaPrivateKey.FromBase64(privateKey1.ToBase64(), type); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); - - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); - - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } - - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/HashAsyncTests.cs b/OnixLabs.Security.Cryptography.UnitTests/HashAsyncTests.cs index 7a695d1..ffba6fc 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/HashAsyncTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/HashAsyncTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,30 +14,29 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class HashAsyncTests { - public sealed class HashAsyncTests + [Fact(DisplayName = "Identical hashes should be considered equal")] + public async void IdenticalHashesShouldBeConsideredEqual() { - [Fact(DisplayName = "Identical hashes should be considered equal")] - public async void IdenticalHashesShouldBeConsideredEqual() - { - // Arrange - Hash a = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); - Hash b = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); + // Arrange + Hash a = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); + Hash b = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); - // Assert - Assert.Equal(a, b); - } + // Assert + Assert.Equal(a, b); + } - [Fact(DisplayName = "Different hashes should not be considered equal")] - public async void DifferentHashesShouldNotBeConsideredEqual() - { - // Arrange - Hash a = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); - Hash b = await Hash.ComputeSha2Hash256Async("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + [Fact(DisplayName = "Different hashes should not be considered equal")] + public async void DifferentHashesShouldNotBeConsideredEqual() + { + // Arrange + Hash a = await Hash.ComputeSha2Hash256Async("abcdefghijklmnopqrstuvwxyz"); + Hash b = await Hash.ComputeSha2Hash256Async("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - // Assert - Assert.NotEqual(a, b); - } + // Assert + Assert.NotEqual(a, b); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/HashTests.cs b/OnixLabs.Security.Cryptography.UnitTests/HashTests.cs index f25bed2..240c376 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/HashTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/HashTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,74 +14,73 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class HashTests { - public sealed class HashTests + [Fact(DisplayName = "Identical Hash values produce identical hash codes.")] + public void IdenticalHashValuesProduceIdenticalHashCodes() { - [Fact(DisplayName = "Identical Hash values produce identical hash codes.")] - public void IdenticalHashValuesProduceIdenticalHashCodes() - { - // Arrange - Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - Hash b = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); + // Arrange + Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); + Hash b = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } - - [Fact(DisplayName = "Identical hashes should be considered equal")] - public void IdenticalHashesShouldBeConsideredEqual() - { - // Arrange - Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - Hash b = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); - // Assert - Assert.Equal(a, b); - } + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } - [Fact(DisplayName = "Different hashes should not be considered equal")] - public void DifferentHashesShouldNotBeConsideredEqual() - { - // Arrange - Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - Hash b = Hash.ComputeSha2Hash256("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + [Fact(DisplayName = "Identical hashes should be considered equal")] + public void IdenticalHashesShouldBeConsideredEqual() + { + // Arrange + Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); + Hash b = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); - // Assert - Assert.NotEqual(a, b); - } + // Assert + Assert.Equal(a, b); + } - [Fact(DisplayName = "Parse should be able to parse a known hash")] - public void ParseShouldBeAbleToParseAKnownHash() - { - // Arrange - const string expected = "Sha2Hash256:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; + [Fact(DisplayName = "Different hashes should not be considered equal")] + public void DifferentHashesShouldNotBeConsideredEqual() + { + // Arrange + Hash a = Hash.ComputeSha2Hash256("abcdefghijklmnopqrstuvwxyz"); + Hash b = Hash.ComputeSha2Hash256("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - // Act - Hash hash = Hash.Parse(expected); - string actual = hash.ToStringWithAlgorithmType(); + // Assert + Assert.NotEqual(a, b); + } - // Assert - Assert.Equal(expected, actual); - } + [Fact(DisplayName = "Parse should be able to parse a known hash")] + public void ParseShouldBeAbleToParseAKnownHash() + { + // Arrange + const string expected = "Sha2Hash256:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; + + // Act + Hash hash = Hash.Parse(expected); + string actual = hash.ToStringWithAlgorithmType(); - [Fact(DisplayName = "Parse should be able to parse an unknown hash")] - public void ParseShouldBeAbleToParseAnUnknownHash() - { - // Arrange - const string value = "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; - const string expected = "Unknown:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; + // Assert + Assert.Equal(expected, actual); + } + + [Fact(DisplayName = "Parse should be able to parse an unknown hash")] + public void ParseShouldBeAbleToParseAnUnknownHash() + { + // Arrange + const string value = "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; + const string expected = "Unknown:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"; - // Act - Hash hash = Hash.Parse(value); - string actual = hash.ToStringWithAlgorithmType(); + // Act + Hash hash = Hash.Parse(value); + string actual = hash.ToStringWithAlgorithmType(); - // Assert - Assert.Equal(expected, actual); - } + // Assert + Assert.Equal(expected, actual); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/HmacAsyncTests.cs b/OnixLabs.Security.Cryptography.UnitTests/HmacAsyncTests.cs index cfcac70..12d7382 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/HmacAsyncTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/HmacAsyncTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,41 +14,40 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class HmacAsyncTests { - public sealed class HmacAsyncTests + [Fact(DisplayName = "Identical HMACs should be considered equal")] + public async void IdenticalHashesShouldBeConsideredEqual() + { + // Arrange + Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); + + // Assert + Assert.Equal(a, b); + } + + [Fact(DisplayName = "Different HMACs should not be considered equal (different data)")] + public async void DifferentHashesShouldNotBeConsideredEqualWithDifferentData() { - [Fact(DisplayName = "Identical HMACs should be considered equal")] - public async void IdenticalHashesShouldBeConsideredEqual() - { - // Arrange - Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); - - // Assert - Assert.Equal(a, b); - } - - [Fact(DisplayName = "Different HMACs should not be considered equal (different data)")] - public async void DifferentHashesShouldNotBeConsideredEqualWithDifferentData() - { - // Arrange - Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = await Hmac.ComputeSha2Hmac256Async("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "key"); - - // Assert - Assert.NotEqual(a, b); - } - - [Fact(DisplayName = "Different HMACs should not be considered equal (different keys)")] - public async void DifferentHashesShouldNotBeConsideredEqualWithDifferentKeys() - { - // Arrange - Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "123"); - - // Assert - Assert.NotEqual(a, b); - } + // Arrange + Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = await Hmac.ComputeSha2Hmac256Async("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "key"); + + // Assert + Assert.NotEqual(a, b); + } + + [Fact(DisplayName = "Different HMACs should not be considered equal (different keys)")] + public async void DifferentHashesShouldNotBeConsideredEqualWithDifferentKeys() + { + // Arrange + Hmac a = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = await Hmac.ComputeSha2Hmac256Async("abcdefghijklmnopqrstuvwxyz", "123"); + + // Assert + Assert.NotEqual(a, b); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/HmacTests.cs b/OnixLabs.Security.Cryptography.UnitTests/HmacTests.cs index 852b8ca..eea32c7 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/HmacTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/HmacTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,71 +14,70 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class HmacTests { - public sealed class HmacTests + [Fact(DisplayName = "Identical Hmac values produce identical hash codes.")] + public void IdenticalHmacValuesProduceIdenticalHashCodes() { - [Fact(DisplayName = "Identical Hmac values produce identical hash codes.")] - public void IdenticalHmacValuesProduceIdenticalHashCodes() - { - // Arrange - Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + // Arrange + Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - // Act - int hashCodeA = a.GetHashCode(); - int hashCodeB = b.GetHashCode(); + // Act + int hashCodeA = a.GetHashCode(); + int hashCodeB = b.GetHashCode(); - // Assert - Assert.Equal(hashCodeA, hashCodeB); - } + // Assert + Assert.Equal(hashCodeA, hashCodeB); + } - [Fact(DisplayName = "Identical HMACs should be considered equal")] - public void IdenticalHashesShouldBeConsideredEqual() - { - // Arrange - Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + [Fact(DisplayName = "Identical HMACs should be considered equal")] + public void IdenticalHashesShouldBeConsideredEqual() + { + // Arrange + Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - // Assert - Assert.Equal(a, b); - } + // Assert + Assert.Equal(a, b); + } - [Fact(DisplayName = "Different HMACs should not be considered equal (different data)")] - public void DifferentHashesShouldNotBeConsideredEqualWithDifferentData() - { - // Arrange - Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = Hmac.ComputeSha2Hmac256("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "key"); + [Fact(DisplayName = "Different HMACs should not be considered equal (different data)")] + public void DifferentHashesShouldNotBeConsideredEqualWithDifferentData() + { + // Arrange + Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = Hmac.ComputeSha2Hmac256("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "key"); - // Assert - Assert.NotEqual(a, b); - } + // Assert + Assert.NotEqual(a, b); + } - [Fact(DisplayName = "Different HMACs should not be considered equal (different keys)")] - public void DifferentHashesShouldNotBeConsideredEqualWithDifferentKeys() - { - // Arrange - Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); - Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "123"); + [Fact(DisplayName = "Different HMACs should not be considered equal (different keys)")] + public void DifferentHashesShouldNotBeConsideredEqualWithDifferentKeys() + { + // Arrange + Hmac a = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "key"); + Hmac b = Hmac.ComputeSha2Hmac256("abcdefghijklmnopqrstuvwxyz", "123"); - // Assert - Assert.NotEqual(a, b); - } + // Assert + Assert.NotEqual(a, b); + } - [Fact(DisplayName = "Parse should be able to parse a known hash")] - public void ParseShouldBeAbleToParseAKnownHash() - { - // Arrange - const string expected = - "Sha2Hmac256:73ac6fa8599f4bde8dfee594c7f5f6ff03023b2d99ca71a7eccf729a8fc5c324:48656c6c6f2c20576f726c6421"; + [Fact(DisplayName = "Parse should be able to parse a known hash")] + public void ParseShouldBeAbleToParseAKnownHash() + { + // Arrange + const string expected = + "Sha2Hmac256:73ac6fa8599f4bde8dfee594c7f5f6ff03023b2d99ca71a7eccf729a8fc5c324:48656c6c6f2c20576f726c6421"; - // Act - Hmac hash = Hmac.Parse(expected); - string actual = hash.ToStringWithAlgorithmType(); + // Act + Hmac hash = Hmac.Parse(expected); + string actual = hash.ToStringWithAlgorithmType(); - // Assert - Assert.Equal(expected, actual); - } + // Assert + Assert.Equal(expected, actual); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/KeyTestBase.cs b/OnixLabs.Security.Cryptography.UnitTests/KeyTestBase.cs index 3617250..095071b 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/KeyTestBase.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/KeyTestBase.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,18 +14,17 @@ using System; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public abstract class KeyTestBase { - public abstract class KeyTestBase + protected static byte[] GenerateRandomData(int length = 1024) { - protected static byte[] GenerateRandomData(int length = 1024) - { - byte[] result = new byte[length]; - Random random = new(Guid.NewGuid().GetHashCode()); + byte[] result = new byte[length]; + Random random = new(Guid.NewGuid().GetHashCode()); - random.NextBytes(result); + random.NextBytes(result); - return result; - } + return result; } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/MerkleTreeTests.cs b/OnixLabs.Security.Cryptography.UnitTests/MerkleTreeTests.cs index 4711e28..524645d 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/MerkleTreeTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/MerkleTreeTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,47 +16,46 @@ using System.Linq; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class MerkleTreeTests { - public sealed class MerkleTreeTests + [Fact(DisplayName = "Identical Merkle trees should be considered equal")] + public void IdenticalMerkleTreesShouldBeConsideredEqual() + { + // Arrange + List hashes = Enumerable + .Range(1, 937) + .Select(i => Hash.ComputeSha2Hash256(i.ToString())) + .ToList(); + + // Act + MerkleTree a = MerkleTree.Build(hashes); + MerkleTree b = MerkleTree.Build(hashes); + + // Assert + Assert.Equal(a, b); + } + + [Fact(DisplayName = "Different Merkle trees should not be considered equal")] + public void DifferentMerkleTreesShouldNotBeConsideredEqual() { - [Fact(DisplayName = "Identical Merkle trees should be considered equal")] - public void IdenticalMerkleTreesShouldBeConsideredEqual() - { - // Arrange - List hashes = Enumerable - .Range(1, 937) - .Select(i => Hash.ComputeSha2Hash256(i.ToString())) - .ToList(); - - // Act - MerkleTree a = MerkleTree.Build(hashes); - MerkleTree b = MerkleTree.Build(hashes); - - // Assert - Assert.Equal(a, b); - } - - [Fact(DisplayName = "Different Merkle trees should not be considered equal")] - public void DifferentMerkleTreesShouldNotBeConsideredEqual() - { - // Arrange - List hashesForMerkleTreeA = Enumerable - .Range(1, 937) - .Select(i => Hash.ComputeSha2Hash256($"A{i}")) - .ToList(); - - List hashesForMerkleTreeB = Enumerable - .Range(1, 677) - .Select(i => Hash.ComputeSha2Hash256($"B{i}")) - .ToList(); - - // Act - MerkleTree a = MerkleTree.Build(hashesForMerkleTreeA); - MerkleTree b = MerkleTree.Build(hashesForMerkleTreeB); - - // Assert - Assert.NotEqual(a, b); - } + // Arrange + List hashesForMerkleTreeA = Enumerable + .Range(1, 937) + .Select(i => Hash.ComputeSha2Hash256($"A{i}")) + .ToList(); + + List hashesForMerkleTreeB = Enumerable + .Range(1, 677) + .Select(i => Hash.ComputeSha2Hash256($"B{i}")) + .ToList(); + + // Act + MerkleTree a = MerkleTree.Build(hashesForMerkleTreeA); + MerkleTree b = MerkleTree.Build(hashesForMerkleTreeB); + + // Assert + Assert.NotEqual(a, b); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/OnixLabs.Security.Cryptography.UnitTests.csproj b/OnixLabs.Security.Cryptography.UnitTests/OnixLabs.Security.Cryptography.UnitTests.csproj index 8ac109e..76b5a6a 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/OnixLabs.Security.Cryptography.UnitTests.csproj +++ b/OnixLabs.Security.Cryptography.UnitTests/OnixLabs.Security.Cryptography.UnitTests.csproj @@ -1,9 +1,11 @@ - net5.0 + net6.0 false + + 10 diff --git a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyEncryptedPkcs8Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyEncryptedPkcs8Tests.cs index 80ac269..4d30fff 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyEncryptedPkcs8Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyEncryptedPkcs8Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,98 +16,97 @@ using System.Security.Cryptography; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class RsaKeyEncryptedPkcs8Tests : KeyTestBase { - public sealed class RsaKeyEncryptedPkcs8Tests : KeyTestBase + [Fact(DisplayName = "Two identical RSA PKCS #8 private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical RSA PKCS #8 private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() - { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - // Act - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); - - // Assert - Assert.Equal(privateKey1, privateKey2); - } + // Act + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); - [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same data")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() - { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + // Assert + Assert.Equal(privateKey1, privateKey2); + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); + [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same data")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); } - [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same hash")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - const string password = "This is a secret!"; - PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); + } + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); + [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same hash")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + const string password = "This is a secret!"; + PbeParameters parameters = new(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 64); + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(password, parameters); + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, password, type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); + } + + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) + { + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyPkcs8Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyPkcs8Tests.cs index 79a4e9c..7e9088a 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyPkcs8Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyPkcs8Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,90 +16,89 @@ using System.Security.Cryptography; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class RsaKeyPkcs8Tests : KeyTestBase { - public sealed class RsaKeyPkcs8Tests : KeyTestBase + [Fact(DisplayName = "Two identical RSA PKCS #8 private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical RSA PKCS #8 private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() - { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; - // Act - byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(); - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, type, padding); - - // Assert - Assert.Equal(privateKey1, privateKey2); - } + // Act + byte[] pkcs8PrivateKey = privateKey1.ExportPkcs8Key(); + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(pkcs8PrivateKey, type, padding); - [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same data")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() - { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + // Assert + Assert.Equal(privateKey1, privateKey2); + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); + [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same data")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); } - [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same hash")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); + } + } - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); + [Fact(DisplayName = "Two identical RSA PKCS #8 keys should be able to sign and verify the same hash")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = RsaPrivateKey.ImportPkcs8Key(privateKey1.ExportPkcs8Key(), type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } + // Act + for (int index = 0; index < 5; index++) + { + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); + } + + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) + { + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyTests.cs b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyTests.cs index ba76154..91b4d64 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/RsaKeyTests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/RsaKeyTests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,107 +17,106 @@ using OnixLabs.Core.Text; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class RsaKeyTests : KeyTestBase { - public sealed class RsaKeyTests : KeyTestBase + [Fact(DisplayName = "Two identical RSA private keys should be considered equal")] + public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() { - [Fact(DisplayName = "Two identical RSA private keys should be considered equal")] - public void TwoIdenticalPrivateKeysShouldBeConsideredEqual() + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + + // Act + Base58 base58PrivateKey = privateKey1.ToBase58(); + PrivateKey privateKey2 = RsaPrivateKey.FromBase58(base58PrivateKey, type, padding); + + // Assert + Assert.Equal(privateKey1, privateKey2); + } + + [Fact(DisplayName = "Two identical RSA public keys should be considered equal")] + public void TwoIdenticalPublicKeysShouldBeConsideredEqual() + { + // Arrange + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PublicKey publicKey1 = pair.PublicKey; + + // Act + Base58 base58PublicKey = publicKey1.ToBase58(); + PublicKey publicKey2 = RsaPublicKey.FromBase58(base58PublicKey, type, padding); + + // Assert + Assert.Equal(publicKey1, publicKey2); + } + + [Fact(DisplayName = "Two identical RSA keys should be able to sign and verify the same data")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() + { + // Arrange + IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = RsaPrivateKey.FromBase64(privateKey1.ToBase64(), type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); + + // Act + for (int index = 0; index < 5; index++) { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - - // Act - Base58 base58PrivateKey = privateKey1.ToBase58(); - PrivateKey privateKey2 = RsaPrivateKey.FromBase58(base58PrivateKey, type, padding); - - // Assert - Assert.Equal(privateKey1, privateKey2); + byte[] data = GenerateRandomData(); + DigitalSignature signature1 = privateKey1.SignData(data); + DigitalSignature signature2 = privateKey2.SignData(data); + + signatures.Add((signature1, data)); + signatures.Add((signature2, data)); } - [Fact(DisplayName = "Two identical RSA public keys should be considered equal")] - public void TwoIdenticalPublicKeysShouldBeConsideredEqual() + // Assert + foreach ((DigitalSignature signature, byte[] data) in signatures) { - // Arrange - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PublicKey publicKey1 = pair.PublicKey; - - // Act - Base58 base58PublicKey = publicKey1.ToBase58(); - PublicKey publicKey2 = RsaPublicKey.FromBase58(base58PublicKey, type, padding); - - // Assert - Assert.Equal(publicKey1, publicKey2); + Assert.True(signature.IsDataValid(data, publicKey1)); + Assert.True(signature.IsDataValid(data, publicKey2)); } + } + + [Fact(DisplayName = "Two identical RSA keys should be able to sign and verify the same hash")] + public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + { + // Arrange + IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); + HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; + RSASignaturePadding padding = RSASignaturePadding.Pss; + KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); + PrivateKey privateKey1 = pair.PrivateKey; + PrivateKey privateKey2 = RsaPrivateKey.FromBase64(privateKey1.ToBase64(), type, padding); + PublicKey publicKey1 = pair.PublicKey; + PublicKey publicKey2 = privateKey1.GetPublicKey(); - [Fact(DisplayName = "Two identical RSA keys should be able to sign and verify the same data")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameData() + // Act + for (int index = 0; index < 5; index++) { - // Arrange - IList<(DigitalSignature, byte[])> signatures = new List<(DigitalSignature, byte[])>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = RsaPrivateKey.FromBase64(privateKey1.ToBase64(), type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); - - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - DigitalSignature signature1 = privateKey1.SignData(data); - DigitalSignature signature2 = privateKey2.SignData(data); - - signatures.Add((signature1, data)); - signatures.Add((signature2, data)); - } - - // Assert - foreach ((DigitalSignature signature, byte[] data) in signatures) - { - Assert.True(signature.IsDataValid(data, publicKey1)); - Assert.True(signature.IsDataValid(data, publicKey2)); - } + byte[] data = GenerateRandomData(); + Hash hashedData = Hash.ComputeSha2Hash256(data); + DigitalSignature signature1 = privateKey1.SignHash(hashedData); + DigitalSignature signature2 = privateKey2.SignHash(hashedData); + + signatures.Add((signature1, hashedData)); + signatures.Add((signature2, hashedData)); } - [Fact(DisplayName = "Two identical RSA keys should be able to sign and verify the same hash")] - public void TwoIdenticalRsaKeysShouldBeAbleToSignAndVerifyTheSameHash() + // Assert + foreach ((DigitalSignature signature, Hash hashedData) in signatures) { - // Arrange - IList<(DigitalSignature, Hash)> signatures = new List<(DigitalSignature, Hash)>(); - HashAlgorithmType type = HashAlgorithmType.Sha2Hash256; - RSASignaturePadding padding = RSASignaturePadding.Pss; - KeyPair pair = KeyPair.CreateRsaKeyPair(type, padding); - PrivateKey privateKey1 = pair.PrivateKey; - PrivateKey privateKey2 = RsaPrivateKey.FromBase64(privateKey1.ToBase64(), type, padding); - PublicKey publicKey1 = pair.PublicKey; - PublicKey publicKey2 = privateKey1.GetPublicKey(); - - // Act - for (int index = 0; index < 5; index++) - { - byte[] data = GenerateRandomData(); - Hash hashedData = Hash.ComputeSha2Hash256(data); - DigitalSignature signature1 = privateKey1.SignHash(hashedData); - DigitalSignature signature2 = privateKey2.SignHash(hashedData); - - signatures.Add((signature1, hashedData)); - signatures.Add((signature2, hashedData)); - } - - // Assert - foreach ((DigitalSignature signature, Hash hashedData) in signatures) - { - Assert.True(signature.IsHashValid(hashedData, publicKey1)); - Assert.True(signature.IsHashValid(hashedData, publicKey2)); - } + Assert.True(signature.IsHashValid(hashedData, publicKey1)); + Assert.True(signature.IsHashValid(hashedData, publicKey2)); } } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash224Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash224Tests.cs index 1025b47..1de9700 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash224Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash224Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,27 +14,26 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3Hash224Tests : Sha3HashTestBase { - public sealed class Sha3Hash224Tests : Sha3HashTestBase - { - protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash224(); + protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash224(); - [Theory(DisplayName = "Sha3Managed224 should produce the expected hash for the specified string literal")] - [InlineData("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", "")] - [InlineData("9877af03f5e1919851d0ef4ce6b23f1e85a40b446d93713f4c6e6dcd", "1234567890")] - [InlineData("beae76edd99d4ad4d398d51c5ea1d8b7b3fa6d49d687b0cb1ec2ec41", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("5cdeca81e123f87cad96b9cba999f16f6d41549608d4e0f4681b8239", "abcdefghijklmnopqrstuvwxyz")] - public override void TestSha3WithLiteralString(string expected, string literal) - { - base.TestSha3WithLiteralString(expected, literal); - } + [Theory(DisplayName = "Sha3Managed224 should produce the expected hash for the specified string literal")] + [InlineData("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", "")] + [InlineData("9877af03f5e1919851d0ef4ce6b23f1e85a40b446d93713f4c6e6dcd", "1234567890")] + [InlineData("beae76edd99d4ad4d398d51c5ea1d8b7b3fa6d49d687b0cb1ec2ec41", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("5cdeca81e123f87cad96b9cba999f16f6d41549608d4e0f4681b8239", "abcdefghijklmnopqrstuvwxyz")] + public override void TestSha3WithLiteralString(string expected, string literal) + { + base.TestSha3WithLiteralString(expected, literal); + } - [Theory(DisplayName = "Sha3Managed224 should produce the expected hash for the specified string template")] - [InlineData("d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c", "a", 1_000_000)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations) - { - base.TestSha3WithGeneratedString(expected, template, iterations); - } + [Theory(DisplayName = "Sha3Managed224 should produce the expected hash for the specified string template")] + [InlineData("d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c", "a", 1_000_000)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations) + { + base.TestSha3WithGeneratedString(expected, template, iterations); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash256Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash256Tests.cs index 84b983c..e355c65 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash256Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash256Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,27 +14,26 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3Hash256Tests : Sha3HashTestBase { - public sealed class Sha3Hash256Tests : Sha3HashTestBase - { - protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash256(); + protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash256(); - [Theory(DisplayName = "Sha3Managed256 should produce the expected hash for the specified string literal")] - [InlineData("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", "")] - [InlineData("01da8843e976913aa5c15a62d45f1c9267391dcbd0a76ad411919043f374a163", "1234567890")] - [InlineData("738eeb2d4adf0d452456695011bb252bd4701a0ae78fdd3fc945a963bceb1702", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData("7cab2dc765e21b241dbc1c255ce620b29f527c6d5e7f5f843e56288f0d707521", "abcdefghijklmnopqrstuvwxyz")] - public override void TestSha3WithLiteralString(string expected, string literal) - { - base.TestSha3WithLiteralString(expected, literal); - } + [Theory(DisplayName = "Sha3Managed256 should produce the expected hash for the specified string literal")] + [InlineData("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", "")] + [InlineData("01da8843e976913aa5c15a62d45f1c9267391dcbd0a76ad411919043f374a163", "1234567890")] + [InlineData("738eeb2d4adf0d452456695011bb252bd4701a0ae78fdd3fc945a963bceb1702", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData("7cab2dc765e21b241dbc1c255ce620b29f527c6d5e7f5f843e56288f0d707521", "abcdefghijklmnopqrstuvwxyz")] + public override void TestSha3WithLiteralString(string expected, string literal) + { + base.TestSha3WithLiteralString(expected, literal); + } - [Theory(DisplayName = "Sha3Managed256 should produce a valid hash result for the given string template")] - [InlineData("5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1", "a", 1_000_000)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations) - { - base.TestSha3WithGeneratedString(expected, template, iterations); - } + [Theory(DisplayName = "Sha3Managed256 should produce a valid hash result for the given string template")] + [InlineData("5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1", "a", 1_000_000)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations) + { + base.TestSha3WithGeneratedString(expected, template, iterations); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash384Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash384Tests.cs index a5d9ca3..5124b0f 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash384Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash384Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3Managed384Tests : Sha3HashTestBase { - public sealed class Sha3Managed384Tests : Sha3HashTestBase - { - protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash384(); + protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash384(); - [Theory(DisplayName = "Sha3Managed384 should produce the expected hash for the specified string literal")] - [InlineData( - "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004", - "" - )] - [InlineData( - "6fdddab7d670f202629531c1a51b32ca30696d0af4dd5b0fbb5f82c0aba5e505110455f37d7ef73950c2bb0495a38f56", - "1234567890" - )] - [InlineData( - "284da0df47fc9e75a4ef1248f69ca0d12a5d44508942e63b03b8c227510c2e1b43400009fcd36c0acc941679e5024a04", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - )] - [InlineData( - "fed399d2217aaf4c717ad0c5102c15589e1c990cc2b9a5029056a7f7485888d6ab65db2370077a5cadb53fc9280d278f", - "abcdefghijklmnopqrstuvwxyz" - )] - public override void TestSha3WithLiteralString(string expected, string literal) - { - base.TestSha3WithLiteralString(expected, literal); - } + [Theory(DisplayName = "Sha3Managed384 should produce the expected hash for the specified string literal")] + [InlineData( + "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004", + "" + )] + [InlineData( + "6fdddab7d670f202629531c1a51b32ca30696d0af4dd5b0fbb5f82c0aba5e505110455f37d7ef73950c2bb0495a38f56", + "1234567890" + )] + [InlineData( + "284da0df47fc9e75a4ef1248f69ca0d12a5d44508942e63b03b8c227510c2e1b43400009fcd36c0acc941679e5024a04", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + )] + [InlineData( + "fed399d2217aaf4c717ad0c5102c15589e1c990cc2b9a5029056a7f7485888d6ab65db2370077a5cadb53fc9280d278f", + "abcdefghijklmnopqrstuvwxyz" + )] + public override void TestSha3WithLiteralString(string expected, string literal) + { + base.TestSha3WithLiteralString(expected, literal); + } - [Theory(DisplayName = "Sha3Managed384 should produce a valid hash result for the given string template")] - [InlineData("eee9e24d78c1855337983451df97c8ad9eedf256c6334f8e948d252d5e0e76847aa0774ddb90a842190d2c558b4b8340", - "a", 1_000_000)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations) - { - base.TestSha3WithGeneratedString(expected, template, iterations); - } + [Theory(DisplayName = "Sha3Managed384 should produce a valid hash result for the given string template")] + [InlineData("eee9e24d78c1855337983451df97c8ad9eedf256c6334f8e948d252d5e0e76847aa0774ddb90a842190d2c558b4b8340", + "a", 1_000_000)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations) + { + base.TestSha3WithGeneratedString(expected, template, iterations); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash512Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash512Tests.cs index e5c7ba3..3160f2e 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash512Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Hash512Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,37 +14,36 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3Managed512Tests : Sha3HashTestBase { - public sealed class Sha3Managed512Tests : Sha3HashTestBase - { - protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash512(); + protected override Sha3 HashAlgorithm => Sha3.CreateSha3Hash512(); - [Theory(DisplayName = "Sha3Managed512 should produce the expected hash for the specified message")] - [InlineData( - "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26", - "")] - [InlineData( - "36dde7d288a2166a651d51ec6ded9e70e72cf6b366293d6f513c75393c57d6f33b949879b9d5e7f7c21cd8c02ede75e74fc54ea15bd043b4df008533fc68ae69", - "1234567890")] - [InlineData( - "69958b041bc72e9922e02cd4250953ee69d5f6e69f97d8def72b34effc0aea2bf5cfe03bd4ada0e271060593395656c1bf9eb68d1fc4cf146f90601152222df7", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] - [InlineData( - "af328d17fa28753a3c9f5cb72e376b90440b96f0289e5703b729324a975ab384eda565fc92aaded143669900d761861687acdc0a5ffa358bd0571aaad80aca68", - "abcdefghijklmnopqrstuvwxyz")] - public override void TestSha3WithLiteralString(string expected, string literal) - { - base.TestSha3WithLiteralString(expected, literal); - } + [Theory(DisplayName = "Sha3Managed512 should produce the expected hash for the specified message")] + [InlineData( + "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26", + "")] + [InlineData( + "36dde7d288a2166a651d51ec6ded9e70e72cf6b366293d6f513c75393c57d6f33b949879b9d5e7f7c21cd8c02ede75e74fc54ea15bd043b4df008533fc68ae69", + "1234567890")] + [InlineData( + "69958b041bc72e9922e02cd4250953ee69d5f6e69f97d8def72b34effc0aea2bf5cfe03bd4ada0e271060593395656c1bf9eb68d1fc4cf146f90601152222df7", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + [InlineData( + "af328d17fa28753a3c9f5cb72e376b90440b96f0289e5703b729324a975ab384eda565fc92aaded143669900d761861687acdc0a5ffa358bd0571aaad80aca68", + "abcdefghijklmnopqrstuvwxyz")] + public override void TestSha3WithLiteralString(string expected, string literal) + { + base.TestSha3WithLiteralString(expected, literal); + } - [Theory(DisplayName = "Sha3Managed512 should produce the expected hash for the specified string template")] - [InlineData( - "3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87", - "a", 1_000_000)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations) - { - base.TestSha3WithGeneratedString(expected, template, iterations); - } + [Theory(DisplayName = "Sha3Managed512 should produce the expected hash for the specified string template")] + [InlineData( + "3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87", + "a", 1_000_000)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations) + { + base.TestSha3WithGeneratedString(expected, template, iterations); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3HashTestBase.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3HashTestBase.cs index 83fe8f3..75c363b 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3HashTestBase.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3HashTestBase.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,29 +17,28 @@ using System.Text; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public abstract class Sha3HashTestBase { - public abstract class Sha3HashTestBase - { - protected abstract Sha3 HashAlgorithm { get; } + protected abstract Sha3 HashAlgorithm { get; } - public virtual void TestSha3WithLiteralString(string expected, string literal) - { - string actual = ComputeHash(HashAlgorithm, literal); - Assert.Equal(expected, actual); - } + public virtual void TestSha3WithLiteralString(string expected, string literal) + { + string actual = ComputeHash(HashAlgorithm, literal); + Assert.Equal(expected, actual); + } - public virtual void TestSha3WithGeneratedString(string expected, string template, int iterations) - { - string actual = ComputeHash(HashAlgorithm, string.Concat(Enumerable.Repeat(template, iterations))); - Assert.Equal(expected, actual); - } + public virtual void TestSha3WithGeneratedString(string expected, string template, int iterations) + { + string actual = ComputeHash(HashAlgorithm, string.Concat(Enumerable.Repeat(template, iterations))); + Assert.Equal(expected, actual); + } - private static string ComputeHash(HashAlgorithm algorithm, string plainText) - { - byte[] plainTextBytes = Encoding.Default.GetBytes(plainText); - byte[] hashedBytes = algorithm.ComputeHash(plainTextBytes); - return Hash.FromByteArray(hashedBytes).ToString(); - } + private static string ComputeHash(HashAlgorithm algorithm, string plainText) + { + byte[] plainTextBytes = Encoding.Default.GetBytes(plainText); + byte[] hashedBytes = algorithm.ComputeHash(plainTextBytes); + return Hash.FromByteArray(hashedBytes).ToString(); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake128Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake128Tests.cs index b8c253f..2849e64 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake128Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake128Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,42 +14,41 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3ManagedShake128Tests : Sha3ShakeTestBase { - public sealed class Sha3ManagedShake128Tests : Sha3ShakeTestBase + [Theory(DisplayName = "Sha3ManagedShake128 should produce the expected hash for the specified string literal")] + [InlineData("7f9c2ba4", "", 4)] + [InlineData("7f9c2ba4e88f827d", "", 8)] + [InlineData("7f9c2ba4e88f827d616045507605853e", "", 16)] + [InlineData("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26", "", 32)] + [InlineData("1cd2c71a", "1234567890", 4)] + [InlineData("1cd2c71a52e3f2a6", "1234567890", 8)] + [InlineData("1cd2c71a52e3f2a620173e915f17648d", "1234567890", 16)] + [InlineData("1cd2c71a52e3f2a620173e915f17648dcc43443ef78754302c6b44cf47daf527", "1234567890", 32)] + [InlineData("5b3b6a58", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)] + [InlineData("5b3b6a587417f8fa", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)] + [InlineData("5b3b6a587417f8fa192aba21c16b7b7a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 16)] + [InlineData("5b3b6a587417f8fa192aba21c16b7b7a6375aac5f04e950f", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 24)] + [InlineData("961c919c", "abcdefghijklmnopqrstuvwxyz", 4)] + [InlineData("961c919c0854576e", "abcdefghijklmnopqrstuvwxyz", 8)] + [InlineData("961c919c0854576e561320e81514bf37", "abcdefghijklmnopqrstuvwxyz", 16)] + [InlineData("961c919c0854576e561320e81514bf3724197d0715e16a36", "abcdefghijklmnopqrstuvwxyz", 24)] + public override void TestSha3WithLiteralString(string expected, string literal, int length) { - [Theory(DisplayName = "Sha3ManagedShake128 should produce the expected hash for the specified string literal")] - [InlineData("7f9c2ba4", "", 4)] - [InlineData("7f9c2ba4e88f827d", "", 8)] - [InlineData("7f9c2ba4e88f827d616045507605853e", "", 16)] - [InlineData("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26", "", 32)] - [InlineData("1cd2c71a", "1234567890", 4)] - [InlineData("1cd2c71a52e3f2a6", "1234567890", 8)] - [InlineData("1cd2c71a52e3f2a620173e915f17648d", "1234567890", 16)] - [InlineData("1cd2c71a52e3f2a620173e915f17648dcc43443ef78754302c6b44cf47daf527", "1234567890", 32)] - [InlineData("5b3b6a58", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)] - [InlineData("5b3b6a587417f8fa", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)] - [InlineData("5b3b6a587417f8fa192aba21c16b7b7a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 16)] - [InlineData("5b3b6a587417f8fa192aba21c16b7b7a6375aac5f04e950f", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 24)] - [InlineData("961c919c", "abcdefghijklmnopqrstuvwxyz", 4)] - [InlineData("961c919c0854576e", "abcdefghijklmnopqrstuvwxyz", 8)] - [InlineData("961c919c0854576e561320e81514bf37", "abcdefghijklmnopqrstuvwxyz", 16)] - [InlineData("961c919c0854576e561320e81514bf3724197d0715e16a36", "abcdefghijklmnopqrstuvwxyz", 24)] - public override void TestSha3WithLiteralString(string expected, string literal, int length) - { - HashAlgorithm = Sha3.CreateSha3Shake128(length); - base.TestSha3WithLiteralString(expected, literal, length); - } + HashAlgorithm = Sha3.CreateSha3Shake128(length); + base.TestSha3WithLiteralString(expected, literal, length); + } - [Theory(DisplayName = "Sha3ManagedShake128 should produce the expected hash for the specified string template")] - [InlineData("9d222c79", "a", 1_000_000, 4)] - [InlineData("9d222c79c4ff9d09", "a", 1_000_000, 8)] - [InlineData("9d222c79c4ff9d092cf6ca86143aa411", "a", 1_000_000, 16)] - [InlineData("9d222c79c4ff9d092cf6ca86143aa411e369973808ef97093255826c5572ef58", "a", 1_000_000, 32)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) - { - HashAlgorithm = Sha3.CreateSha3Shake128(length); - base.TestSha3WithGeneratedString(expected, template, iterations, length); - } + [Theory(DisplayName = "Sha3ManagedShake128 should produce the expected hash for the specified string template")] + [InlineData("9d222c79", "a", 1_000_000, 4)] + [InlineData("9d222c79c4ff9d09", "a", 1_000_000, 8)] + [InlineData("9d222c79c4ff9d092cf6ca86143aa411", "a", 1_000_000, 16)] + [InlineData("9d222c79c4ff9d092cf6ca86143aa411e369973808ef97093255826c5572ef58", "a", 1_000_000, 32)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) + { + HashAlgorithm = Sha3.CreateSha3Shake128(length); + base.TestSha3WithGeneratedString(expected, template, iterations, length); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake256Tests.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake256Tests.cs index bf8679b..d36885c 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake256Tests.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3Shake256Tests.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,42 +14,41 @@ using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public sealed class Sha3ManagedShake256Tests : Sha3ShakeTestBase { - public sealed class Sha3ManagedShake256Tests : Sha3ShakeTestBase + [Theory(DisplayName = "Sha3ManagedShake256 should produce the expected hash for the specified string literal")] + [InlineData("46b9dd2b", "", 4)] + [InlineData("46b9dd2b0ba88d13", "", 8)] + [InlineData("46b9dd2b0ba88d13233b3feb743eeb24", "", 16)] + [InlineData("46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f", "", 32)] + [InlineData("cd65a4e5", "1234567890", 4)] + [InlineData("cd65a4e553405b50", "1234567890", 8)] + [InlineData("cd65a4e553405b50c2f37001ea81905f", "1234567890", 16)] + [InlineData("cd65a4e553405b50c2f37001ea81905f36d650cc775fdad898b2e343644cb3db", "1234567890", 32)] + [InlineData("fa8775b6", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)] + [InlineData("fa8775b64bf3aaf1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)] + [InlineData("fa8775b64bf3aaf10d7f473c460f4d23", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 16)] + [InlineData("fa8775b64bf3aaf10d7f473c460f4d2361f56ff34ae7267a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 24)] + [InlineData("b7b78b04", "abcdefghijklmnopqrstuvwxyz", 4)] + [InlineData("b7b78b04a3dd30a2", "abcdefghijklmnopqrstuvwxyz", 8)] + [InlineData("b7b78b04a3dd30a265c8886c33fda947", "abcdefghijklmnopqrstuvwxyz", 16)] + [InlineData("b7b78b04a3dd30a265c8886c33fda94799853de5d3d10541", "abcdefghijklmnopqrstuvwxyz", 24)] + public override void TestSha3WithLiteralString(string expected, string literal, int length) { - [Theory(DisplayName = "Sha3ManagedShake256 should produce the expected hash for the specified string literal")] - [InlineData("46b9dd2b", "", 4)] - [InlineData("46b9dd2b0ba88d13", "", 8)] - [InlineData("46b9dd2b0ba88d13233b3feb743eeb24", "", 16)] - [InlineData("46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f", "", 32)] - [InlineData("cd65a4e5", "1234567890", 4)] - [InlineData("cd65a4e553405b50", "1234567890", 8)] - [InlineData("cd65a4e553405b50c2f37001ea81905f", "1234567890", 16)] - [InlineData("cd65a4e553405b50c2f37001ea81905f36d650cc775fdad898b2e343644cb3db", "1234567890", 32)] - [InlineData("fa8775b6", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)] - [InlineData("fa8775b64bf3aaf1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)] - [InlineData("fa8775b64bf3aaf10d7f473c460f4d23", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 16)] - [InlineData("fa8775b64bf3aaf10d7f473c460f4d2361f56ff34ae7267a", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 24)] - [InlineData("b7b78b04", "abcdefghijklmnopqrstuvwxyz", 4)] - [InlineData("b7b78b04a3dd30a2", "abcdefghijklmnopqrstuvwxyz", 8)] - [InlineData("b7b78b04a3dd30a265c8886c33fda947", "abcdefghijklmnopqrstuvwxyz", 16)] - [InlineData("b7b78b04a3dd30a265c8886c33fda94799853de5d3d10541", "abcdefghijklmnopqrstuvwxyz", 24)] - public override void TestSha3WithLiteralString(string expected, string literal, int length) - { - HashAlgorithm = Sha3.CreateSha3Shake256(length); - base.TestSha3WithLiteralString(expected, literal, length); - } + HashAlgorithm = Sha3.CreateSha3Shake256(length); + base.TestSha3WithLiteralString(expected, literal, length); + } - [Theory(DisplayName = "Sha3ManagedShake256 should produce the expected hash for the specified string template")] - [InlineData("3578a7a4", "a", 1_000_000, 4)] - [InlineData("3578a7a4ca913756", "a", 1_000_000, 8)] - [InlineData("3578a7a4ca9137569cdf76ed617d31bb", "a", 1_000_000, 16)] - [InlineData("3578a7a4ca9137569cdf76ed617d31bb994fca9c1bbf8b184013de8234dfd13a", "a", 1_000_000, 32)] - public override void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) - { - HashAlgorithm = Sha3.CreateSha3Shake256(length); - base.TestSha3WithGeneratedString(expected, template, iterations, length); - } + [Theory(DisplayName = "Sha3ManagedShake256 should produce the expected hash for the specified string template")] + [InlineData("3578a7a4", "a", 1_000_000, 4)] + [InlineData("3578a7a4ca913756", "a", 1_000_000, 8)] + [InlineData("3578a7a4ca9137569cdf76ed617d31bb", "a", 1_000_000, 16)] + [InlineData("3578a7a4ca9137569cdf76ed617d31bb994fca9c1bbf8b184013de8234dfd13a", "a", 1_000_000, 32)] + public override void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) + { + HashAlgorithm = Sha3.CreateSha3Shake256(length); + base.TestSha3WithGeneratedString(expected, template, iterations, length); } } diff --git a/OnixLabs.Security.Cryptography.UnitTests/Sha3ShakeTestBase.cs b/OnixLabs.Security.Cryptography.UnitTests/Sha3ShakeTestBase.cs index 8e8678e..92f9d71 100644 --- a/OnixLabs.Security.Cryptography.UnitTests/Sha3ShakeTestBase.cs +++ b/OnixLabs.Security.Cryptography.UnitTests/Sha3ShakeTestBase.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,29 +17,28 @@ using System.Text; using Xunit; -namespace OnixLabs.Security.Cryptography.UnitTests +namespace OnixLabs.Security.Cryptography.UnitTests; + +public abstract class Sha3ShakeTestBase { - public abstract class Sha3ShakeTestBase - { - protected Sha3 HashAlgorithm { get; set; } + protected Sha3 HashAlgorithm { get; set; } - public virtual void TestSha3WithLiteralString(string expected, string literal, int length) - { - string actual = ComputeHash(HashAlgorithm, literal); - Assert.Equal(expected, actual); - } + public virtual void TestSha3WithLiteralString(string expected, string literal, int length) + { + string actual = ComputeHash(HashAlgorithm, literal); + Assert.Equal(expected, actual); + } - public virtual void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) - { - string actual = ComputeHash(HashAlgorithm, string.Concat(Enumerable.Repeat(template, iterations))); - Assert.Equal(expected, actual); - } + public virtual void TestSha3WithGeneratedString(string expected, string template, int iterations, int length) + { + string actual = ComputeHash(HashAlgorithm, string.Concat(Enumerable.Repeat(template, iterations))); + Assert.Equal(expected, actual); + } - private static string ComputeHash(HashAlgorithm algorithm, string plainText) - { - byte[] plainTextBytes = Encoding.Default.GetBytes(plainText); - byte[] hashedBytes = algorithm.ComputeHash(plainTextBytes); - return Hash.FromByteArray(hashedBytes).ToString(); - } + private static string ComputeHash(HashAlgorithm algorithm, string plainText) + { + byte[] plainTextBytes = Encoding.Default.GetBytes(plainText); + byte[] hashedBytes = algorithm.ComputeHash(plainTextBytes); + return Hash.FromByteArray(hashedBytes).ToString(); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.Empty.cs b/OnixLabs.Security.Cryptography/DigitalSignature.Empty.cs index 90c5e37..f64bb8b 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.Empty.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct DigitalSignature { - public readonly partial struct DigitalSignature - { - /// - /// Gets an empty digital signature value. - /// - public static readonly DigitalSignature Empty; + /// + /// Gets an empty digital signature value. + /// + public static readonly DigitalSignature Empty; - /// - /// Initializes static members of the class. - /// - static DigitalSignature() - { - Empty = FromByteArray(Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static DigitalSignature() + { + Empty = FromByteArray(Array.Empty()); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.Equatable.cs b/OnixLabs.Security.Cryptography/DigitalSignature.Equatable.cs index 8b2c221..837007e 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.Equatable.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,59 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct DigitalSignature : IEquatable { - public readonly partial struct DigitalSignature : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(DigitalSignature a, DigitalSignature b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(DigitalSignature a, DigitalSignature b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(DigitalSignature a, DigitalSignature b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(DigitalSignature a, DigitalSignature b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(DigitalSignature other) - { - return other.Value.SequenceEqual(Value); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(DigitalSignature other) + { + return other.Value.SequenceEqual(Value); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is DigitalSignature other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is DigitalSignature other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Value.GetContentHashCode()); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.From.cs b/OnixLabs.Security.Cryptography/DigitalSignature.From.cs index 9a33250..27a39b1 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.From.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,62 +14,61 @@ using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct DigitalSignature { - public readonly partial struct DigitalSignature + /// + /// Creates a instance from the specified digitally signed data. + /// + /// The digitally signed data. + /// Returns a instance from the specified digitally signed data. + public static DigitalSignature FromByteArray(byte[] value) { - /// - /// Creates a instance from the specified digitally signed data. - /// - /// The digitally signed data. - /// Returns a instance from the specified digitally signed data. - public static DigitalSignature FromByteArray(byte[] value) - { - return new DigitalSignature(value); - } + return new DigitalSignature(value); + } - /// - /// Creates a from the specified value. - /// - /// The Base-16 from which to construct a signature value. - /// Returns an from the specified Base-16 value. - public static DigitalSignature FromBase16(Base16 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-16 from which to construct a signature value. + /// Returns an from the specified Base-16 value. + public static DigitalSignature FromBase16(Base16 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-32 from which to construct a signature value. - /// Returns an from the specified Base-32 value. - public static DigitalSignature FromBase32(Base32 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-32 from which to construct a signature value. + /// Returns an from the specified Base-32 value. + public static DigitalSignature FromBase32(Base32 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-58 from which to construct a signature value. - /// Returns an from the specified Base-58 value. - public static DigitalSignature FromBase58(Base58 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-58 from which to construct a signature value. + /// Returns an from the specified Base-58 value. + public static DigitalSignature FromBase58(Base58 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-64 from which to construct a signature value. - /// Returns an from the specified Base-64 value. - public static DigitalSignature FromBase64(Base64 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-64 from which to construct a signature value. + /// Returns an from the specified Base-64 value. + public static DigitalSignature FromBase64(Base64 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.To.cs b/OnixLabs.Security.Cryptography/DigitalSignature.To.cs index 310ebc8..85cf729 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.To.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,82 +16,81 @@ using OnixLabs.Core; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct DigitalSignature { - public readonly partial struct DigitalSignature + /// + /// Returns a byte array containing the underlying signed data. + /// + /// A byte array containing the underlying signed data. + public byte[] ToByteArray() { - /// - /// Returns a byte array containing the underlying signed data. - /// - /// A byte array containing the underlying signed data. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// Returns a value that represents the underlying signature data. - public Base16 ToBase16() - { - return Base16.FromByteArray(Value); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// Returns a value that represents the underlying signature data. + public Base16 ToBase16() + { + return Base16.FromByteArray(Value); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// Returns a value that represents the underlying signature data. - public Base32 ToBase32() - { - return ToBase32(Base32Alphabet.Default); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// Returns a value that represents the underlying signature data. + public Base32 ToBase32() + { + return ToBase32(Base32Alphabet.Default); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// The Base-32 alphabet to use to encode the signature data. - /// Returns a value that represents the underlying signature data. - public Base32 ToBase32(Base32Alphabet alphabet) - { - return Base32.FromByteArray(Value, alphabet); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// The Base-32 alphabet to use to encode the signature data. + /// Returns a value that represents the underlying signature data. + public Base32 ToBase32(Base32Alphabet alphabet) + { + return Base32.FromByteArray(Value, alphabet); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// Returns a value that represents the underlying signature data. - public Base58 ToBase58() - { - return ToBase58(Base58Alphabet.Default); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// Returns a value that represents the underlying signature data. + public Base58 ToBase58() + { + return ToBase58(Base58Alphabet.Default); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// The Base-58 alphabet to use to encode the signature data. - /// Returns a value that represents the underlying signature data. - public Base58 ToBase58(Base58Alphabet alphabet) - { - return Base58.FromByteArray(Value, alphabet); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// The Base-58 alphabet to use to encode the signature data. + /// Returns a value that represents the underlying signature data. + public Base58 ToBase58(Base58Alphabet alphabet) + { + return Base58.FromByteArray(Value, alphabet); + } - /// - /// Returns a value that represents the underlying signature data. - /// - /// Returns a value that represents the underlying signature data. - public Base64 ToBase64() - { - return Base64.FromByteArray(Value); - } + /// + /// Returns a value that represents the underlying signature data. + /// + /// Returns a value that represents the underlying signature data. + public Base64 ToBase64() + { + return Base64.FromByteArray(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToHexString(Value).ToLower(); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToHexString(Value).ToLower(); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.Validation.cs b/OnixLabs.Security.Cryptography/DigitalSignature.Validation.cs index 69741ec..10920cf 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.Validation.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.Validation.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,82 +14,81 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct DigitalSignature { - public readonly partial struct DigitalSignature + /// + /// Determines whether this is valid, given the specified unsigned data and public key. + /// + /// The unsigned data to validate. + /// The public key to validate. + /// Returns true if this is valid; otherwise, false. + public bool IsDataValid(byte[] unsignedData, PublicKey key) { - /// - /// Determines whether this is valid, given the specified unsigned data and public key. - /// - /// The unsigned data to validate. - /// The public key to validate. - /// Returns true if this is valid; otherwise, false. - public bool IsDataValid(byte[] unsignedData, PublicKey key) - { - return key.IsDataValid(this, unsignedData); - } + return key.IsDataValid(this, unsignedData); + } - /// - /// Determines whether this is valid, given the specified unsigned hash and public key. - /// - /// The unsigned data to validate. - /// The public key to validate. - /// Returns true if this is valid; otherwise, false. - public bool IsHashValid(byte[] unsignedHash, PublicKey key) - { - return key.IsHashValid(this, unsignedHash); - } + /// + /// Determines whether this is valid, given the specified unsigned hash and public key. + /// + /// The unsigned data to validate. + /// The public key to validate. + /// Returns true if this is valid; otherwise, false. + public bool IsHashValid(byte[] unsignedHash, PublicKey key) + { + return key.IsHashValid(this, unsignedHash); + } - /// - /// Determines whether this is valid, given the specified unsigned hash and public key. - /// - /// The unsigned data to validate. - /// The public key to validate. - /// Returns true if this is valid; otherwise, false. - public bool IsHashValid(Hash unsignedHash, PublicKey key) - { - byte[] unsignedHashBytes = unsignedHash.ToByteArray(); - return IsHashValid(unsignedHashBytes, key); - } + /// + /// Determines whether this is valid, given the specified unsigned hash and public key. + /// + /// The unsigned data to validate. + /// The public key to validate. + /// Returns true if this is valid; otherwise, false. + public bool IsHashValid(Hash unsignedHash, PublicKey key) + { + byte[] unsignedHashBytes = unsignedHash.ToByteArray(); + return IsHashValid(unsignedHashBytes, key); + } - /// - /// Verifies this . - /// - /// The unsigned data to verify. - /// The public key to verify. - /// If this was not signed by the specified key. - public void VerifyData(byte[] unsignedData, PublicKey key) + /// + /// Verifies this . + /// + /// The unsigned data to verify. + /// The public key to verify. + /// If this was not signed by the specified key. + public void VerifyData(byte[] unsignedData, PublicKey key) + { + if (!IsDataValid(unsignedData, key)) { - if (!IsDataValid(unsignedData, key)) - { - throw new CryptographicException("The specified digital signature was not signed with this key."); - } + throw new CryptographicException("The specified digital signature was not signed with this key."); } + } - /// - /// Verifies this . - /// - /// The unsigned hash to verify. - /// The public key to verify. - /// If this was not signed by the specified key. - public void VerifyHash(byte[] unsignedHash, PublicKey key) + /// + /// Verifies this . + /// + /// The unsigned hash to verify. + /// The public key to verify. + /// If this was not signed by the specified key. + public void VerifyHash(byte[] unsignedHash, PublicKey key) + { + if (!IsHashValid(unsignedHash, key)) { - if (!IsHashValid(unsignedHash, key)) - { - throw new CryptographicException("The specified digital signature was not signed with this key."); - } + throw new CryptographicException("The specified digital signature was not signed with this key."); } + } - /// - /// Verifies this . - /// - /// The unsigned hash to verify. - /// The public key to verify. - /// If this was not signed by the specified key. - public void VerifyHash(Hash unsignedHash, PublicKey key) - { - byte[] unsignedHashBytes = unsignedHash.ToByteArray(); - VerifyHash(unsignedHashBytes, key); - } + /// + /// Verifies this . + /// + /// The unsigned hash to verify. + /// The public key to verify. + /// If this was not signed by the specified key. + public void VerifyHash(Hash unsignedHash, PublicKey key) + { + byte[] unsignedHashBytes = unsignedHash.ToByteArray(); + VerifyHash(unsignedHashBytes, key); } } diff --git a/OnixLabs.Security.Cryptography/DigitalSignature.cs b/OnixLabs.Security.Cryptography/DigitalSignature.cs index c89644a..6ffb8d1 100644 --- a/OnixLabs.Security.Cryptography/DigitalSignature.cs +++ b/OnixLabs.Security.Cryptography/DigitalSignature.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a digital signature. +/// +public readonly partial struct DigitalSignature { /// - /// Represents a digital signature. + /// Initializes a new instance of the struct. /// - public readonly partial struct DigitalSignature + /// The digitally signed data. + private DigitalSignature(byte[] value) { - /// - /// Initializes a new instance of the struct. - /// - /// The digitally signed data. - private DigitalSignature(byte[] value) - { - Value = value; - } - - /// - /// Gets the underlying digitally signed data. - /// - private byte[] Value { get; } + Value = value; } + + /// + /// Gets the underlying digitally signed data. + /// + private byte[] Value { get; } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Export.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Export.cs index 2d765c1..73f6f0f 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Export.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Export.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,36 +15,35 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPrivateKey { - public sealed partial class EcdsaPrivateKey + /// + /// Exports the key in PKCS #8 format. + /// + /// Returns the key in PKCS #8 format. + public override byte[] ExportPkcs8Key() + { + using ECDsa privateKey = ECDsa.Create(); + + privateKey.ImportECPrivateKey(KeyData, out int _); + + return privateKey.ExportPkcs8PrivateKey(); + } + + /// + /// Exports the key in encrypted PKCS #8 format. + /// + /// The password to use for encryption. + /// The parameters required for password based encryption. + /// Returns the key in encrypted PKCS #8 format. + public override byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters) { - /// - /// Exports the key in PKCS #8 format. - /// - /// Returns the key in PKCS #8 format. - public override byte[] ExportPkcs8Key() - { - using ECDsa privateKey = ECDsa.Create(); - - privateKey.ImportECPrivateKey(KeyData, out int _); - - return privateKey.ExportPkcs8PrivateKey(); - } - - /// - /// Exports the key in encrypted PKCS #8 format. - /// - /// The password to use for encryption. - /// The parameters required for password based encryption. - /// Returns the key in encrypted PKCS #8 format. - public override byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters) - { - using ECDsa privateKey = ECDsa.Create(); - - privateKey.ImportECPrivateKey(KeyData, out int _); - - return privateKey.ExportEncryptedPkcs8PrivateKey(password, parameters); - } + using ECDsa privateKey = ECDsa.Create(); + + privateKey.ImportECPrivateKey(KeyData, out int _); + + return privateKey.ExportEncryptedPkcs8PrivateKey(password, parameters); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.From.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.From.cs index 99666a5..e43b3b0 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.From.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,67 +14,66 @@ using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPrivateKey { - public sealed partial class EcdsaPrivateKey + /// + /// Creates an from the specified key data and hash algorithm type. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPrivateKey FromByteArray(byte[] key, HashAlgorithmType type) { - /// - /// Creates an from the specified key data and hash algorithm type. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPrivateKey FromByteArray(byte[] key, HashAlgorithmType type) - { - return new EcdsaPrivateKey(key, type); - } + return new EcdsaPrivateKey(key, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPrivateKey FromBase16(Base16 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPrivateKey FromBase16(Base16 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPrivateKey FromBase32(Base32 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPrivateKey FromBase32(Base32 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPrivateKey FromBase58(Base58 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPrivateKey FromBase58(Base58 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPrivateKey FromBase64(Base64 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPrivateKey FromBase64(Base64 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Get.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Get.cs index 41e8677..91cfb79 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Get.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Get.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,22 +14,21 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPrivateKey { - public sealed partial class EcdsaPrivateKey + /// + /// Gets the public key component from this private key. + /// + /// Returns the public key component from this private key. + public override PublicKey GetPublicKey() { - /// - /// Gets the public key component from this private key. - /// - /// Returns the public key component from this private key. - public override PublicKey GetPublicKey() - { - using ECDsa privateKey = ECDsa.Create(); + using ECDsa privateKey = ECDsa.Create(); - privateKey.ImportECPrivateKey(KeyData, out int _); - byte[] publicKey = privateKey.ExportSubjectPublicKeyInfo(); + privateKey.ImportECPrivateKey(KeyData, out int _); + byte[] publicKey = privateKey.ExportSubjectPublicKeyInfo(); - return new EcdsaPublicKey(publicKey, AlgorithmType); - } + return new EcdsaPublicKey(publicKey, AlgorithmType); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Import.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Import.cs index 526316a..ac3559e 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Import.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Import.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,121 +15,117 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPrivateKey { - public sealed partial class EcdsaPrivateKey + /// + /// Imports a PKCS #8 formatted key. + /// + /// The key data to import. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, HashAlgorithmType type) { - /// - /// Imports a PKCS #8 formatted key. - /// - /// The key data to import. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, HashAlgorithmType type) - { - ECDsa privateKey = ECDsa.Create(); + ECDsa privateKey = ECDsa.Create(); - privateKey.ImportPkcs8PrivateKey(data, out int _); - byte[] bytes = privateKey.ExportECPrivateKey(); + privateKey.ImportPkcs8PrivateKey(data, out int _); + byte[] bytes = privateKey.ExportECPrivateKey(); - return FromByteArray(bytes, type); - } + return FromByteArray(bytes, type); + } - /// - /// Imports a PKCS #8 formatted key. - /// - /// The key data to import. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, HashAlgorithmType type) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, type); - } + /// + /// Imports a PKCS #8 formatted key. + /// + /// The key data to import. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, HashAlgorithmType type) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key( - ReadOnlySpan data, - ReadOnlySpan password, - HashAlgorithmType type) - { - ECDsa privateKey = ECDsa.Create(); + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, ReadOnlySpan password, HashAlgorithmType type) + { + ECDsa privateKey = ECDsa.Create(); - privateKey.ImportEncryptedPkcs8PrivateKey(password, data, out int _); - byte[] bytes = privateKey.ExportECPrivateKey(); + privateKey.ImportEncryptedPkcs8PrivateKey(password, data, out int _); + byte[] bytes = privateKey.ExportECPrivateKey(); - return FromByteArray(bytes, type); - } + return FromByteArray(bytes, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, char[] password, HashAlgorithmType type) - { - ReadOnlySpan characters = password.AsSpan(); - return ImportPkcs8Key(data, characters, type); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, char[] password, HashAlgorithmType type) + { + ReadOnlySpan characters = password.AsSpan(); + return ImportPkcs8Key(data, characters, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, string password, HashAlgorithmType type) - { - ReadOnlySpan characters = password.AsSpan(); - return ImportPkcs8Key(data, characters, type); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, string password, HashAlgorithmType type) + { + ReadOnlySpan characters = password.AsSpan(); + return ImportPkcs8Key(data, characters, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, ReadOnlySpan password, HashAlgorithmType type) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, ReadOnlySpan password, HashAlgorithmType type) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, char[] password, HashAlgorithmType type) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, char[] password, HashAlgorithmType type) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, string password, HashAlgorithmType type) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static EcdsaPrivateKey ImportPkcs8Key(byte[] data, string password, HashAlgorithmType type) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Sign.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Sign.cs index a1eca45..a47a64d 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Sign.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.Sign.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,39 +14,38 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPrivateKey { - public sealed partial class EcdsaPrivateKey + /// + /// Computes a from the specified unsigned data. + /// + /// The unsigned data from which to compute a . + /// Returns a from the specified unsigned data. + public override DigitalSignature SignData(byte[] unsignedData) + { + using ECDsa privateKey = ECDsa.Create(); + + privateKey.ImportECPrivateKey(KeyData, out int _); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + byte[] signedData = privateKey.SignData(unsignedData, name); + + return DigitalSignature.FromByteArray(signedData); + } + + /// + /// Computes a from the specified unsigned hash. + /// + /// The unsigned hash from which to compute a . + /// Returns a from the specified unsigned hash. + public override DigitalSignature SignHash(byte[] unsignedHash) { - /// - /// Computes a from the specified unsigned data. - /// - /// The unsigned data from which to compute a . - /// Returns a from the specified unsigned data. - public override DigitalSignature SignData(byte[] unsignedData) - { - using ECDsa privateKey = ECDsa.Create(); - - privateKey.ImportECPrivateKey(KeyData, out int _); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - byte[] signedData = privateKey.SignData(unsignedData, name); - - return DigitalSignature.FromByteArray(signedData); - } - - /// - /// Computes a from the specified unsigned hash. - /// - /// The unsigned hash from which to compute a . - /// Returns a from the specified unsigned hash. - public override DigitalSignature SignHash(byte[] unsignedHash) - { - using ECDsa privateKey = ECDsa.Create(); - - privateKey.ImportECPrivateKey(KeyData, out int _); - byte[] signedData = privateKey.SignHash(unsignedHash); - - return DigitalSignature.FromByteArray(signedData); - } + using ECDsa privateKey = ECDsa.Create(); + + privateKey.ImportECPrivateKey(KeyData, out int _); + byte[] signedData = privateKey.SignHash(unsignedHash); + + return DigitalSignature.FromByteArray(signedData); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.cs b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.cs index dea5669..48fad76 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPrivateKey.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPrivateKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,20 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents an ECDSA private key. +/// +public sealed partial class EcdsaPrivateKey : PrivateKey { /// - /// Represents an ECDSA private key. + /// Creates a new instance of the class. /// - public sealed partial class EcdsaPrivateKey : PrivateKey + /// The private key data. + /// The hash algorithm type for computing signature data. + internal EcdsaPrivateKey(byte[] data, HashAlgorithmType type) : base(data, type) { - /// - /// Creates a new instance of the class. - /// - /// The private key data. - /// The hash algorithm type for computing signature data. - internal EcdsaPrivateKey(byte[] data, HashAlgorithmType type) : base(data, type) - { - } } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPublicKey.From.cs b/OnixLabs.Security.Cryptography/EcdsaPublicKey.From.cs index 845618c..125755f 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPublicKey.From.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPublicKey.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,67 +14,66 @@ using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPublicKey { - public sealed partial class EcdsaPublicKey + /// + /// Creates an from the specified key data and hash algorithm type. + /// + /// The key data from which to construct a public key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPublicKey FromByteArray(byte[] key, HashAlgorithmType type) { - /// - /// Creates an from the specified key data and hash algorithm type. - /// - /// The key data from which to construct a public key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPublicKey FromByteArray(byte[] key, HashAlgorithmType type) - { - return new EcdsaPublicKey(key, type); - } + return new EcdsaPublicKey(key, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPublicKey FromBase16(Base16 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPublicKey FromBase16(Base16 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPublicKey FromBase32(Base32 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPublicKey FromBase32(Base32 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPublicKey FromBase58(Base58 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPublicKey FromBase58(Base58 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static EcdsaPublicKey FromBase64(Base64 key, HashAlgorithmType type) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static EcdsaPublicKey FromBase64(Base64 key, HashAlgorithmType type) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPublicKey.Verify.cs b/OnixLabs.Security.Cryptography/EcdsaPublicKey.Verify.cs index d24742b..bd44b43 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPublicKey.Verify.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPublicKey.Verify.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,41 +14,40 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class EcdsaPublicKey { - public sealed partial class EcdsaPublicKey + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned data to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public override bool IsDataValid(DigitalSignature signature, byte[] unsignedData) + { + using ECDsa publicKey = ECDsa.Create(); + + publicKey.ImportSubjectPublicKeyInfo(KeyData, out int _); + byte[] signatureData = signature.ToByteArray(); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + + return publicKey.VerifyData(unsignedData, signatureData, name); + } + + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned hash to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public override bool IsHashValid(DigitalSignature signature, byte[] unsignedHash) { - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned data to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public override bool IsDataValid(DigitalSignature signature, byte[] unsignedData) - { - using ECDsa publicKey = ECDsa.Create(); - - publicKey.ImportSubjectPublicKeyInfo(KeyData, out int _); - byte[] signatureData = signature.ToByteArray(); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - - return publicKey.VerifyData(unsignedData, signatureData, name); - } - - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned hash to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public override bool IsHashValid(DigitalSignature signature, byte[] unsignedHash) - { - using ECDsa publicKey = ECDsa.Create(); - - publicKey.ImportSubjectPublicKeyInfo(KeyData, out int _); - byte[] signatureData = signature.ToByteArray(); - - return publicKey.VerifyHash(unsignedHash, signatureData); - } + using ECDsa publicKey = ECDsa.Create(); + + publicKey.ImportSubjectPublicKeyInfo(KeyData, out int _); + byte[] signatureData = signature.ToByteArray(); + + return publicKey.VerifyHash(unsignedHash, signatureData); } } diff --git a/OnixLabs.Security.Cryptography/EcdsaPublicKey.cs b/OnixLabs.Security.Cryptography/EcdsaPublicKey.cs index c37cec7..1af352b 100644 --- a/OnixLabs.Security.Cryptography/EcdsaPublicKey.cs +++ b/OnixLabs.Security.Cryptography/EcdsaPublicKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,20 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents an ECDSA public key. +/// +public sealed partial class EcdsaPublicKey : PublicKey { /// - /// Represents an ECDSA public key. + /// Creates a new instance of the class. /// - public sealed partial class EcdsaPublicKey : PublicKey + /// The public key data. + /// The hash algorithm type for computing signature data. + internal EcdsaPublicKey(byte[] data, HashAlgorithmType type) : base(data, type) { - /// - /// Creates a new instance of the class. - /// - /// The public key data. - /// The hash algorithm type for computing signature data. - internal EcdsaPublicKey(byte[] data, HashAlgorithmType type) : base(data, type) - { - } } } diff --git a/OnixLabs.Security.Cryptography/Hash.AllOneHash.cs b/OnixLabs.Security.Cryptography/Hash.AllOneHash.cs index 9df6982..94beba4 100644 --- a/OnixLabs.Security.Cryptography/Hash.AllOneHash.cs +++ b/OnixLabs.Security.Cryptography/Hash.AllOneHash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,47 +14,44 @@ using System; using System.Linq; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Creates an all-one hash of the specified length. This will create a hash of an unknown type. + /// + /// The length of the hash in bytes. + /// Returns an all-one of the specified length. + public static Hash CreateAllOneHash(int length) { - /// - /// Creates an all-one hash of the specified length. This will create a hash of an unknown type. - /// - /// The length of the hash in bytes. - /// Returns an all-one of the specified length. - public static Hash CreateAllOneHash(int length) - { - return CreateAllOneHash(HashAlgorithmType.Unknown, length); - } - - /// - /// Creates an all-one hash of the specified hash algorithm type. - /// - /// The type of hash to create. - /// Returns an all-one of the specified hash algorithm type. - public static Hash CreateAllOneHash(HashAlgorithmType type) - { - return CreateAllOneHash(type, type.Length); - } + return CreateAllOneHash(HashAlgorithmType.Unknown, length); + } - /// - /// Creates an all-one hash of the specified hash algorithm type and length. - /// - /// The type of hash to create. - /// The length of the hash in bytes. - /// Returns an all-one of the specified hash algorithm type and length. - /// If the length of the hash is unexpected. - public static Hash CreateAllOneHash(HashAlgorithmType type, int length) - { - if (type.Length != HashAlgorithmType.UnknownLength && type.Length != length) - { - throw new ArgumentException("Unexpected hash algorithm output length."); - } + /// + /// Creates an all-one hash of the specified hash algorithm type. + /// + /// The type of hash to create. + /// Returns an all-one of the specified hash algorithm type. + public static Hash CreateAllOneHash(HashAlgorithmType type) + { + return CreateAllOneHash(type, type.Length); + } - byte[] bytes = Enumerable.Repeat(byte.MaxValue, length).ToArray(); - return FromByteArray(bytes, type); - } + /// + /// Creates an all-one hash of the specified hash algorithm type and length. + /// + /// The type of hash to create. + /// The length of the hash in bytes. + /// Returns an all-one of the specified hash algorithm type and length. + /// If the length of the hash is unexpected. + public static Hash CreateAllOneHash(HashAlgorithmType type, int length) + { + Check(type.IsUnknown || type.Length == length, "Unexpected hash algorithm output length."); + + byte[] bytes = Enumerable.Repeat(byte.MaxValue, length).ToArray(); + return FromByteArray(bytes, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.AllZeroHash.cs b/OnixLabs.Security.Cryptography/Hash.AllZeroHash.cs index 411855d..5985b43 100644 --- a/OnixLabs.Security.Cryptography/Hash.AllZeroHash.cs +++ b/OnixLabs.Security.Cryptography/Hash.AllZeroHash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,47 +14,44 @@ using System; using System.Linq; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Creates an all-zero hash of the specified length. This will create a hash of an unknown type. + /// + /// The length of the hash in bytes. + /// Returns an all-zero of the specified length. + public static Hash CreateAllZeroHash(int length) { - /// - /// Creates an all-zero hash of the specified length. This will create a hash of an unknown type. - /// - /// The length of the hash in bytes. - /// Returns an all-zero of the specified length. - public static Hash CreateAllZeroHash(int length) - { - return CreateAllZeroHash(HashAlgorithmType.Unknown, length); - } + return CreateAllZeroHash(HashAlgorithmType.Unknown, length); + } - /// - /// Creates an all-zero hash of the specified hash algorithm type. - /// - /// The type of hash to create. - /// Returns an all-zero of the specified hash algorithm type. - public static Hash CreateAllZeroHash(HashAlgorithmType type) - { - return CreateAllZeroHash(type, type.Length); - } + /// + /// Creates an all-zero hash of the specified hash algorithm type. + /// + /// The type of hash to create. + /// Returns an all-zero of the specified hash algorithm type. + public static Hash CreateAllZeroHash(HashAlgorithmType type) + { + return CreateAllZeroHash(type, type.Length); + } - /// - /// Creates an all-zero hash of the specified hash algorithm type and length. - /// - /// The type of hash to create. - /// The length of the hash in bytes. - /// Returns an all-zero of the specified hash algorithm type and length. - /// If the length of the hash is unexpected. - public static Hash CreateAllZeroHash(HashAlgorithmType type, int length) - { - if (type.Length != HashAlgorithmType.UnknownLength && type.Length != length) - { - throw new ArgumentException("Unexpected hash algorithm output length."); - } + /// + /// Creates an all-zero hash of the specified hash algorithm type and length. + /// + /// The type of hash to create. + /// The length of the hash in bytes. + /// Returns an all-zero of the specified hash algorithm type and length. + /// If the length of the hash is unexpected. + public static Hash CreateAllZeroHash(HashAlgorithmType type, int length) + { + Check(type.IsUnknown || type.Length == length, "Unexpected hash algorithm output length."); - byte[] bytes = Enumerable.Repeat(byte.MinValue, length).ToArray(); - return FromByteArray(bytes, type); - } + byte[] bytes = Enumerable.Repeat(byte.MinValue, length).ToArray(); + return FromByteArray(bytes, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Md5Hash.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Md5Hash.cs index 03a4aef..3272729 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Md5Hash.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Md5Hash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes an MD5 hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeMd5Hash(string value) { - /// - /// Computes an MD5 hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeMd5Hash(string value) - { - return ComputeMd5Hash(value, Encoding.Default); - } + return ComputeMd5Hash(value, Encoding.Default); + } - /// - /// Computes an MD5 hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeMd5Hash(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Md5Hash, encoding); - } + /// + /// Computes an MD5 hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeMd5Hash(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Md5Hash, encoding); + } - /// - /// Computes an MD5 hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeMd5Hash(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Md5Hash); - } + /// + /// Computes an MD5 hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeMd5Hash(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Md5Hash); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha1Hash.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha1Hash.cs index d837662..f55d934 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha1Hash.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha1Hash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-1 hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha1Hash(string value) { - /// - /// Computes a SHA-1 hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha1Hash(string value) - { - return ComputeSha1Hash(value, Encoding.Default); - } + return ComputeSha1Hash(value, Encoding.Default); + } - /// - /// Computes a SHA-1 hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha1Hash(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha1Hash, encoding); - } + /// + /// Computes a SHA-1 hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha1Hash(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha1Hash, encoding); + } - /// - /// Computes a SHA-1 hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha1Hash(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha1Hash); - } + /// + /// Computes a SHA-1 hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha1Hash(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha1Hash); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash256.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash256.cs index 41f87fb..e19fd63 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash256.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash256(string value) { - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash256(string value) - { - return ComputeSha2Hash256(value, Encoding.Default); - } + return ComputeSha2Hash256(value, Encoding.Default); + } - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha2Hash256(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash256, encoding); - } + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha2Hash256(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash256, encoding); + } - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash256(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash256); - } + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash256(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash256); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash384.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash384.cs index 669584a..8b1c0f1 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash384.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash384(string value) { - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash384(string value) - { - return ComputeSha2Hash384(value, Encoding.Default); - } + return ComputeSha2Hash384(value, Encoding.Default); + } - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha2Hash384(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash384, encoding); - } + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha2Hash384(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash384, encoding); + } - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash384(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash384); - } + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash384(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash384); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash512.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash512.cs index 55d3c15..d310bd6 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash512.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha2Hash512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash512(string value) { - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash512(string value) - { - return ComputeSha2Hash512(value, Encoding.Default); - } + return ComputeSha2Hash512(value, Encoding.Default); + } - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha2Hash512(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash512, encoding); - } + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha2Hash512(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash512, encoding); + } - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha2Hash512(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha2Hash512); - } + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha2Hash512(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha2Hash512); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash224.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash224.cs index 75963c4..64e6a74 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash224.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash224.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash224(string value) { - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash224(string value) - { - return ComputeSha3Hash224(value, Encoding.Default); - } + return ComputeSha3Hash224(value, Encoding.Default); + } - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha3Hash224(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash224, encoding); - } + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha3Hash224(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash224, encoding); + } - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash224(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash224); - } + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash224(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash224); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash256.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash256.cs index e4a29d4..6346596 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash256.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash256(string value) { - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash256(string value) - { - return ComputeSha3Hash256(value, Encoding.Default); - } + return ComputeSha3Hash256(value, Encoding.Default); + } - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha3Hash256(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash256, encoding); - } + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha3Hash256(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash256, encoding); + } - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash256(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash256); - } + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash256(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash256); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash384.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash384.cs index 0334f9e..6ab1e42 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash384.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash384(string value) { - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash384(string value) - { - return ComputeSha3Hash384(value, Encoding.Default); - } + return ComputeSha3Hash384(value, Encoding.Default); + } - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha3Hash384(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash384, encoding); - } + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha3Hash384(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash384, encoding); + } - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash384(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash384); - } + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash384(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash384); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash512.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash512.cs index 33d4bbd..6c2c34b 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash512.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Hash512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash512(string value) { - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash512(string value) - { - return ComputeSha3Hash512(value, Encoding.Default); - } + return ComputeSha3Hash512(value, Encoding.Default); + } - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static Hash ComputeSha3Hash512(string value, Encoding encoding) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash512, encoding); - } + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static Hash ComputeSha3Hash512(string value, Encoding encoding) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash512, encoding); + } - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static Hash ComputeSha3Hash512(byte[] value) - { - return ComputeHash(value, HashAlgorithmType.Sha3Hash512); - } + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static Hash ComputeSha3Hash512(byte[] value) + { + return ComputeHash(value, HashAlgorithmType.Sha3Hash512); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake128.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake128.cs index 7b3b283..c94f57b 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake128.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake128.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,43 +14,42 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake128(string value, int length) { - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake128(string value, int length) - { - return ComputeSha3Shake128(value, Encoding.Default, length); - } + return ComputeSha3Shake128(value, Encoding.Default, length); + } - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake128(string value, Encoding encoding, int length) - { - return ComputeHash(value, HashAlgorithmType.Sha3Shake128, encoding, length); - } + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake128(string value, Encoding encoding, int length) + { + return ComputeHash(value, HashAlgorithmType.Sha3Shake128, encoding, length); + } - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake128(byte[] value, int length) - { - return ComputeHash(value, HashAlgorithmType.Sha3Shake128, length); - } + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake128(byte[] value, int length) + { + return ComputeHash(value, HashAlgorithmType.Sha3Shake128, length); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake256.cs b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake256.cs index 0cf05d9..d1cd45e 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake256.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.Sha3Shake256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,43 +14,42 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake256(string value, int length) { - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake256(string value, int length) - { - return ComputeSha3Shake256(value, Encoding.Default, length); - } + return ComputeSha3Shake256(value, Encoding.Default, length); + } - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake256(string value, Encoding encoding, int length) - { - return ComputeHash(value, HashAlgorithmType.Sha3Shake256, encoding, length); - } + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake256(string value, Encoding encoding, int length) + { + return ComputeHash(value, HashAlgorithmType.Sha3Shake256, encoding, length); + } - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static Hash ComputeSha3Shake256(byte[] value, int length) - { - return ComputeHash(value, HashAlgorithmType.Sha3Shake256, length); - } + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static Hash ComputeSha3Shake256(byte[] value, int length) + { + return ComputeHash(value, HashAlgorithmType.Sha3Shake256, length); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Compute.cs b/OnixLabs.Security.Cryptography/Hash.Compute.cs index a131d70..32ebeea 100644 --- a/OnixLabs.Security.Cryptography/Hash.Compute.cs +++ b/OnixLabs.Security.Cryptography/Hash.Compute.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,83 +15,82 @@ using System.Security.Cryptography; using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(string value, HashAlgorithmType type) { - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(string value, HashAlgorithmType type) - { - return ComputeHash(value, type, Encoding.Default); - } + return ComputeHash(value, type, Encoding.Default); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(string value, HashAlgorithmType type, Encoding encoding) - { - return ComputeHash(encoding.GetBytes(value), type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(string value, HashAlgorithmType type, Encoding encoding) + { + return ComputeHash(encoding.GetBytes(value), type); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(string value, HashAlgorithmType type, int length) - { - return ComputeHash(value, type, Encoding.Default, length); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(string value, HashAlgorithmType type, int length) + { + return ComputeHash(value, type, Encoding.Default, length); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(string value, HashAlgorithmType type, Encoding encoding, int length) - { - return ComputeHash(encoding.GetBytes(value), type, length); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(string value, HashAlgorithmType type, Encoding encoding, int length) + { + return ComputeHash(encoding.GetBytes(value), type, length); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(byte[] value, HashAlgorithmType type) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(); - byte[] hashedValue = algorithm.ComputeHash(value); - return FromByteArray(hashedValue, type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(byte[] value, HashAlgorithmType type) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(); + byte[] hashedValue = algorithm.ComputeHash(value); + return FromByteArray(hashedValue, type); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static Hash ComputeHash(byte[] value, HashAlgorithmType type, int length) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(length); - byte[] hashedValue = algorithm.ComputeHash(value); - return FromByteArray(hashedValue, type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static Hash ComputeHash(byte[] value, HashAlgorithmType type, int length) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(length); + byte[] hashedValue = algorithm.ComputeHash(value); + return FromByteArray(hashedValue, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Md5Hash.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Md5Hash.cs index 3307503..65c5509 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Md5Hash.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Md5Hash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes an MD5 hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeMd5HashAsync(string value) { - /// - /// Computes an MD5 hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeMd5HashAsync(string value) - { - return await ComputeMd5HashAsync(value, Encoding.Default); - } + return await ComputeMd5HashAsync(value, Encoding.Default); + } - /// - /// Computes an MD5 hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeMd5HashAsync(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Md5Hash, encoding); - } + /// + /// Computes an MD5 hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeMd5HashAsync(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Md5Hash, encoding); + } - /// - /// Computes an MD5 hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeMd5HashAsync(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Md5Hash); - } + /// + /// Computes an MD5 hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeMd5HashAsync(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Md5Hash); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha1Hash.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha1Hash.cs index 26b9255..9261255 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha1Hash.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha1Hash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-1 hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha1HashAsync(string value) { - /// - /// Computes a SHA-1 hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha1HashAsync(string value) - { - return await ComputeSha1HashAsync(value, Encoding.Default); - } + return await ComputeSha1HashAsync(value, Encoding.Default); + } - /// - /// Computes a SHA-1 hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha1HashAsync(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha1Hash, encoding); - } + /// + /// Computes a SHA-1 hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha1HashAsync(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha1Hash, encoding); + } - /// - /// Computes a SHA-1 hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha1HashAsync(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha1Hash); - } + /// + /// Computes a SHA-1 hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha1HashAsync(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha1Hash); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash256.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash256.cs index 56516a5..3fa2372 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash256.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash256Async(string value) { - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash256Async(string value) - { - return await ComputeSha2Hash256Async(value, Encoding.Default); - } + return await ComputeSha2Hash256Async(value, Encoding.Default); + } - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha2Hash256Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash256, encoding); - } + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha2Hash256Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash256, encoding); + } - /// - /// Computes a SHA-2 256-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash256Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash256); - } + /// + /// Computes a SHA-2 256-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash256Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash256); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash384.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash384.cs index 8ca359e..0e329c6 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash384.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash384Async(string value) { - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash384Async(string value) - { - return await ComputeSha2Hash384Async(value, Encoding.Default); - } + return await ComputeSha2Hash384Async(value, Encoding.Default); + } - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha2Hash384Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash384, encoding); - } + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha2Hash384Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash384, encoding); + } - /// - /// Computes a SHA-2 384-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash384Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash384); - } + /// + /// Computes a SHA-2 384-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash384Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash384); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash512.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash512.cs index c2758d1..43d7fbc 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash512.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha2Hash512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash512Async(string value) { - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash512Async(string value) - { - return await ComputeSha2Hash512Async(value, Encoding.Default); - } + return await ComputeSha2Hash512Async(value, Encoding.Default); + } - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha2Hash512Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash512, encoding); - } + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha2Hash512Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash512, encoding); + } - /// - /// Computes a SHA-2 512-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha2Hash512Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash512); - } + /// + /// Computes a SHA-2 512-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha2Hash512Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha2Hash512); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash224.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash224.cs index 0e1e45e..165702a 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash224.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash224.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash224Async(string value) { - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash224Async(string value) - { - return await ComputeSha3Hash224Async(value, Encoding.Default); - } + return await ComputeSha3Hash224Async(value, Encoding.Default); + } - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha3Hash224Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash224, encoding); - } + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha3Hash224Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash224, encoding); + } - /// - /// Computes a SHA-3 224-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash224Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash224); - } + /// + /// Computes a SHA-3 224-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash224Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash224); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash256.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash256.cs index f0da545..19378c7 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash256.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash256Async(string value) { - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash256Async(string value) - { - return await ComputeSha3Hash256Async(value, Encoding.Default); - } + return await ComputeSha3Hash256Async(value, Encoding.Default); + } - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha3Hash256Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash256, encoding); - } + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha3Hash256Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash256, encoding); + } - /// - /// Computes a SHA-3 256-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash256Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash256); - } + /// + /// Computes a SHA-3 256-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash256Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash256); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash384.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash384.cs index 1513dfd..b48436a 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash384.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash384Async(string value) { - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash384Async(string value) - { - return await ComputeSha3Hash384Async(value, Encoding.Default); - } + return await ComputeSha3Hash384Async(value, Encoding.Default); + } - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha3Hash384Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash384, encoding); - } + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha3Hash384Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash384, encoding); + } - /// - /// Computes a SHA-3 384-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash384Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash384); - } + /// + /// Computes a SHA-3 384-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash384Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash384); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash512.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash512.cs index 1ebed28..a6717c9 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash512.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Hash512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,40 +15,39 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash512Async(string value) { - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash512Async(string value) - { - return await ComputeSha3Hash512Async(value, Encoding.Default); - } + return await ComputeSha3Hash512Async(value, Encoding.Default); + } - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a of the input value. - public static async Task ComputeSha3Hash512Async(string value, Encoding encoding) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash512, encoding); - } + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a of the input value. + public static async Task ComputeSha3Hash512Async(string value, Encoding encoding) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash512, encoding); + } - /// - /// Computes a SHA-3 512-bit hash from the specified value. - /// - /// The input value to hash. - /// Returns a of the input value. - public static async Task ComputeSha3Hash512Async(byte[] value) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash512); - } + /// + /// Computes a SHA-3 512-bit hash from the specified value. + /// + /// The input value to hash. + /// Returns a of the input value. + public static async Task ComputeSha3Hash512Async(byte[] value) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Hash512); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake128.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake128.cs index 5f672fd..102ac35 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake128.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake128.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,43 +15,42 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake128Async(string value, int length) { - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake128Async(string value, int length) - { - return await ComputeSha3Shake128Async(value, Encoding.Default, length); - } + return await ComputeSha3Shake128Async(value, Encoding.Default, length); + } - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake128Async(string value, Encoding encoding, int length) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake128, encoding, length); - } + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake128Async(string value, Encoding encoding, int length) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake128, encoding, length); + } - /// - /// Computes a SHA-3 Shake 128-bit hash from the specified value. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake128Async(byte[] value, int length) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake128, length); - } + /// + /// Computes a SHA-3 Shake 128-bit hash from the specified value. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake128Async(byte[] value, int length) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake128, length); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake256.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake256.cs index c43a0a0..96e5d02 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake256.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.Sha3Shake256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,43 +15,42 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// This will use the default encoding to convert the input string into a byte array. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake256Async(string value, int length) { - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// This will use the default encoding to convert the input string into a byte array. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake256Async(string value, int length) - { - return await ComputeSha3Shake256Async(value, Encoding.Default, length); - } + return await ComputeSha3Shake256Async(value, Encoding.Default, length); + } - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake256Async(string value, Encoding encoding, int length) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake256, encoding, length); - } + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake256Async(string value, Encoding encoding, int length) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake256, encoding, length); + } - /// - /// Computes a SHA-3 Shake 256-bit hash from the specified value. - /// - /// The input value to hash. - /// The length of the hash in bytes. - /// Returns a of the input value. - public static async Task ComputeSha3Shake256Async(byte[] value, int length) - { - return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake256, length); - } + /// + /// Computes a SHA-3 Shake 256-bit hash from the specified value. + /// + /// The input value to hash. + /// The length of the hash in bytes. + /// Returns a of the input value. + public static async Task ComputeSha3Shake256Async(byte[] value, int length) + { + return await ComputeHashAsync(value, HashAlgorithmType.Sha3Shake256, length); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.cs b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.cs index 76be832..04f8532 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeAsync.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeAsync.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,89 +17,84 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(string value, HashAlgorithmType type) { - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync(string value, HashAlgorithmType type) - { - return await ComputeHashAsync(value, type, Encoding.Default); - } + return await ComputeHashAsync(value, type, Encoding.Default); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync(string value, HashAlgorithmType type, Encoding encoding) - { - return await ComputeHashAsync(encoding.GetBytes(value), type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(string value, HashAlgorithmType type, Encoding encoding) + { + return await ComputeHashAsync(encoding.GetBytes(value), type); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync(string value, HashAlgorithmType type, int length) - { - return await ComputeHashAsync(value, type, Encoding.Default, length); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(string value, HashAlgorithmType type, int length) + { + return await ComputeHashAsync(value, type, Encoding.Default, length); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync( - string value, - HashAlgorithmType type, - Encoding encoding, - int length) - { - return await ComputeHashAsync(encoding.GetBytes(value), type, length); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(string value, HashAlgorithmType type, Encoding encoding, int length) + { + return await ComputeHashAsync(encoding.GetBytes(value), type, length); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync(byte[] value, HashAlgorithmType type) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(); - await using Stream stream = new MemoryStream(value); - byte[] hashedValue = await algorithm.ComputeHashAsync(stream); - return FromByteArray(hashedValue, type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(byte[] value, HashAlgorithmType type) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(); + await using Stream stream = new MemoryStream(value); + byte[] hashedValue = await algorithm.ComputeHashAsync(stream); + return FromByteArray(hashedValue, type); + } - /// - /// Computes the hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a hash of the specified value. - public static async Task ComputeHashAsync(byte[] value, HashAlgorithmType type, int length) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(length); - await using Stream stream = new MemoryStream(value); - byte[] hashedValue = await algorithm.ComputeHashAsync(stream); - return FromByteArray(hashedValue, type); - } + /// + /// Computes the hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a hash of the specified value. + public static async Task ComputeHashAsync(byte[] value, HashAlgorithmType type, int length) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(length); + await using Stream stream = new MemoryStream(value); + byte[] hashedValue = await algorithm.ComputeHashAsync(stream); + return FromByteArray(hashedValue, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeTwice.cs b/OnixLabs.Security.Cryptography/Hash.ComputeTwice.cs index 61893db..e4b0eb7 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeTwice.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeTwice.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,85 +15,84 @@ using System.Security.Cryptography; using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(string value, HashAlgorithmType type) { - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(string value, HashAlgorithmType type) - { - return ComputeHashTwice(value, type, Encoding.Default); - } + return ComputeHashTwice(value, type, Encoding.Default); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(string value, HashAlgorithmType type, Encoding encoding) - { - return ComputeHashTwice(encoding.GetBytes(value), type); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(string value, HashAlgorithmType type, Encoding encoding) + { + return ComputeHashTwice(encoding.GetBytes(value), type); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(string value, HashAlgorithmType type, int length) - { - return ComputeHashTwice(value, type, Encoding.Default, length); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(string value, HashAlgorithmType type, int length) + { + return ComputeHashTwice(value, type, Encoding.Default, length); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(string value, HashAlgorithmType type, Encoding encoding, int length) - { - return ComputeHashTwice(encoding.GetBytes(value), type, length); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(string value, HashAlgorithmType type, Encoding encoding, int length) + { + return ComputeHashTwice(encoding.GetBytes(value), type, length); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(byte[] value, HashAlgorithmType type) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(); - byte[] firstRoundValue = algorithm.ComputeHash(value); - byte[] secondRoundValue = algorithm.ComputeHash(firstRoundValue); - return FromByteArray(secondRoundValue, type); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(byte[] value, HashAlgorithmType type) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(); + byte[] firstRoundValue = algorithm.ComputeHash(value); + byte[] secondRoundValue = algorithm.ComputeHash(firstRoundValue); + return FromByteArray(secondRoundValue, type); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static Hash ComputeHashTwice(byte[] value, HashAlgorithmType type, int length) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(length); - byte[] firstRoundValue = algorithm.ComputeHash(value); - byte[] secondRoundValue = algorithm.ComputeHash(firstRoundValue); - return FromByteArray(secondRoundValue, type); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static Hash ComputeHashTwice(byte[] value, HashAlgorithmType type, int length) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(length); + byte[] firstRoundValue = algorithm.ComputeHash(value); + byte[] secondRoundValue = algorithm.ComputeHash(firstRoundValue); + return FromByteArray(secondRoundValue, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.ComputeTwiceAsync.cs b/OnixLabs.Security.Cryptography/Hash.ComputeTwiceAsync.cs index e8fe9aa..7d05fd1 100644 --- a/OnixLabs.Security.Cryptography/Hash.ComputeTwiceAsync.cs +++ b/OnixLabs.Security.Cryptography/Hash.ComputeTwiceAsync.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,99 +17,94 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type) { - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type) - { - return await ComputeHashTwiceAsync(value, type, Encoding.Default); - } + return await ComputeHashTwiceAsync(value, type, Encoding.Default); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type, Encoding encoding) - { - return await ComputeHashTwiceAsync(encoding.GetBytes(value), type); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type, Encoding encoding) + { + return await ComputeHashTwiceAsync(encoding.GetBytes(value), type); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type, int length) - { - return await ComputeHashTwiceAsync(value, type, Encoding.Default, length); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type, int length) + { + return await ComputeHashTwiceAsync(value, type, Encoding.Default, length); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The encoding which will be used to convert the input string into a byte array. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync( - string value, - HashAlgorithmType type, - Encoding encoding, - int length) - { - return await ComputeHashTwiceAsync(encoding.GetBytes(value), type, length); - } + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The encoding which will be used to convert the input string into a byte array. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(string value, HashAlgorithmType type, Encoding encoding, int length) + { + return await ComputeHashTwiceAsync(encoding.GetBytes(value), type, length); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync(byte[] value, HashAlgorithmType type) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(); + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(byte[] value, HashAlgorithmType type) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(); - await using Stream firstRoundStream = new MemoryStream(value); - byte[] firstRoundValue = await algorithm.ComputeHashAsync(firstRoundStream); + await using Stream firstRoundStream = new MemoryStream(value); + byte[] firstRoundValue = await algorithm.ComputeHashAsync(firstRoundStream); - await using Stream secondRoundStream = new MemoryStream(firstRoundValue); - byte[] secondRoundValue = await algorithm.ComputeHashAsync(secondRoundStream); + await using Stream secondRoundStream = new MemoryStream(firstRoundValue); + byte[] secondRoundValue = await algorithm.ComputeHashAsync(secondRoundStream); - return FromByteArray(secondRoundValue, type); - } + return FromByteArray(secondRoundValue, type); + } - /// - /// Computes a twice-hashed hash of the specified value using the specified . - /// - /// The value for which to compute a hash. - /// The hash algorithm type of the computed hash. - /// The output length of the computed hash in bytes. - /// Returns a representing a twice-hashed hash of the specified value. - public static async Task ComputeHashTwiceAsync(byte[] value, HashAlgorithmType type, int length) - { - using HashAlgorithm algorithm = type.GetHashAlgorithm(length); + /// + /// Computes a twice-hashed hash of the specified value using the specified . + /// + /// The value for which to compute a hash. + /// The hash algorithm type of the computed hash. + /// The output length of the computed hash in bytes. + /// Returns a representing a twice-hashed hash of the specified value. + public static async Task ComputeHashTwiceAsync(byte[] value, HashAlgorithmType type, int length) + { + using HashAlgorithm algorithm = type.GetHashAlgorithm(length); - await using Stream firstRoundStream = new MemoryStream(value); - byte[] firstRoundValue = await algorithm.ComputeHashAsync(firstRoundStream); + await using Stream firstRoundStream = new MemoryStream(value); + byte[] firstRoundValue = await algorithm.ComputeHashAsync(firstRoundStream); - await using Stream secondRoundStream = new MemoryStream(firstRoundValue); - byte[] secondRoundValue = await algorithm.ComputeHashAsync(secondRoundStream); + await using Stream secondRoundStream = new MemoryStream(firstRoundValue); + byte[] secondRoundValue = await algorithm.ComputeHashAsync(secondRoundStream); - return FromByteArray(secondRoundValue, type); - } + return FromByteArray(secondRoundValue, type); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Concantenate.cs b/OnixLabs.Security.Cryptography/Hash.Concantenate.cs index 5ea4d5b..05163bf 100644 --- a/OnixLabs.Security.Cryptography/Hash.Concantenate.cs +++ b/OnixLabs.Security.Cryptography/Hash.Concantenate.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,69 +15,64 @@ using System; using System.Linq; using System.Security.Cryptography; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Concatenates two hashes. + /// + /// The first to concatenate. + /// The second to concatenate. + /// Returns the concatenation of the two instances. + public static Hash Concatenate(Hash a, Hash b) { - /// - /// Concatenates two hashes. - /// - /// The first to concatenate. - /// The second to concatenate. - /// Returns the concatenation of the two instances. - public static Hash Concatenate(Hash a, Hash b) - { - if (a.AlgorithmType != b.AlgorithmType) - { - throw new ArgumentException("Cannot concatenate hashes of different algorithm types."); - } + Check(a.AlgorithmType == b.AlgorithmType, "Cannot concatenate hashes of different algorithm types."); + + using HashAlgorithm algorithm = a.AlgorithmType.GetHashAlgorithm(); + byte[] concatenatedValue = a.ToByteArray().Concat(b.ToByteArray()).ToArray(); + byte[] hashedValue = algorithm.ComputeHash(concatenatedValue); - using HashAlgorithm algorithm = a.AlgorithmType.GetHashAlgorithm(); - byte[] concatenatedValue = a.ToByteArray().Concat(b.ToByteArray()).ToArray(); - byte[] hashedValue = algorithm.ComputeHash(concatenatedValue); - return FromByteArray(hashedValue, a.AlgorithmType); - } + return FromByteArray(hashedValue, a.AlgorithmType); + } - /// - /// Concatenates two hashes. - /// - /// The first to concatenate. - /// The second to concatenate. - /// The length of the hash in bytes. - /// Returns the concatenation of the two instances. - public static Hash Concatenate(Hash a, Hash b, int length) - { - if (a.AlgorithmType != b.AlgorithmType) - { - throw new ArgumentException("Cannot concatenate hashes of different algorithm types."); - } + /// + /// Concatenates two hashes. + /// + /// The first to concatenate. + /// The second to concatenate. + /// The length of the hash in bytes. + /// Returns the concatenation of the two instances. + public static Hash Concatenate(Hash a, Hash b, int length) + { + Check(a.AlgorithmType == b.AlgorithmType, "Cannot concatenate hashes of different algorithm types."); - using HashAlgorithm algorithm = a.AlgorithmType.GetHashAlgorithm(length); - byte[] concatenatedValue = a.ToByteArray().Concat(b.ToByteArray()).ToArray(); - byte[] hashedValue = algorithm.ComputeHash(concatenatedValue); - return FromByteArray(hashedValue, a.AlgorithmType); - } + using HashAlgorithm algorithm = a.AlgorithmType.GetHashAlgorithm(length); + byte[] concatenatedValue = a.ToByteArray().Concat(b.ToByteArray()).ToArray(); + byte[] hashedValue = algorithm.ComputeHash(concatenatedValue); + return FromByteArray(hashedValue, a.AlgorithmType); + } - /// - /// Concatenates this hash with another hash. - /// - /// The other hash to concatenate with this hash. - /// Returns the concatenation of the two instances. - public Hash Concatenate(Hash other) - { - return Concatenate(this, other); - } + /// + /// Concatenates this hash with another hash. + /// + /// The other hash to concatenate with this hash. + /// Returns the concatenation of the two instances. + public Hash Concatenate(Hash other) + { + return Concatenate(this, other); + } - /// - /// Concatenates this hash with another hash. - /// - /// The other hash to concatenate with this hash. - /// The length of the hash in bytes. - /// Returns the concatenation of the two instances. - public Hash Concatenate(Hash other, int length) - { - return Concatenate(this, other, length); - } + /// + /// Concatenates this hash with another hash. + /// + /// The other hash to concatenate with this hash. + /// The length of the hash in bytes. + /// Returns the concatenation of the two instances. + public Hash Concatenate(Hash other, int length) + { + return Concatenate(this, other, length); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Empty.cs b/OnixLabs.Security.Cryptography/Hash.Empty.cs index 01023ed..b5bb1a1 100644 --- a/OnixLabs.Security.Cryptography/Hash.Empty.cs +++ b/OnixLabs.Security.Cryptography/Hash.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash - { - /// - /// Gets an empty hash value. - /// - public static readonly Hash Empty; + /// + /// Gets an empty hash value. + /// + public static readonly Hash Empty; - /// - /// Initializes static members of the class. - /// - static Hash() - { - Empty = FromByteArray(Array.Empty(), HashAlgorithmType.Unknown); - } + /// + /// Initializes static members of the class. + /// + static Hash() + { + Empty = FromByteArray(Array.Empty(), HashAlgorithmType.Unknown); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Equatable.cs b/OnixLabs.Security.Cryptography/Hash.Equatable.cs index 50bd659..14b77dc 100644 --- a/OnixLabs.Security.Cryptography/Hash.Equatable.cs +++ b/OnixLabs.Security.Cryptography/Hash.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,60 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash : IEquatable { - public readonly partial struct Hash : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Hash a, Hash b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Hash a, Hash b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Hash a, Hash b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Hash a, Hash b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Hash other) - { - return other.AlgorithmType == AlgorithmType - && other.Value.SequenceEqual(Value); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Hash other) + { + return other.AlgorithmType == AlgorithmType && other.Value.SequenceEqual(Value); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Hash other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Hash other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(AlgorithmType, Value.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(AlgorithmType, Value.GetContentHashCode()); } } diff --git a/OnixLabs.Security.Cryptography/Hash.From.cs b/OnixLabs.Security.Cryptography/Hash.From.cs index eb3948d..7dec22c 100644 --- a/OnixLabs.Security.Cryptography/Hash.From.cs +++ b/OnixLabs.Security.Cryptography/Hash.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,74 +14,73 @@ using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Creates a instance from a array. + /// This will create a hash of an unknown type. + /// + /// The array to represent as a hash. + /// A new instance. + public static Hash FromByteArray(byte[] value) { - /// - /// Creates a instance from a array. - /// This will create a hash of an unknown type. - /// - /// The array to represent as a hash. - /// A new instance. - public static Hash FromByteArray(byte[] value) - { - return FromByteArray(value, HashAlgorithmType.Unknown); - } + return FromByteArray(value, HashAlgorithmType.Unknown); + } - /// - /// Creates a instance from a array. - /// - /// The array to represent as a hash. - /// The hash algorithm type of the hash. - /// A new instance. - public static Hash FromByteArray(byte[] value, HashAlgorithmType type) - { - return new Hash(value, type); - } + /// + /// Creates a instance from a array. + /// + /// The array to represent as a hash. + /// The hash algorithm type of the hash. + /// A new instance. + public static Hash FromByteArray(byte[] value, HashAlgorithmType type) + { + return new Hash(value, type); + } - /// - /// Creates a from the specified value. - /// - /// The Base-16 from which to construct a hash value. - /// Returns an from the specified Base-16 value. - public static Hash FromBase16(Base16 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-16 from which to construct a hash value. + /// Returns an from the specified Base-16 value. + public static Hash FromBase16(Base16 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-32 from which to construct a hash value. - /// Returns an from the specified Base-32 value. - public static Hash FromBase32(Base32 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-32 from which to construct a hash value. + /// Returns an from the specified Base-32 value. + public static Hash FromBase32(Base32 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-58 from which to construct a hash value. - /// Returns an from the specified Base-58 value. - public static Hash FromBase58(Base58 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-58 from which to construct a hash value. + /// Returns an from the specified Base-58 value. + public static Hash FromBase58(Base58 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); + } - /// - /// Creates a from the specified value. - /// - /// The Base-64 from which to construct a hash value. - /// Returns an from the specified Base-64 value. - public static Hash FromBase64(Base64 value) - { - byte[] bytes = value.ToByteArray(); - return FromByteArray(bytes); - } + /// + /// Creates a from the specified value. + /// + /// The Base-64 from which to construct a hash value. + /// Returns an from the specified Base-64 value. + public static Hash FromBase64(Base64 value) + { + byte[] bytes = value.ToByteArray(); + return FromByteArray(bytes); } } diff --git a/OnixLabs.Security.Cryptography/Hash.Parse.cs b/OnixLabs.Security.Cryptography/Hash.Parse.cs index 7e1976a..0806815 100644 --- a/OnixLabs.Security.Cryptography/Hash.Parse.cs +++ b/OnixLabs.Security.Cryptography/Hash.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,86 +15,85 @@ using System; using OnixLabs.Core; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Parses a hexadecimal representation of a hash into a instance. + /// + /// A that contains a hash to convert. + /// The hash algorithm type of the hash. + /// A new instance. + public static Hash Parse(string value, HashAlgorithmType? type = null) { - /// - /// Parses a hexadecimal representation of a hash into a instance. - /// - /// A that contains a hash to convert. - /// The hash algorithm type of the hash. - /// A new instance. - public static Hash Parse(string value, HashAlgorithmType? type = null) - { - HashAlgorithmType parsedType = GetParsedHashAlgorithmType(value); - byte[] parsedValue = GetParsedHashValue(value); - - if (type is not null) - { - CheckMatchingHashAlgorithms(parsedType, type); - } - - return FromByteArray(parsedValue, parsedType); - } + HashAlgorithmType parsedType = GetParsedHashAlgorithmType(value); + byte[] parsedValue = GetParsedHashValue(value); - /// - /// Attempts to parse a hexadecimal representation of a hash into a instance. - /// - /// A that contains a hash to convert. - /// The hash algorithm type of the hash. - /// The result if conversion was successful. - /// Returns true if the hash conversion was successful; otherwise, false. - public static bool TryParse(string value, HashAlgorithmType? type, out Hash hash) + if (type is not null) { - try - { - hash = Parse(value, type); - return true; - } - catch - { - hash = default; - return false; - } + CheckMatchingHashAlgorithms(parsedType, type); } - /// - /// Parses a from the specified value. - /// - /// The hash value to parse. - /// Returns a from the specified value. - private static HashAlgorithmType GetParsedHashAlgorithmType(string value) + return FromByteArray(parsedValue, parsedType); + } + + /// + /// Attempts to parse a hexadecimal representation of a hash into a instance. + /// + /// A that contains a hash to convert. + /// The hash algorithm type of the hash. + /// The result if conversion was successful. + /// Returns true if the hash conversion was successful; otherwise, false. + public static bool TryParse(string value, HashAlgorithmType? type, out Hash hash) + { + try { - string defaultHashAlgorithmType = HashAlgorithmType.Unknown.Name; - string parsedType = value.SubstringBefore(':', defaultHashAlgorithmType); - return HashAlgorithmType.FromName(parsedType); + hash = Parse(value, type); + return true; } - - /// - /// Parses a array from the specified value. - /// - /// The hash value to parse. - /// Returns a array from the specified value. - private static byte[] GetParsedHashValue(string value) + catch { - string parsedValue = value.SubstringAfter(':'); - return Convert.FromHexString(parsedValue); + hash = default; + return false; } + } + + /// + /// Parses a from the specified value. + /// + /// The hash value to parse. + /// Returns a from the specified value. + private static HashAlgorithmType GetParsedHashAlgorithmType(string value) + { + string defaultHashAlgorithmType = HashAlgorithmType.Unknown.Name; + string parsedType = value.SubstringBefore(':', defaultHashAlgorithmType); + return HashAlgorithmType.FromName(parsedType); + } - /// - /// Checks that the parsed and specified instances match. - /// - /// The parsed to check. - /// The specified to check. - /// If the instances do not match. - private static void CheckMatchingHashAlgorithms(HashAlgorithmType parsed, HashAlgorithmType specified) + /// + /// Parses a array from the specified value. + /// + /// The hash value to parse. + /// Returns a array from the specified value. + private static byte[] GetParsedHashValue(string value) + { + string parsedValue = value.SubstringAfter(':'); + return Convert.FromHexString(parsedValue); + } + + /// + /// Checks that the parsed and specified instances match. + /// + /// The parsed to check. + /// The specified to check. + /// If the instances do not match. + private static void CheckMatchingHashAlgorithms(HashAlgorithmType parsed, HashAlgorithmType specified) + { + if (parsed != specified) { - if (parsed != specified) - { - throw new InvalidOperationException( - $"The parsed hash algorithm type '{parsed}' does not match the expected hash algorithm type '{specified}'."); - } + throw new InvalidOperationException( + $"The parsed hash algorithm type '{parsed}' does not match the expected hash algorithm type '{specified}'."); } } } diff --git a/OnixLabs.Security.Cryptography/Hash.To.cs b/OnixLabs.Security.Cryptography/Hash.To.cs index 1b9cfbc..f086e86 100644 --- a/OnixLabs.Security.Cryptography/Hash.To.cs +++ b/OnixLabs.Security.Cryptography/Hash.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,91 +16,90 @@ using OnixLabs.Core; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hash { - public readonly partial struct Hash + /// + /// Returns a array containing the underlying hash data. + /// + /// A array containing the underlying hash data. + public byte[] ToByteArray() { - /// - /// Returns a array containing the underlying hash data. - /// - /// A array containing the underlying hash data. - public byte[] ToByteArray() - { - return Value.Copy(); - } + return Value.Copy(); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// Returns a value that represents the underlying hash data. - public Base16 ToBase16() - { - return Base16.FromByteArray(Value); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// Returns a value that represents the underlying hash data. + public Base16 ToBase16() + { + return Base16.FromByteArray(Value); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// Returns a value that represents the underlying hash data. - public Base32 ToBase32() - { - return ToBase32(Base32Alphabet.Default); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// Returns a value that represents the underlying hash data. + public Base32 ToBase32() + { + return ToBase32(Base32Alphabet.Default); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// The Base-32 alphabet to use to encode the hash data. - /// Returns a value that represents the underlying hash data. - public Base32 ToBase32(Base32Alphabet alphabet) - { - return Base32.FromByteArray(Value, alphabet); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// The Base-32 alphabet to use to encode the hash data. + /// Returns a value that represents the underlying hash data. + public Base32 ToBase32(Base32Alphabet alphabet) + { + return Base32.FromByteArray(Value, alphabet); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// Returns a value that represents the underlying hash data. - public Base58 ToBase58() - { - return ToBase58(Base58Alphabet.Default); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// Returns a value that represents the underlying hash data. + public Base58 ToBase58() + { + return ToBase58(Base58Alphabet.Default); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// The Base-58 alphabet to use to encode the hash data. - /// Returns a value that represents the underlying hash data. - public Base58 ToBase58(Base58Alphabet alphabet) - { - return Base58.FromByteArray(Value, alphabet); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// The Base-58 alphabet to use to encode the hash data. + /// Returns a value that represents the underlying hash data. + public Base58 ToBase58(Base58Alphabet alphabet) + { + return Base58.FromByteArray(Value, alphabet); + } - /// - /// Returns a value that represents the underlying hash data. - /// - /// Returns a value that represents the underlying hash data. - public Base64 ToBase64() - { - return Base64.FromByteArray(Value); - } + /// + /// Returns a value that represents the underlying hash data. + /// + /// Returns a value that represents the underlying hash data. + public Base64 ToBase64() + { + return Base64.FromByteArray(Value); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToHexString(Value).ToLower(); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToHexString(Value).ToLower(); + } - /// - /// Returns a that represents the current object, including the hash algorithm type. - /// - /// A that represents the current object, including the hash algorithm type. - public string ToStringWithAlgorithmType() - { - return $"{AlgorithmType.Name}:{ToString()}"; - } + /// + /// Returns a that represents the current object, including the hash algorithm type. + /// + /// A that represents the current object, including the hash algorithm type. + public string ToStringWithAlgorithmType() + { + return $"{AlgorithmType.Name}:{ToString()}"; } } diff --git a/OnixLabs.Security.Cryptography/Hash.cs b/OnixLabs.Security.Cryptography/Hash.cs index c97952c..fe2903a 100644 --- a/OnixLabs.Security.Cryptography/Hash.cs +++ b/OnixLabs.Security.Cryptography/Hash.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,34 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a cryptographic hash. +/// +public readonly partial struct Hash { /// - /// Represents a cryptographic hash. + /// Initializes a new instance of the struct. /// - public readonly partial struct Hash + /// The underlying hexadecimal value of the hash. + /// The hash algorithm type of the hash. + private Hash(byte[] value, HashAlgorithmType type) { - /// - /// Initializes a new instance of the struct. - /// - /// The underlying hexadecimal value of the hash. - /// The hash algorithm type of the hash. - private Hash(byte[] value, HashAlgorithmType type) - { - type.VerifyHashLength(value); + type.VerifyHashLength(value); - AlgorithmType = type; - Value = value; - } + AlgorithmType = type; + Value = value; + } - /// - /// Gets the hash algorithm type of the hash. - /// - public HashAlgorithmType AlgorithmType { get; } + /// + /// Gets the hash algorithm type of the hash. + /// + public HashAlgorithmType AlgorithmType { get; } - /// - /// Gets the underlying value of the hash. - /// - private byte[] Value { get; } - } + /// + /// Gets the underlying value of the hash. + /// + private byte[] Value { get; } } diff --git a/OnixLabs.Security.Cryptography/HashAlgorithmType.Enumerations.cs b/OnixLabs.Security.Cryptography/HashAlgorithmType.Enumerations.cs index ecd33d4..a359816 100644 --- a/OnixLabs.Security.Cryptography/HashAlgorithmType.Enumerations.cs +++ b/OnixLabs.Security.Cryptography/HashAlgorithmType.Enumerations.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,93 +12,92 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class HashAlgorithmType { - public sealed partial class HashAlgorithmType - { - /// - /// An unknown hash algorithm. - /// - public static readonly HashAlgorithmType Unknown = new(0, nameof(Unknown), UnknownLength, false); - - /// - /// The MD5 hash algorithm. - /// - public static readonly HashAlgorithmType Md5Hash = new(1, nameof(Md5Hash), 16, false); - - /// - /// The SHA-1 hash algorithm. - /// - public static readonly HashAlgorithmType Sha1Hash = new(2, nameof(Sha1Hash), 20, false); - - /// - /// The SHA-2 256-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hash256 = new(3, nameof(Sha2Hash256), 32, false); - - /// - /// The SHA-2 384-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hash384 = new(4, nameof(Sha2Hash384), 48, false); - - /// - /// The SHA-2 512-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hash512 = new(5, nameof(Sha2Hash512), 64, false); - - /// - /// The SHA-3 224-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Hash224 = new(6, nameof(Sha3Hash224), 28, false); - - /// - /// The SHA-3 256-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Hash256 = new(7, nameof(Sha3Hash256), 32, false); - - /// - /// The SHA-3 384-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Hash384 = new(8, nameof(Sha3Hash384), 48, false); - - /// - /// The SHA-3 512-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Hash512 = new(9, nameof(Sha3Hash512), 64, false); - - /// - /// The SHA-3 Shake 128-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Shake128 = new(10, nameof(Sha3Shake128), UnknownLength, false); - - /// - /// The SHA-3 Shake 256-bit hash algorithm. - /// - public static readonly HashAlgorithmType Sha3Shake256 = new(11, nameof(Sha3Shake256), UnknownLength, false); - - /// - /// The MD5 HMAC keyed hash algorithm. - /// - public static readonly HashAlgorithmType Md5Hmac = new(12, nameof(Md5Hmac), 16, true); - - /// - /// The SHA-1 HMAC keyed hash algorithm. - /// - public static readonly HashAlgorithmType Sha1Hmac = new(13, nameof(Sha1Hmac), 20, true); - - /// - /// The SHA-2 256-bit HMAC keyed hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hmac256 = new(14, nameof(Sha2Hmac256), 32, true); - - /// - /// The SHA-2 384-bit HMAC keyed hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hmac384 = new(15, nameof(Sha2Hmac384), 48, true); - - /// - /// The SHA-2 512-bit HMAC keyed hash algorithm. - /// - public static readonly HashAlgorithmType Sha2Hmac512 = new(16, nameof(Sha2Hmac512), 64, true); - } + /// + /// An unknown hash algorithm. + /// + public static readonly HashAlgorithmType Unknown = new(0, nameof(Unknown), UnknownLength, false); + + /// + /// The MD5 hash algorithm. + /// + public static readonly HashAlgorithmType Md5Hash = new(1, nameof(Md5Hash), 16, false); + + /// + /// The SHA-1 hash algorithm. + /// + public static readonly HashAlgorithmType Sha1Hash = new(2, nameof(Sha1Hash), 20, false); + + /// + /// The SHA-2 256-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hash256 = new(3, nameof(Sha2Hash256), 32, false); + + /// + /// The SHA-2 384-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hash384 = new(4, nameof(Sha2Hash384), 48, false); + + /// + /// The SHA-2 512-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hash512 = new(5, nameof(Sha2Hash512), 64, false); + + /// + /// The SHA-3 224-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Hash224 = new(6, nameof(Sha3Hash224), 28, false); + + /// + /// The SHA-3 256-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Hash256 = new(7, nameof(Sha3Hash256), 32, false); + + /// + /// The SHA-3 384-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Hash384 = new(8, nameof(Sha3Hash384), 48, false); + + /// + /// The SHA-3 512-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Hash512 = new(9, nameof(Sha3Hash512), 64, false); + + /// + /// The SHA-3 Shake 128-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Shake128 = new(10, nameof(Sha3Shake128), UnknownLength, false); + + /// + /// The SHA-3 Shake 256-bit hash algorithm. + /// + public static readonly HashAlgorithmType Sha3Shake256 = new(11, nameof(Sha3Shake256), UnknownLength, false); + + /// + /// The MD5 HMAC keyed hash algorithm. + /// + public static readonly HashAlgorithmType Md5Hmac = new(12, nameof(Md5Hmac), 16, true); + + /// + /// The SHA-1 HMAC keyed hash algorithm. + /// + public static readonly HashAlgorithmType Sha1Hmac = new(13, nameof(Sha1Hmac), 20, true); + + /// + /// The SHA-2 256-bit HMAC keyed hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hmac256 = new(14, nameof(Sha2Hmac256), 32, true); + + /// + /// The SHA-2 384-bit HMAC keyed hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hmac384 = new(15, nameof(Sha2Hmac384), 48, true); + + /// + /// The SHA-2 512-bit HMAC keyed hash algorithm. + /// + public static readonly HashAlgorithmType Sha2Hmac512 = new(16, nameof(Sha2Hmac512), 64, true); } diff --git a/OnixLabs.Security.Cryptography/HashAlgorithmType.Equatable.cs b/OnixLabs.Security.Cryptography/HashAlgorithmType.Equatable.cs deleted file mode 100644 index 9cfa1de..0000000 --- a/OnixLabs.Security.Cryptography/HashAlgorithmType.Equatable.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020-2021 ONIXLabs -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace OnixLabs.Security.Cryptography -{ - public sealed partial class HashAlgorithmType - { - /// - /// Checks for equality between this and another . - /// This will return false if either this, or the other is . - /// - /// The object to check for equality. - /// - /// Returns true if this is equal to the other; otherwise, false. - /// If either is , this always returns false. - /// - public override bool Equals(HashAlgorithmType? other) - { - return !ReferenceEquals(this, Unknown) - && !ReferenceEquals(other, Unknown) - && base.Equals(other); - } - } -} diff --git a/OnixLabs.Security.Cryptography/HashAlgorithmType.Get.cs b/OnixLabs.Security.Cryptography/HashAlgorithmType.Get.cs index 90e5dd8..e8de590 100644 --- a/OnixLabs.Security.Cryptography/HashAlgorithmType.Get.cs +++ b/OnixLabs.Security.Cryptography/HashAlgorithmType.Get.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,82 +14,85 @@ using System; using System.Security.Cryptography; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class HashAlgorithmType { - public sealed partial class HashAlgorithmType + /// + /// Gets the hash algorithm for this instance. + /// + /// Returns a for this . + public HashAlgorithm GetHashAlgorithm() { - /// - /// Gets the hash algorithm for this instance. - /// - /// Specifies the expected output hash length. - /// Returns a for this . - /// If the hash algorithm does not expect an output length. - /// If the hash algorithm is unknown. - public HashAlgorithm GetHashAlgorithm(int length = UnknownLength) - { - if (length != UnknownLength && Length > UnknownLength) - { - throw new ArgumentException($"Output length not expected for the specified hash algorithm: {Name}"); - } + return GetHashAlgorithm(Length); + } - return Name switch - { - nameof(Md5Hash) => MD5.Create(), - nameof(Sha1Hash) => SHA1.Create(), - nameof(Sha2Hash256) => SHA256.Create(), - nameof(Sha2Hash384) => SHA384.Create(), - nameof(Sha2Hash512) => SHA512.Create(), - nameof(Sha3Hash224) => Sha3.CreateSha3Hash224(), - nameof(Sha3Hash256) => Sha3.CreateSha3Hash256(), - nameof(Sha3Hash384) => Sha3.CreateSha3Hash384(), - nameof(Sha3Hash512) => Sha3.CreateSha3Hash512(), - nameof(Sha3Shake128) => Sha3.CreateSha3Shake128(length), - nameof(Sha3Shake256) => Sha3.CreateSha3Shake256(length), - _ => throw new ArgumentException($"Hash algorithm '{Name}' is unknown.") - }; - } + /// + /// Gets the hash algorithm for this instance. + /// + /// Specifies the expected output hash length. + /// Returns a for this . + /// If the hash algorithm does not expect an output length. + /// If the hash algorithm is unknown. + public HashAlgorithm GetHashAlgorithm(int length) + { + Check(IsUnknown || length == Length, $"Output length not expected for the specified hash algorithm: {Name}"); - /// - /// Gets the keyed hash algorithm for this instance. - /// - /// The key that should be used by the keyed hash algorithm. - /// Returns a for this . - /// If the hash algorithm is unknown or is not a keyed hash algorithm. - public KeyedHashAlgorithm GetKeyedHashAlgorithm(byte[]? key = null) + return Name switch { - if (!Keyed) - { - throw new ArgumentException($"Hash algorithm type '{Name}' is not a keyed hash algorithm."); - } + nameof(Md5Hash) => MD5.Create(), + nameof(Sha1Hash) => SHA1.Create(), + nameof(Sha2Hash256) => SHA256.Create(), + nameof(Sha2Hash384) => SHA384.Create(), + nameof(Sha2Hash512) => SHA512.Create(), + nameof(Sha3Hash224) => Sha3.CreateSha3Hash224(), + nameof(Sha3Hash256) => Sha3.CreateSha3Hash256(), + nameof(Sha3Hash384) => Sha3.CreateSha3Hash384(), + nameof(Sha3Hash512) => Sha3.CreateSha3Hash512(), + nameof(Sha3Shake128) => Sha3.CreateSha3Shake128(length), + nameof(Sha3Shake256) => Sha3.CreateSha3Shake256(length), + _ => throw new ArgumentException($"Hash algorithm '{Name}' is unknown.") + }; + } - return Name switch - { - nameof(Md5Hmac) => key is null ? new HMACMD5() : new HMACMD5(key), - nameof(Sha1Hmac) => key is null ? new HMACSHA1() : new HMACSHA1(key), - nameof(Sha2Hmac256) => key is null ? new HMACSHA256() : new HMACSHA256(key), - nameof(Sha2Hmac384) => key is null ? new HMACSHA384() : new HMACSHA384(key), - nameof(Sha2Hmac512) => key is null ? new HMACSHA512() : new HMACSHA512(key), - _ => throw new ArgumentException($"Hash algorithm '{Name}' is unknown.") - }; - } + /// + /// Gets the keyed hash algorithm for this instance. + /// + /// The key that should be used by the keyed hash algorithm. + /// Returns a for this . + /// If the hash algorithm is unknown or is not a keyed hash algorithm. + public KeyedHashAlgorithm GetKeyedHashAlgorithm(byte[]? key = null) + { + Check(IsKeyBased, $"Hash algorithm type '{Name}' is not a keyed hash algorithm."); - /// - /// Gets the equivalent for this . - /// - /// Returns the equivalent for this . - /// If there is no corresponding equivalent for this . - public HashAlgorithmName GetHashAlgorithmName() + return Name switch + { + nameof(Md5Hmac) => key is null ? new HMACMD5() : new HMACMD5(key), + nameof(Sha1Hmac) => key is null ? new HMACSHA1() : new HMACSHA1(key), + nameof(Sha2Hmac256) => key is null ? new HMACSHA256() : new HMACSHA256(key), + nameof(Sha2Hmac384) => key is null ? new HMACSHA384() : new HMACSHA384(key), + nameof(Sha2Hmac512) => key is null ? new HMACSHA512() : new HMACSHA512(key), + _ => throw new ArgumentException($"Hash algorithm '{Name}' is unknown.") + }; + } + + /// + /// Gets the equivalent for this . + /// + /// Returns the equivalent for this . + /// If there is no corresponding equivalent for this . + public HashAlgorithmName GetHashAlgorithmName() + { + return Name switch { - return Name switch - { - nameof(Md5Hash) => HashAlgorithmName.MD5, - nameof(Sha1Hash) => HashAlgorithmName.SHA1, - nameof(Sha2Hash256) => HashAlgorithmName.SHA256, - nameof(Sha2Hash384) => HashAlgorithmName.SHA384, - nameof(Sha2Hash512) => HashAlgorithmName.SHA512, - _ => throw new ArgumentException($"No corresponding {nameof(HashAlgorithmName)} for '{Name}'.") - }; - } + nameof(Md5Hash) => HashAlgorithmName.MD5, + nameof(Sha1Hash) => HashAlgorithmName.SHA1, + nameof(Sha2Hash256) => HashAlgorithmName.SHA256, + nameof(Sha2Hash384) => HashAlgorithmName.SHA384, + nameof(Sha2Hash512) => HashAlgorithmName.SHA512, + _ => throw new ArgumentException($"No corresponding {nameof(HashAlgorithmName)} for '{Name}'.") + }; } } diff --git a/OnixLabs.Security.Cryptography/HashAlgorithmType.Verify.cs b/OnixLabs.Security.Cryptography/HashAlgorithmType.Verify.cs index e01d99a..21065a7 100644 --- a/OnixLabs.Security.Cryptography/HashAlgorithmType.Verify.cs +++ b/OnixLabs.Security.Cryptography/HashAlgorithmType.Verify.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,32 +13,29 @@ // limitations under the License. using System; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class HashAlgorithmType { - public sealed partial class HashAlgorithmType + /// + /// Determines whether the length of a byte array is valid. + /// + /// The byte array to length check. + /// Returns true if the length of the byte array is valid; otherwise, false. + public bool IsValidHashLength(byte[] value) { - /// - /// Determines whether the length of a byte array is valid. - /// - /// The byte array to length check. - /// Returns true if the length of the byte array is valid; otherwise, false. - public bool IsValidHashLength(byte[] value) - { - return Length == -1 || Length == value.Length; - } + return Length == -1 || Length == value.Length; + } - /// - /// Verifies that the length of a byte array is valid. - /// - /// The byte array to length check. - /// If the length of the byte array is invalid. - public void VerifyHashLength(byte[] value) - { - if (!IsValidHashLength(value)) - { - throw new ArgumentException("The length of the hash is invalid.", nameof(value)); - } - } + /// + /// Verifies that the length of a byte array is valid. + /// + /// The byte array to length check. + /// If the length of the byte array is invalid. + public void VerifyHashLength(byte[] value) + { + Check(IsValidHashLength(value), "The length of the hash is invalid.", nameof(value)); } } diff --git a/OnixLabs.Security.Cryptography/HashAlgorithmType.cs b/OnixLabs.Security.Cryptography/HashAlgorithmType.cs index 20645f4..ada1def 100644 --- a/OnixLabs.Security.Cryptography/HashAlgorithmType.cs +++ b/OnixLabs.Security.Cryptography/HashAlgorithmType.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,44 @@ using OnixLabs.Core; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Specifies values that define known hash algorithm types. +/// +public sealed partial class HashAlgorithmType : Enumeration { /// - /// Specifies values that define known hash algorithm types. + /// A constant that defines an unknown hash algorithm length. + /// + private const int UnknownLength = -1; + + /// + /// Initializes a new instance of the class. /// - public sealed partial class HashAlgorithmType : Enumeration + /// The value of the hash algorithm type. + /// The name of the hash algorithm type. + /// The length in bytes of the hash algorithm type. + /// Determines whether the algorithm is a key based hash algorithm. + private HashAlgorithmType(int value, string name, int length, bool isKeyBased) : base(value, name) { - /// - /// A constant that defines an unknown hash algorithm length. - /// - public const int UnknownLength = -1; + Length = length; + IsKeyBased = isKeyBased; + } - /// - /// Initializes a new instance of the class. - /// - /// The value of the hash algorithm type. - /// The name of the hash algorithm type. - /// The length in bytes of the hash algorithm type. - /// Determines whether the algorithm is a keyed hash algorithm. - private HashAlgorithmType(int value, string name, int length, bool keyed) : base(value, name) - { - Length = length; - Keyed = keyed; - } + /// + /// Gets the length of an algorithm's hash in bytes. + /// -1 Means that the algorithm's hash is of variable length, or is unknown. + /// + public int Length { get; } - /// - /// Gets the length of an algorithm's hash in bytes. - /// -1 Means that the algorithm's hash is of variable length, or is unknown. - /// - public int Length { get; } + /// + /// Gets a value that determines whether the algorithm is a key based hash algorithm. + /// + public bool IsKeyBased { get; } - /// - /// Gets a value that determines whether the algorithm is a keyed hash algorithm. - /// - public bool Keyed { get; } - } + /// + /// Gets a value that determines whether the algorithm type is unknown. + /// + public bool IsUnknown => ReferenceEquals(this, Unknown); } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.Md5Hmac.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.Md5Hmac.cs index e1f8981..d1cf46f 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.Md5Hmac.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.Md5Hmac.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,46 +14,45 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes an MD5 HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeMd5Hmac(string value, string key) { - /// - /// Computes an MD5 HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeMd5Hmac(string value, string key) - { - return ComputeMd5Hmac(value, key, Encoding.Default); - } + return ComputeMd5Hmac(value, key, Encoding.Default); + } - /// - /// Computes an MD5 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static Hmac ComputeMd5Hmac(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes an MD5 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static Hmac ComputeMd5Hmac(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeMd5Hmac(valueBytes, keyBytes); - } + return ComputeMd5Hmac(valueBytes, keyBytes); + } - /// - /// Computes an MD5 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeMd5Hmac(byte[] value, byte[] key) - { - return ComputeHmac(value, key, HashAlgorithmType.Md5Hmac); - } + /// + /// Computes an MD5 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeMd5Hmac(byte[] value, byte[] key) + { + return ComputeHmac(value, key, HashAlgorithmType.Md5Hmac); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha1Hmac.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha1Hmac.cs index ae5aa0e..5c63312 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha1Hmac.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha1Hmac.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,46 +14,45 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha1Hmac(string value, string key) { - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha1Hmac(string value, string key) - { - return ComputeSha1Hmac(value, key, Encoding.Default); - } + return ComputeSha1Hmac(value, key, Encoding.Default); + } - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static Hmac ComputeSha1Hmac(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static Hmac ComputeSha1Hmac(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeSha1Hmac(valueBytes, keyBytes); - } + return ComputeSha1Hmac(valueBytes, keyBytes); + } - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha1Hmac(byte[] value, byte[] key) - { - return ComputeHmac(value, key, HashAlgorithmType.Sha1Hmac); - } + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha1Hmac(byte[] value, byte[] key) + { + return ComputeHmac(value, key, HashAlgorithmType.Sha1Hmac); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac256.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac256.cs index 8e6f856..d936676 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac256.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,46 +14,45 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac256(string value, string key) { - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac256(string value, string key) - { - return ComputeSha2Hmac256(value, key, Encoding.Default); - } + return ComputeSha2Hmac256(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac256(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac256(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeSha2Hmac256(valueBytes, keyBytes); - } + return ComputeSha2Hmac256(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac256(byte[] value, byte[] key) - { - return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac256); - } + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac256(byte[] value, byte[] key) + { + return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac256); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac384.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac384.cs index aa291df..c05966d 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac384.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,46 +14,45 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac384(string value, string key) { - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac384(string value, string key) - { - return ComputeSha2Hmac384(value, key, Encoding.Default); - } + return ComputeSha2Hmac384(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac384(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac384(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeSha2Hmac384(valueBytes, keyBytes); - } + return ComputeSha2Hmac384(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac384(byte[] value, byte[] key) - { - return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac384); - } + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac384(byte[] value, byte[] key) + { + return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac384); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac512.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac512.cs index 695c9c4..b390832 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac512.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.Sha2Hmac512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,46 +14,45 @@ using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac512(string value, string key) { - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac512(string value, string key) - { - return ComputeSha2Hmac512(value, key, Encoding.Default); - } + return ComputeSha2Hmac512(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac512(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac512(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeSha2Hmac512(valueBytes, keyBytes); - } + return ComputeSha2Hmac512(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static Hmac ComputeSha2Hmac512(byte[] value, byte[] key) - { - return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac512); - } + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static Hmac ComputeSha2Hmac512(byte[] value, byte[] key) + { + return ComputeHmac(value, key, HashAlgorithmType.Sha2Hmac512); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Compute.cs b/OnixLabs.Security.Cryptography/Hmac.Compute.cs index d449c16..1fc842f 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Compute.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Compute.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,53 +15,52 @@ using System.Security.Cryptography; using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// Returns a representing the specified value and key. + public static Hmac ComputeHmac(string value, string key, HashAlgorithmType type) { - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// Returns a representing the specified value and key. - public static Hmac ComputeHmac(string value, string key, HashAlgorithmType type) - { - return ComputeHmac(value, key, type, Encoding.Default); - } + return ComputeHmac(value, key, type, Encoding.Default); + } - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a representing the specified value and key. - public static Hmac ComputeHmac(string value, string key, HashAlgorithmType type, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a representing the specified value and key. + public static Hmac ComputeHmac(string value, string key, HashAlgorithmType type, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return ComputeHmac(valueBytes, keyBytes, type); - } + return ComputeHmac(valueBytes, keyBytes, type); + } - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// Returns a representing the specified value and key. - public static Hmac ComputeHmac(byte[] value, byte[] key, HashAlgorithmType type) - { - using KeyedHashAlgorithm algorithm = type.GetKeyedHashAlgorithm(key); + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// Returns a representing the specified value and key. + public static Hmac ComputeHmac(byte[] value, byte[] key, HashAlgorithmType type) + { + using KeyedHashAlgorithm algorithm = type.GetKeyedHashAlgorithm(key); - byte[] data = algorithm.ComputeHash(value); - Hash hash = Hash.FromByteArray(data, type); + byte[] data = algorithm.ComputeHash(value); + Hash hash = Hash.FromByteArray(data, type); - return Create(hash, value); - } + return Create(hash, value); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Md5Hmac.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Md5Hmac.cs index 81729f6..e246790 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Md5Hmac.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Md5Hmac.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes an MD5 HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeMd5HmacAsync(string value, string key) { - /// - /// Computes an MD5 HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeMd5HmacAsync(string value, string key) - { - return await ComputeMd5HmacAsync(value, key, Encoding.Default); - } + return await ComputeMd5HmacAsync(value, key, Encoding.Default); + } - /// - /// Computes an MD5 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static async Task ComputeMd5HmacAsync(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes an MD5 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static async Task ComputeMd5HmacAsync(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeMd5HmacAsync(valueBytes, keyBytes); - } + return await ComputeMd5HmacAsync(valueBytes, keyBytes); + } - /// - /// Computes an MD5 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeMd5HmacAsync(byte[] value, byte[] key) - { - return await ComputeHmacAsync(value, key, HashAlgorithmType.Md5Hmac); - } + /// + /// Computes an MD5 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeMd5HmacAsync(byte[] value, byte[] key) + { + return await ComputeHmacAsync(value, key, HashAlgorithmType.Md5Hmac); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha1Hmac.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha1Hmac.cs index 05e2620..46fb8d0 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha1Hmac.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha1Hmac.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha1HmacAsync(string value, string key) { - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha1HmacAsync(string value, string key) - { - return await ComputeSha1HmacAsync(value, key, Encoding.Default); - } + return await ComputeSha1HmacAsync(value, key, Encoding.Default); + } - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static async Task ComputeSha1HmacAsync(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static async Task ComputeSha1HmacAsync(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeSha1HmacAsync(valueBytes, keyBytes); - } + return await ComputeSha1HmacAsync(valueBytes, keyBytes); + } - /// - /// Computes a SHA-1 HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha1HmacAsync(byte[] value, byte[] key) - { - return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha1Hmac); - } + /// + /// Computes a SHA-1 HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha1HmacAsync(byte[] value, byte[] key) + { + return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha1Hmac); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac256.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac256.cs index fc61d18..43bf383 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac256.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac256Async(string value, string key) { - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac256Async(string value, string key) - { - return await ComputeSha2Hmac256Async(value, key, Encoding.Default); - } + return await ComputeSha2Hmac256Async(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac256Async(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac256Async(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeSha2Hmac256Async(valueBytes, keyBytes); - } + return await ComputeSha2Hmac256Async(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 256-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac256Async(byte[] value, byte[] key) - { - return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac256); - } + /// + /// Computes a SHA-2 256-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac256Async(byte[] value, byte[] key) + { + return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac256); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac384.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac384.cs index a651727..1bf5ad2 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac384.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac384Async(string value, string key) { - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac384Async(string value, string key) - { - return await ComputeSha2Hmac384Async(value, key, Encoding.Default); - } + return await ComputeSha2Hmac384Async(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac384Async(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac384Async(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeSha2Hmac384Async(valueBytes, keyBytes); - } + return await ComputeSha2Hmac384Async(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 384-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac384Async(byte[] value, byte[] key) - { - return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac384); - } + /// + /// Computes a SHA-2 384-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac384Async(byte[] value, byte[] key) + { + return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac384); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac512.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac512.cs index e730bc4..c2cc2ff 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac512.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.Sha2Hmac512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// This will use the default encoding to convert the input value and key into a byte array. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac512Async(string value, string key) { - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// This will use the default encoding to convert the input value and key into a byte array. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac512Async(string value, string key) - { - return await ComputeSha2Hmac512Async(value, key, Encoding.Default); - } + return await ComputeSha2Hmac512Async(value, key, Encoding.Default); + } - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac512Async(string value, string key, Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac512Async(string value, string key, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeSha2Hmac512Async(valueBytes, keyBytes); - } + return await ComputeSha2Hmac512Async(valueBytes, keyBytes); + } - /// - /// Computes a SHA-2 512-bit HMAC from the specified value and key. - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// Returns a of the input value and key. - public static async Task ComputeSha2Hmac512Async(byte[] value, byte[] key) - { - return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac512); - } + /// + /// Computes a SHA-2 512-bit HMAC from the specified value and key. + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// Returns a of the input value and key. + public static async Task ComputeSha2Hmac512Async(byte[] value, byte[] key) + { + return await ComputeHmacAsync(value, key, HashAlgorithmType.Sha2Hmac512); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.cs b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.cs index ec7937b..f09bf8b 100644 --- a/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.cs +++ b/OnixLabs.Security.Cryptography/Hmac.ComputeAsync.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,58 +17,53 @@ using System.Text; using System.Threading.Tasks; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// Returns a representing the specified value and key. + public static async Task ComputeHmacAsync(string value, string key, HashAlgorithmType type) { - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// Returns a representing the specified value and key. - public static async Task ComputeHmacAsync(string value, string key, HashAlgorithmType type) - { - return await ComputeHmacAsync(value, key, type, Encoding.Default); - } + return await ComputeHmacAsync(value, key, type, Encoding.Default); + } - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// The encoding which will be used to convert the value and key into a byte array. - /// Returns a representing the specified value and key. - public static async Task ComputeHmacAsync( - string value, - string key, - HashAlgorithmType type, - Encoding encoding) - { - byte[] valueBytes = encoding.GetBytes(value); - byte[] keyBytes = encoding.GetBytes(key); + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// The encoding which will be used to convert the value and key into a byte array. + /// Returns a representing the specified value and key. + public static async Task ComputeHmacAsync(string value, string key, HashAlgorithmType type, Encoding encoding) + { + byte[] valueBytes = encoding.GetBytes(value); + byte[] keyBytes = encoding.GetBytes(key); - return await ComputeHmacAsync(valueBytes, keyBytes, type); - } + return await ComputeHmacAsync(valueBytes, keyBytes, type); + } - /// - /// Computes a hashed message authentication code (HMAC). - /// - /// The value for which to compute a HMAC. - /// The key for which to compute a HMAC. - /// The hash algorithm type of the computed HMAC. - /// Returns a representing the specified value and key. - public static async Task ComputeHmacAsync(byte[] value, byte[] key, HashAlgorithmType type) - { - using KeyedHashAlgorithm algorithm = type.GetKeyedHashAlgorithm(key); - await using Stream stream = new MemoryStream(value); + /// + /// Computes a hashed message authentication code (HMAC). + /// + /// The value for which to compute a HMAC. + /// The key for which to compute a HMAC. + /// The hash algorithm type of the computed HMAC. + /// Returns a representing the specified value and key. + public static async Task ComputeHmacAsync(byte[] value, byte[] key, HashAlgorithmType type) + { + using KeyedHashAlgorithm algorithm = type.GetKeyedHashAlgorithm(key); + await using Stream stream = new MemoryStream(value); - byte[] data = await algorithm.ComputeHashAsync(stream); - Hash hash = Hash.FromByteArray(data, type); + byte[] data = await algorithm.ComputeHashAsync(stream); + Hash hash = Hash.FromByteArray(data, type); - return Create(hash, value); - } + return Create(hash, value); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Create.cs b/OnixLabs.Security.Cryptography/Hmac.Create.cs index ada3937..2ddc8ca 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Create.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Create.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,19 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Creates a hashed message authentication code (HMAC). + /// + /// The representing the HMAC. + /// The underlying un-hashed data. + /// Returns a new instance. + public static Hmac Create(Hash hash, byte[] data) { - /// - /// Creates a hashed message authentication code (HMAC). - /// - /// The representing the HMAC. - /// The underlying un-hashed data. - /// Returns a new instance. - public static Hmac Create(Hash hash, byte[] data) - { - return new Hmac(hash, data); - } + return new Hmac(hash, data); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Empty.cs b/OnixLabs.Security.Cryptography/Hmac.Empty.cs index 44c984f..dcf141d 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Empty.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Empty.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,21 +14,20 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac - { - /// - /// Gets an empty hashed message authentication code (HMAC) value. - /// - public static readonly Hmac Empty; + /// + /// Gets an empty hashed message authentication code (HMAC) value. + /// + public static readonly Hmac Empty; - /// - /// Initializes static members of the class. - /// - static Hmac() - { - Empty = Create(Hash.Empty, Array.Empty()); - } + /// + /// Initializes static members of the class. + /// + static Hmac() + { + Empty = Create(Hash.Empty, Array.Empty()); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Equatable.cs b/OnixLabs.Security.Cryptography/Hmac.Equatable.cs index f8d9ccb..c418ded 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Equatable.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,60 +16,58 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac : IEquatable { - public readonly partial struct Hmac : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(Hmac a, Hmac b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(Hmac a, Hmac b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(Hmac a, Hmac b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(Hmac a, Hmac b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(Hmac other) - { - return other.Hash == Hash - && other.Data.SequenceEqual(Data); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(Hmac other) + { + return other.Hash == Hash && other.Data.SequenceEqual(Data); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return obj is Hmac other && Equals(other); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return obj is Hmac other && Equals(other); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(Hash, Data.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(Hash, Data.GetContentHashCode()); } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Parse.cs b/OnixLabs.Security.Cryptography/Hmac.Parse.cs index 65d6356..d8633b3 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Parse.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Parse.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System; using OnixLabs.Core; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Parses a hexadecimal representation of a HMAC into a instance. + /// + /// A that contains a HMAC to convert. + /// The hash algorithm type of the HMAC. + /// A new instance. + public static Hmac Parse(string value, HashAlgorithmType? type = null) { - /// - /// Parses a hexadecimal representation of a HMAC into a instance. - /// - /// A that contains a HMAC to convert. - /// The hash algorithm type of the HMAC. - /// A new instance. - public static Hmac Parse(string value, HashAlgorithmType? type = null) - { - string hashComponent = value.SubstringBeforeLast(':'); - string dataComponent = value.SubstringAfterLast(':'); + string hashComponent = value.SubstringBeforeLast(':'); + string dataComponent = value.SubstringAfterLast(':'); - Hash hash = Hash.Parse(hashComponent, type); - byte[] data = Convert.FromHexString(dataComponent); + Hash hash = Hash.Parse(hashComponent, type); + byte[] data = Convert.FromHexString(dataComponent); - return Create(hash, data); - } + return Create(hash, data); + } - /// - /// Attempts to parse a hexadecimal representation of a HMAC into a instance. - /// - /// A that contains a HMAC to convert. - /// The hash algorithm type of the hash. - /// The result if conversion was successful. - /// Returns true if the hash conversion was successful; otherwise, false. - public static bool TryParse(string value, HashAlgorithmType? type, out Hmac hmac) + /// + /// Attempts to parse a hexadecimal representation of a HMAC into a instance. + /// + /// A that contains a HMAC to convert. + /// The hash algorithm type of the hash. + /// The result if conversion was successful. + /// Returns true if the hash conversion was successful; otherwise, false. + public static bool TryParse(string value, HashAlgorithmType? type, out Hmac hmac) + { + try + { + hmac = Parse(value, type); + return true; + } + catch { - try - { - hmac = Parse(value, type); - return true; - } - catch - { - hmac = default; - return false; - } + hmac = default; + return false; } } } diff --git a/OnixLabs.Security.Cryptography/Hmac.To.cs b/OnixLabs.Security.Cryptography/Hmac.To.cs index c41aa6b..f37933c 100644 --- a/OnixLabs.Security.Cryptography/Hmac.To.cs +++ b/OnixLabs.Security.Cryptography/Hmac.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,26 +14,25 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() { - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return $"{Hash}:{Convert.ToHexString(Data).ToLower()}"; - } + return $"{Hash}:{Convert.ToHexString(Data).ToLower()}"; + } - /// - /// Returns a that represents the current object, including the hash algorithm type. - /// - /// A that represents the current object, including the hash algorithm type. - public string ToStringWithAlgorithmType() - { - return $"{Hash.AlgorithmType.Name}:{ToString()}"; - } + /// + /// Returns a that represents the current object, including the hash algorithm type. + /// + /// A that represents the current object, including the hash algorithm type. + public string ToStringWithAlgorithmType() + { + return $"{Hash.AlgorithmType.Name}:{ToString()}"; } } diff --git a/OnixLabs.Security.Cryptography/Hmac.Verify.cs b/OnixLabs.Security.Cryptography/Hmac.Verify.cs index 039e713..63161ac 100644 --- a/OnixLabs.Security.Cryptography/Hmac.Verify.cs +++ b/OnixLabs.Security.Cryptography/Hmac.Verify.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,72 +15,71 @@ using System.Security.Cryptography; using System.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public readonly partial struct Hmac { - public readonly partial struct Hmac + /// + /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The key to validate against this . + /// Returns true if this was created with the specified key; otherwise, false. + public bool IsValid(string key) { - /// - /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The key to validate against this . - /// Returns true if this was created with the specified key; otherwise, false. - public bool IsValid(string key) - { - return IsValid(key, Encoding.Default); - } + return IsValid(key, Encoding.Default); + } - /// - /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The key to validate against this . - /// The encoding which will be used to convert the key into a byte array. - /// Returns true if this was created with the specified key; otherwise, false. - public bool IsValid(string key, Encoding encoding) - { - byte[] keyBytes = encoding.GetBytes(key); - return IsValid(keyBytes); - } + /// + /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The key to validate against this . + /// The encoding which will be used to convert the key into a byte array. + /// Returns true if this was created with the specified key; otherwise, false. + public bool IsValid(string key, Encoding encoding) + { + byte[] keyBytes = encoding.GetBytes(key); + return IsValid(keyBytes); + } - /// - /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The key to validate against this . - /// Returns true if this was created with the specified key; otherwise, false. - public bool IsValid(byte[] key) - { - return this == ComputeHmac(Data, key, Hash.AlgorithmType); - } + /// + /// Determines whether the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The key to validate against this . + /// Returns true if this was created with the specified key; otherwise, false. + public bool IsValid(byte[] key) + { + return this == ComputeHmac(Data, key, Hash.AlgorithmType); + } - /// - /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The key to validate against this . - public void Verify(string key) - { - Verify(key, Encoding.Default); - } + /// + /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The key to validate against this . + public void Verify(string key) + { + Verify(key, Encoding.Default); + } - /// - /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The encoding which will be used to convert the key into a byte array. - /// The key to validate against this . - public void Verify(string key, Encoding encoding) - { - byte[] keyBytes = encoding.GetBytes(key); - Verify(keyBytes); - } + /// + /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The encoding which will be used to convert the key into a byte array. + /// The key to validate against this . + public void Verify(string key, Encoding encoding) + { + byte[] keyBytes = encoding.GetBytes(key); + Verify(keyBytes); + } - /// - /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. - /// - /// The key to validate against this . - public void Verify(byte[] key) + /// + /// Verifies that the hashed message authentication code (HMAC) was created with the specified key. + /// + /// The key to validate against this . + public void Verify(byte[] key) + { + if (!IsValid(key)) { - if (!IsValid(key)) - { - throw new CryptographicException("The HMAC was could not be verified with the specified key."); - } + throw new CryptographicException("The HMAC was could not be verified with the specified key."); } } } diff --git a/OnixLabs.Security.Cryptography/Hmac.cs b/OnixLabs.Security.Cryptography/Hmac.cs index aa862e8..019cbf6 100644 --- a/OnixLabs.Security.Cryptography/Hmac.cs +++ b/OnixLabs.Security.Cryptography/Hmac.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,37 +14,36 @@ using OnixLabs.Core; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a hashed message authentication code (HMAC). +/// +public readonly partial struct Hmac { /// - /// Represents a hashed message authentication code (HMAC). + /// Represents the underlying un-hashed data. /// - public readonly partial struct Hmac - { - /// - /// Represents the underlying un-hashed data. - /// - private readonly byte[] data; + private readonly byte[] data; - /// - /// Initializes a new instance of the struct. - /// - /// The representing the HMAC. - /// The underlying un-hashed data. - private Hmac(Hash hash, byte[] data) - { - Hash = hash; - this.data = data; - } + /// + /// Initializes a new instance of the struct. + /// + /// The representing the HMAC. + /// The underlying un-hashed data. + private Hmac(Hash hash, byte[] data) + { + Hash = hash; + this.data = data; + } - /// - /// Gets the representing the HMAC. - /// - public Hash Hash { get; } + /// + /// Gets the representing the HMAC. + /// + public Hash Hash { get; } - /// - /// Gets the underlying un-hashed data. - /// - public byte[] Data => data.Copy(); - } + /// + /// Gets the underlying un-hashed data. + /// + public byte[] Data => data.Copy(); } diff --git a/OnixLabs.Security.Cryptography/KeyPair.Create.cs b/OnixLabs.Security.Cryptography/KeyPair.Create.cs index aceae26..d34348a 100644 --- a/OnixLabs.Security.Cryptography/KeyPair.Create.cs +++ b/OnixLabs.Security.Cryptography/KeyPair.Create.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,108 +14,104 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class KeyPair { - public sealed partial class KeyPair + /// + /// Creates an ECDSA public/private key pair. + /// + /// The for computing signature data. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type) + { + using ECDsa asymmetricAlgorithm = ECDsa.Create(); + + PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); + PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); + + return new KeyPair(privateKey, publicKey, type); + } + + /// + /// Creates an ECDSA public/private key pair. + /// + /// The for computing signature data. + /// The curve to use for key generation. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type, ECCurve curve) + { + using ECDsa asymmetricAlgorithm = ECDsa.Create(curve); + + PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); + PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); + + return new KeyPair(privateKey, publicKey, type); + } + + /// + /// Creates an ECDSA public/private key pair. + /// + /// The for computing signature data. + /// The parameters representing the key to use. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type, ECParameters parameters) + { + using ECDsa asymmetricAlgorithm = ECDsa.Create(parameters); + + PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); + PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); + + return new KeyPair(privateKey, publicKey, type); + } + + /// + /// Creates an RSA public/private key pair. + /// + /// The for computing signature data. + /// The for computing signature data. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateRsaKeyPair(HashAlgorithmType type, RSASignaturePadding padding) + { + using RSA asymmetricAlgorithm = RSA.Create(); + + PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); + PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); + + return new KeyPair(privateKey, publicKey, type); + } + + /// + /// Creates an RSA public/private key pair. + /// + /// The for computing signature data. + /// The for computing signature data. + /// The key size, in bits. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateRsaKeyPair(HashAlgorithmType type, RSASignaturePadding padding, int keySizeInBits) { - /// - /// Creates an ECDSA public/private key pair. - /// - /// The for computing signature data. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type) - { - using ECDsa asymmetricAlgorithm = ECDsa.Create(); - - PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); - PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); - - return new KeyPair(privateKey, publicKey, type); - } - - /// - /// Creates an ECDSA public/private key pair. - /// - /// The for computing signature data. - /// The curve to use for key generation. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type, ECCurve curve) - { - using ECDsa asymmetricAlgorithm = ECDsa.Create(curve); - - PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); - PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); - - return new KeyPair(privateKey, publicKey, type); - } - - /// - /// Creates an ECDSA public/private key pair. - /// - /// The for computing signature data. - /// The parameters representing the key to use. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateEcdsaKeyPair(HashAlgorithmType type, ECParameters parameters) - { - using ECDsa asymmetricAlgorithm = ECDsa.Create(parameters); - - PrivateKey privateKey = new EcdsaPrivateKey(asymmetricAlgorithm.ExportECPrivateKey(), type); - PublicKey publicKey = new EcdsaPublicKey(asymmetricAlgorithm.ExportSubjectPublicKeyInfo(), type); - - return new KeyPair(privateKey, publicKey, type); - } - - /// - /// Creates an RSA public/private key pair. - /// - /// The for computing signature data. - /// The for computing signature data. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateRsaKeyPair(HashAlgorithmType type, RSASignaturePadding padding) - { - using RSA asymmetricAlgorithm = RSA.Create(); - - PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); - PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); - - return new KeyPair(privateKey, publicKey, type); - } - - /// - /// Creates an RSA public/private key pair. - /// - /// The for computing signature data. - /// The for computing signature data. - /// The key size, in bits. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateRsaKeyPair(HashAlgorithmType type, RSASignaturePadding padding, int keySizeInBits) - { - using RSA asymmetricAlgorithm = RSA.Create(keySizeInBits); - - PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); - PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); - - return new KeyPair(privateKey, publicKey, type); - } - - /// - /// Creates an RSA public/private key pair. - /// - /// The for computing signature data. - /// The for computing signature data. - /// The parameters for the RSA algorithm. - /// Returns an ECDSA public/private key pair. - public static KeyPair CreateRsaKeyPair( - HashAlgorithmType type, - RSASignaturePadding padding, - RSAParameters parameters) - { - using RSA asymmetricAlgorithm = RSA.Create(parameters); - - PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); - PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); - - return new KeyPair(privateKey, publicKey, type); - } + using RSA asymmetricAlgorithm = RSA.Create(keySizeInBits); + + PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); + PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); + + return new KeyPair(privateKey, publicKey, type); + } + + /// + /// Creates an RSA public/private key pair. + /// + /// The for computing signature data. + /// The for computing signature data. + /// The parameters for the RSA algorithm. + /// Returns an ECDSA public/private key pair. + public static KeyPair CreateRsaKeyPair(HashAlgorithmType type, RSASignaturePadding padding, RSAParameters parameters) + { + using RSA asymmetricAlgorithm = RSA.Create(parameters); + + PrivateKey privateKey = new RsaPrivateKey(asymmetricAlgorithm.ExportRSAPrivateKey(), type, padding); + PublicKey publicKey = new RsaPublicKey(asymmetricAlgorithm.ExportRSAPublicKey(), type, padding); + + return new KeyPair(privateKey, publicKey, type); } } diff --git a/OnixLabs.Security.Cryptography/KeyPair.Equatable.cs b/OnixLabs.Security.Cryptography/KeyPair.Equatable.cs index 9736c0a..51b2248 100644 --- a/OnixLabs.Security.Cryptography/KeyPair.Equatable.cs +++ b/OnixLabs.Security.Cryptography/KeyPair.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,62 +14,61 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class KeyPair : IEquatable { - public sealed partial class KeyPair : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(KeyPair a, KeyPair b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(KeyPair a, KeyPair b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(KeyPair a, KeyPair b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(KeyPair a, KeyPair b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public bool Equals(KeyPair? other) - { - return ReferenceEquals(this, other) - || other is not null - && other.PrivateKey == PrivateKey - && other.PublicKey == PublicKey; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public bool Equals(KeyPair? other) + { + return ReferenceEquals(this, other) + || other is not null + && other.PrivateKey == PrivateKey + && other.PublicKey == PublicKey; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return Equals(obj as KeyPair); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return Equals(obj as KeyPair); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(PrivateKey, PublicKey); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(PrivateKey, PublicKey); } } diff --git a/OnixLabs.Security.Cryptography/KeyPair.From.cs b/OnixLabs.Security.Cryptography/KeyPair.From.cs index 3b09935..5120d94 100644 --- a/OnixLabs.Security.Cryptography/KeyPair.From.cs +++ b/OnixLabs.Security.Cryptography/KeyPair.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,43 +13,33 @@ // limitations under the License. using System; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class KeyPair { - public sealed partial class KeyPair + /// + /// Creates a key pair from the specified public and private key components. + /// + /// The private key component of the key pair. + /// The public key component of the key pair. + /// The hash algorithm type of the key pair. + /// Returns a new instance from the key components. + /// If the private key hash algorithm type is mismatched. + /// If the public key hash algorithm type is mismatched. + /// If the private and public key components are mismatched. + public static KeyPair FromKeyComponents(PrivateKey privateKey, PublicKey publicKey, HashAlgorithmType type) { - /// - /// Creates a key pair from the specified public and private key components. - /// - /// The private key component of the key pair. - /// The public key component of the key pair. - /// The hash algorithm type of the key pair. - /// Returns a new instance from the key components. - /// If the private key hash algorithm type is mismatched. - /// If the public key hash algorithm type is mismatched. - /// If the private and public key components are mismatched. - public static KeyPair FromKeyComponents(PrivateKey privateKey, PublicKey publicKey, HashAlgorithmType type) - { - if (privateKey.AlgorithmType != type) - { - throw new ArgumentException($"Private key hash algorithm type is mismatched with '{type}'."); - } - - if (publicKey.AlgorithmType != type) - { - throw new ArgumentException($"Public key hash algorithm type is mismatched with '{type}'."); - } + Check(privateKey.AlgorithmType == type, $"Private key hash algorithm type is mismatched with '{type}'.", nameof(privateKey)); + Check(publicKey.AlgorithmType == type, $"Public key hash algorithm type is mismatched with '{type}'.", nameof(publicKey)); - byte[] random = Guid.NewGuid().ToByteArray(); - Hash hash = Hash.ComputeSha2Hash256(random); - DigitalSignature signature = privateKey.SignHash(hash); + byte[] random = Guid.NewGuid().ToByteArray(); + Hash hash = Hash.ComputeSha2Hash256(random); + DigitalSignature signature = privateKey.SignHash(hash); - if (!signature.IsHashValid(hash, publicKey)) - { - throw new ArgumentException("Invalid key pair. The specified public and private keys are mismatched."); - } + Check(signature.IsHashValid(hash, publicKey), "Invalid key pair. The specified public and private keys are mismatched."); - return new KeyPair(privateKey, publicKey, type); - } + return new KeyPair(privateKey, publicKey, type); } } diff --git a/OnixLabs.Security.Cryptography/KeyPair.cs b/OnixLabs.Security.Cryptography/KeyPair.cs index 73250f6..420b2fb 100644 --- a/OnixLabs.Security.Cryptography/KeyPair.cs +++ b/OnixLabs.Security.Cryptography/KeyPair.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,39 +12,38 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a cryptographic public/private key pair. +/// +public sealed partial class KeyPair { /// - /// Represents a cryptographic public/private key pair. + /// Prevents new instances of the class from being created. /// - public sealed partial class KeyPair + /// The private key component of this key pair. + /// The public key component of this key pair. + /// The hash algorithm type of this key pair. + private KeyPair(PrivateKey privateKey, PublicKey publicKey, HashAlgorithmType algorithmType) { - /// - /// Prevents new instances of the class from being created. - /// - /// The private key component of this key pair. - /// The public key component of this key pair. - /// The hash algorithm type of this key pair. - private KeyPair(PrivateKey privateKey, PublicKey publicKey, HashAlgorithmType algorithmType) - { - PrivateKey = privateKey; - PublicKey = publicKey; - AlgorithmType = algorithmType; - } + PrivateKey = privateKey; + PublicKey = publicKey; + AlgorithmType = algorithmType; + } - /// - /// Gets the private key component of this key pair. - /// - public PrivateKey PrivateKey { get; } + /// + /// Gets the private key component of this key pair. + /// + public PrivateKey PrivateKey { get; } - /// - /// Gets the public key component of this key pair. - /// - public PublicKey PublicKey { get; } + /// + /// Gets the public key component of this key pair. + /// + public PublicKey PublicKey { get; } - /// - /// Gets the hash algorithm type of this key pair. - /// - public HashAlgorithmType AlgorithmType { get; } - } + /// + /// Gets the hash algorithm type of this key pair. + /// + public HashAlgorithmType AlgorithmType { get; } } diff --git a/OnixLabs.Security.Cryptography/MerkleTree.Equatable.cs b/OnixLabs.Security.Cryptography/MerkleTree.Equatable.cs index f97bb67..0469861 100644 --- a/OnixLabs.Security.Cryptography/MerkleTree.Equatable.cs +++ b/OnixLabs.Security.Cryptography/MerkleTree.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,61 +14,58 @@ using System; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class MerkleTree : IEquatable { - public abstract partial class MerkleTree : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(MerkleTree a, MerkleTree b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(MerkleTree a, MerkleTree b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(MerkleTree a, MerkleTree b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(MerkleTree a, MerkleTree b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public virtual bool Equals(MerkleTree? other) - { - return ReferenceEquals(this, other) - || other is not null - && other.Hash == Hash; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public virtual bool Equals(MerkleTree? other) + { + return ReferenceEquals(this, other) || other is not null && other.Hash == Hash; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return Equals(obj as MerkleTree); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return Equals(obj as MerkleTree); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(GetType(), Hash); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(GetType(), Hash); } } diff --git a/OnixLabs.Security.Cryptography/MerkleTree.cs b/OnixLabs.Security.Cryptography/MerkleTree.cs index 63a4bac..fca22af 100644 --- a/OnixLabs.Security.Cryptography/MerkleTree.cs +++ b/OnixLabs.Security.Cryptography/MerkleTree.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,131 +16,123 @@ using System.Collections.Generic; using System.Linq; using OnixLabs.Core.Linq; +using static OnixLabs.Core.Preconditions; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a Merkle tree. +/// +public abstract partial class MerkleTree { /// - /// Represents a Merkle tree. + /// Prevents an instance of from being created. /// - public abstract partial class MerkleTree + internal MerkleTree() { - /// - /// Prevents an instance of from being created. - /// - internal MerkleTree() - { - } + } - /// - /// Gets the hash of this node. - /// - public abstract Hash Hash { get; } - - /// - /// Builds a Merkle tree from the specified leaf node hashes. - /// - /// The leaf nodes from which to build a Merkle tree. - /// Returns a new instance from the specified leaf nodes. - public static MerkleTree Build(IEnumerable nodes) - { - IReadOnlyList leafNodes = nodes - .Select(MerkleTreeLeafNode.CreateHashNode) - .ToList(); + /// + /// Gets the hash of this node. + /// + public abstract Hash Hash { get; } - return Build(leafNodes); - } + /// + /// Builds a Merkle tree from the specified leaf node hashes. + /// + /// The leaf nodes from which to build a Merkle tree. + /// Returns a new instance from the specified leaf nodes. + public static MerkleTree Build(IEnumerable nodes) + { + IReadOnlyList leafNodes = nodes.Select(MerkleTreeLeafNode.CreateHashNode).ToList(); + return Build(leafNodes); + } - /// - /// Builds a Merkle tree from the specified Merkle tree nodes. - /// - /// The Merkle tree nodes from which to build a Merkle tree. - /// Returns a new instance from the specified nodes. - private static MerkleTree Build(IReadOnlyList nodes) - { - CheckIfMerkleTreesAreEmpty(nodes); - CheckNodesHaveEqualHashAlgorithms(nodes); + /// + /// Builds a Merkle tree from the specified Merkle tree nodes. + /// + /// The Merkle tree nodes from which to build a Merkle tree. + /// Returns a new instance from the specified nodes. + private static MerkleTree Build(IReadOnlyList nodes) + { + CheckIfMerkleTreesAreEmpty(nodes); + CheckNodesHaveEqualHashAlgorithms(nodes); - return MergeMerkleTreeNodes(nodes); - } + return MergeMerkleTreeNodes(nodes); + } - /// - /// Checks whether an is empty. - /// - /// The to check. - /// if the is empty. - private static void CheckIfMerkleTreesAreEmpty(IEnumerable merkleTrees) - { - if (merkleTrees.IsEmpty()) - { - throw new ArgumentException("Cannot construct a merkle tree from an empty list."); - } - } + /// + /// Checks whether an is empty. + /// + /// The to check. + /// if the is empty. + private static void CheckIfMerkleTreesAreEmpty(IEnumerable merkleTrees) + { + Check(merkleTrees.IsNotEmpty(), "Cannot construct a merkle tree from an empty list."); + } - /// - /// Checks whether all elements of an have the same hash algorithm type. - /// - /// The to check. - /// if the elements of the do not have the same hash algorithm type. - private static void CheckNodesHaveEqualHashAlgorithms(IEnumerable merkleTrees) - { - if (!merkleTrees.AllEqualBy(merkleTree => merkleTree.Hash.AlgorithmType)) - { - throw new ArgumentException("Cannot construct a merkle tree with different hash types."); - } - } + /// + /// Checks whether all elements of an have the same hash algorithm type. + /// + /// The to check. + /// if the elements of the do not have the same hash algorithm type. + private static void CheckNodesHaveEqualHashAlgorithms(IEnumerable merkleTrees) + { + Check(merkleTrees.AllEqualBy(merkleTree => merkleTree.Hash.AlgorithmType), + "Cannot construct a merkle tree with different hash types."); + } - /// - /// Ensures that an has an even number of elements. - /// If the contains an odd number of elements, then an all-zero hash - /// of the same will be inserted at the end of the list. - /// - /// The to ensure has an even number of elements. - /// Returns a new containing an even number of elements. - private static IReadOnlyList EnsureEvenNumberOfNodes(IReadOnlyList merkleTrees) - { - if (!merkleTrees.IsOddCount()) return merkleTrees; + /// + /// Ensures that an has an even number of elements. + /// If the contains an odd number of elements, then an all-zero hash + /// of the same will be inserted at the end of the list. + /// + /// The to ensure has an even number of elements. + /// Returns a new containing an even number of elements. + private static IReadOnlyList EnsureEvenNumberOfNodes(IReadOnlyList merkleTrees) + { + if (merkleTrees.IsCountEven()) return merkleTrees; - HashAlgorithmType hashAlgorithmType = merkleTrees[0].Hash.AlgorithmType; - return merkleTrees.Append(MerkleTreeLeafNode.CreateEmptyNode(hashAlgorithmType)).ToList(); - } + HashAlgorithmType hashAlgorithmType = merkleTrees[0].Hash.AlgorithmType; + return merkleTrees.Append(MerkleTreeLeafNode.CreateEmptyNode(hashAlgorithmType)).ToList(); + } - /// - /// Merges an of Merkle tree nodes. - /// - /// The of Merkle tree nodes to merge. - /// Returns a merged of Merkle tree nodes. - private static MerkleTree MergeMerkleTreeNodes(IReadOnlyList merkleTrees) + /// + /// Merges an of Merkle tree nodes. + /// + /// The of Merkle tree nodes to merge. + /// Returns a merged of Merkle tree nodes. + private static MerkleTree MergeMerkleTreeNodes(IReadOnlyList merkleTrees) + { + while (true) { - while (true) + if (merkleTrees.IsSingle()) { - if (merkleTrees.IsSingle()) - { - return merkleTrees[0]; - } - - merkleTrees = EnsureEvenNumberOfNodes(merkleTrees); + return merkleTrees[0]; + } - List mutableMerkleTrees = new(); + merkleTrees = EnsureEvenNumberOfNodes(merkleTrees); - for (int index = 0; index < merkleTrees.Count; index += 2) - { - MerkleTree leftMerkleTree = merkleTrees[index]; - MerkleTree rightMerkleTree = merkleTrees[index + 1]; - MerkleTree merkleTreeNode = new MerkleTreeBranchNode(leftMerkleTree, rightMerkleTree); - mutableMerkleTrees.Add(merkleTreeNode); - } + List mutableMerkleTrees = new(); - merkleTrees = mutableMerkleTrees; + for (int index = 0; index < merkleTrees.Count; index += 2) + { + MerkleTree leftMerkleTree = merkleTrees[index]; + MerkleTree rightMerkleTree = merkleTrees[index + 1]; + MerkleTree merkleTreeNode = new MerkleTreeBranchNode(leftMerkleTree, rightMerkleTree); + mutableMerkleTrees.Add(merkleTreeNode); } - } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Hash.ToString(); + merkleTrees = mutableMerkleTrees; } } + + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Hash.ToString(); + } } diff --git a/OnixLabs.Security.Cryptography/MerkleTreeBranchNode.cs b/OnixLabs.Security.Cryptography/MerkleTreeBranchNode.cs index 5049b21..40dc405 100644 --- a/OnixLabs.Security.Cryptography/MerkleTreeBranchNode.cs +++ b/OnixLabs.Security.Cryptography/MerkleTreeBranchNode.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,37 +12,36 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a Merkle tree branch node. +/// +internal sealed class MerkleTreeBranchNode : MerkleTree { /// - /// Represents a Merkle tree branch node. + /// Creates a new instance of the class. /// - internal sealed class MerkleTreeBranchNode : MerkleTree + /// The left-hand node. + /// The right-hand node. + public MerkleTreeBranchNode(MerkleTree left, MerkleTree right) { - /// - /// Creates a new instance of the class. - /// - /// The left-hand node. - /// The right-hand node. - public MerkleTreeBranchNode(MerkleTree left, MerkleTree right) - { - Left = left; - Right = right; - } + Left = left; + Right = right; + } - /// - /// Gets the left-hand node. - /// - public MerkleTree Left { get; } + /// + /// Gets the left-hand node. + /// + public MerkleTree Left { get; } - /// - /// Gets the right-hand node. - /// - public MerkleTree Right { get; } + /// + /// Gets the right-hand node. + /// + public MerkleTree Right { get; } - /// - /// Gets the hash of this node. - /// - public override Hash Hash => Left.Hash.Concatenate(Right.Hash); - } + /// + /// Gets the hash of this node. + /// + public override Hash Hash => Left.Hash.Concatenate(Right.Hash); } diff --git a/OnixLabs.Security.Cryptography/MerkleTreeLeafNode.cs b/OnixLabs.Security.Cryptography/MerkleTreeLeafNode.cs index cbf8ec9..d73f785 100644 --- a/OnixLabs.Security.Cryptography/MerkleTreeLeafNode.cs +++ b/OnixLabs.Security.Cryptography/MerkleTreeLeafNode.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,44 +12,43 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents a Merkle tree leaf node. +/// +internal sealed class MerkleTreeLeafNode : MerkleTree { /// - /// Represents a Merkle tree leaf node. + /// Creates a new instance of the class. /// - internal sealed class MerkleTreeLeafNode : MerkleTree + public MerkleTreeLeafNode(Hash hash) { - /// - /// Creates a new instance of the class. - /// - public MerkleTreeLeafNode(Hash hash) - { - Hash = hash; - } + Hash = hash; + } - /// - /// Gets the hash of this node. - /// - public override Hash Hash { get; } + /// + /// Gets the hash of this node. + /// + public override Hash Hash { get; } - /// - /// Creates a from from the specified hash. - /// - /// The from which to create a node. - /// Returns an node. - public static MerkleTree CreateHashNode(Hash hash) - { - return new MerkleTreeLeafNode(hash); - } + /// + /// Creates a from from the specified hash. + /// + /// The from which to create a node. + /// Returns an node. + public static MerkleTree CreateHashNode(Hash hash) + { + return new MerkleTreeLeafNode(hash); + } - /// - /// Creates an empty node represented by an all-zero hash. - /// - /// The hash algorithm type of the node to create. - /// Returns an empty node represented by an all-zero hash. - public static MerkleTree CreateEmptyNode(HashAlgorithmType type) - { - return new MerkleTreeLeafNode(Hash.CreateAllZeroHash(type)); - } + /// + /// Creates an empty node represented by an all-zero hash. + /// + /// The hash algorithm type of the node to create. + /// Returns an empty node represented by an all-zero hash. + public static MerkleTree CreateEmptyNode(HashAlgorithmType type) + { + return new MerkleTreeLeafNode(Hash.CreateAllZeroHash(type)); } } diff --git a/OnixLabs.Security.Cryptography/OnixLabs.Security.Cryptography.csproj b/OnixLabs.Security.Cryptography/OnixLabs.Security.Cryptography.csproj index 3eb2306..0e2dc8b 100644 --- a/OnixLabs.Security.Cryptography/OnixLabs.Security.Cryptography.csproj +++ b/OnixLabs.Security.Cryptography/OnixLabs.Security.Cryptography.csproj @@ -1,17 +1,18 @@ - net5.0 + net6.0 OnixLabs.Security.Cryptography ONIXLabs ONIXLabs Cryptography API for .NET - 4.0.0 + 5.0.0 en enable true - Copyright © ONIXLabs 2020-2021 + Copyright © ONIXLabs 2020-2022 https://github.com/onix-labs/onixlabs-dotnet - 4.0.0 + 5.0.0 + 10 diff --git a/OnixLabs.Security.Cryptography/PrivateKey.Equatable.cs b/OnixLabs.Security.Cryptography/PrivateKey.Equatable.cs index 1b77b18..10cfd17 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.Equatable.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,63 +16,62 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PrivateKey : IEquatable { - public abstract partial class PrivateKey : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(PrivateKey a, PrivateKey b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(PrivateKey a, PrivateKey b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(PrivateKey a, PrivateKey b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(PrivateKey a, PrivateKey b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public virtual bool Equals(PrivateKey? other) - { - return ReferenceEquals(this, other) - || other is not null - && other.GetType() == GetType() - && other.KeyData.SequenceEqual(KeyData) - && other.AlgorithmType == AlgorithmType; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public virtual bool Equals(PrivateKey? other) + { + return ReferenceEquals(this, other) + || other is not null + && other.GetType() == GetType() + && other.KeyData.SequenceEqual(KeyData) + && other.AlgorithmType == AlgorithmType; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return Equals(obj as PrivateKey); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return Equals(obj as PrivateKey); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(GetType(), AlgorithmType, KeyData.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(GetType(), AlgorithmType, KeyData.GetContentHashCode()); } } diff --git a/OnixLabs.Security.Cryptography/PrivateKey.Export.cs b/OnixLabs.Security.Cryptography/PrivateKey.Export.cs index e6e532e..c09ebe6 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.Export.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.Export.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,46 +15,45 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PrivateKey { - public abstract partial class PrivateKey - { - /// - /// Exports the key in PKCS #8 format. - /// - /// Returns the key in PKCS #8 format. - public abstract byte[] ExportPkcs8Key(); + /// + /// Exports the key in PKCS #8 format. + /// + /// Returns the key in PKCS #8 format. + public abstract byte[] ExportPkcs8Key(); - /// - /// Exports the key in encrypted PKCS #8 format. - /// - /// The password to use for encryption. - /// The parameters required for password based encryption. - /// Returns the key in encrypted PKCS #8 format. - public abstract byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters); + /// + /// Exports the key in encrypted PKCS #8 format. + /// + /// The password to use for encryption. + /// The parameters required for password based encryption. + /// Returns the key in encrypted PKCS #8 format. + public abstract byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters); - /// - /// Exports the key in encrypted PKCS #8 format. - /// - /// The password to use for encryption. - /// The parameters required for password based encryption. - /// Returns the key in encrypted PKCS #8 format. - public byte[] ExportPkcs8Key(char[] password, PbeParameters parameters) - { - ReadOnlySpan characters = password.AsSpan(); - return ExportPkcs8Key(characters, parameters); - } + /// + /// Exports the key in encrypted PKCS #8 format. + /// + /// The password to use for encryption. + /// The parameters required for password based encryption. + /// Returns the key in encrypted PKCS #8 format. + public byte[] ExportPkcs8Key(char[] password, PbeParameters parameters) + { + ReadOnlySpan characters = password.AsSpan(); + return ExportPkcs8Key(characters, parameters); + } - /// - /// Exports the key in encrypted PKCS #8 format. - /// - /// The password to use for encryption. - /// The parameters required for password based encryption. - /// Returns the key in encrypted PKCS #8 format. - public byte[] ExportPkcs8Key(string password, PbeParameters parameters) - { - char[] characters = password.ToCharArray(); - return ExportPkcs8Key(characters, parameters); - } + /// + /// Exports the key in encrypted PKCS #8 format. + /// + /// The password to use for encryption. + /// The parameters required for password based encryption. + /// Returns the key in encrypted PKCS #8 format. + public byte[] ExportPkcs8Key(string password, PbeParameters parameters) + { + char[] characters = password.ToCharArray(); + return ExportPkcs8Key(characters, parameters); } } diff --git a/OnixLabs.Security.Cryptography/PrivateKey.Get.cs b/OnixLabs.Security.Cryptography/PrivateKey.Get.cs index 8233939..2c165e4 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.Get.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.Get.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,14 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PrivateKey { - public abstract partial class PrivateKey - { - /// - /// Gets the public key component from this private key. - /// - /// Returns the public key component from this private key. - public abstract PublicKey GetPublicKey(); - } + /// + /// Gets the public key component from this private key. + /// + /// Returns the public key component from this private key. + public abstract PublicKey GetPublicKey(); } diff --git a/OnixLabs.Security.Cryptography/PrivateKey.Sign.cs b/OnixLabs.Security.Cryptography/PrivateKey.Sign.cs index 98dc1d6..3caca47 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.Sign.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.Sign.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,33 +12,32 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PrivateKey { - public abstract partial class PrivateKey - { - /// - /// Computes a from the specified unsigned data. - /// - /// The unsigned data from which to compute a . - /// Returns a from the specified unsigned data. - public abstract DigitalSignature SignData(byte[] unsignedData); + /// + /// Computes a from the specified unsigned data. + /// + /// The unsigned data from which to compute a . + /// Returns a from the specified unsigned data. + public abstract DigitalSignature SignData(byte[] unsignedData); - /// - /// Computes a from the specified unsigned hash. - /// - /// The unsigned hash from which to compute a . - /// Returns a from the specified unsigned hash. - public abstract DigitalSignature SignHash(byte[] unsignedHash); + /// + /// Computes a from the specified unsigned hash. + /// + /// The unsigned hash from which to compute a . + /// Returns a from the specified unsigned hash. + public abstract DigitalSignature SignHash(byte[] unsignedHash); - /// - /// Computes a from the specified unsigned hash. - /// - /// The unsigned hash from which to compute a . - /// Returns a from the specified unsigned hash. - public DigitalSignature SignHash(Hash unsignedHash) - { - byte[] unsignedHashBytes = unsignedHash.ToByteArray(); - return SignHash(unsignedHashBytes); - } + /// + /// Computes a from the specified unsigned hash. + /// + /// The unsigned hash from which to compute a . + /// Returns a from the specified unsigned hash. + public DigitalSignature SignHash(Hash unsignedHash) + { + byte[] unsignedHashBytes = unsignedHash.ToByteArray(); + return SignHash(unsignedHashBytes); } } diff --git a/OnixLabs.Security.Cryptography/PrivateKey.To.cs b/OnixLabs.Security.Cryptography/PrivateKey.To.cs index f3f95b7..8b72475 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.To.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,82 +16,81 @@ using OnixLabs.Core; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PrivateKey { - public abstract partial class PrivateKey + /// + /// Returns a array that represents the underlying private key data. + /// + /// Returns a array that represents the underlying private key data. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the underlying private key data. - /// - /// Returns a array that represents the underlying private key data. - public byte[] ToByteArray() - { - return KeyData.Copy(); - } + return KeyData.Copy(); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// Returns a value that represents the underlying private key data. - public Base16 ToBase16() - { - return Base16.FromByteArray(KeyData); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// Returns a value that represents the underlying private key data. + public Base16 ToBase16() + { + return Base16.FromByteArray(KeyData); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// Returns a value that represents the underlying private key data. - public Base32 ToBase32() - { - return ToBase32(Base32Alphabet.Default); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// Returns a value that represents the underlying private key data. + public Base32 ToBase32() + { + return ToBase32(Base32Alphabet.Default); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// The Base-32 alphabet to use to encode the private key data. - /// Returns a value that represents the underlying private key data. - public Base32 ToBase32(Base32Alphabet alphabet) - { - return Base32.FromByteArray(KeyData, alphabet); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// The Base-32 alphabet to use to encode the private key data. + /// Returns a value that represents the underlying private key data. + public Base32 ToBase32(Base32Alphabet alphabet) + { + return Base32.FromByteArray(KeyData, alphabet); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// Returns a value that represents the underlying private key data. - public Base58 ToBase58() - { - return ToBase58(Base58Alphabet.Default); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// Returns a value that represents the underlying private key data. + public Base58 ToBase58() + { + return ToBase58(Base58Alphabet.Default); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// The Base-58 alphabet to use to encode the private key data. - /// Returns a value that represents the underlying private key data. - public Base58 ToBase58(Base58Alphabet alphabet) - { - return Base58.FromByteArray(KeyData, alphabet); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// The Base-58 alphabet to use to encode the private key data. + /// Returns a value that represents the underlying private key data. + public Base58 ToBase58(Base58Alphabet alphabet) + { + return Base58.FromByteArray(KeyData, alphabet); + } - /// - /// Returns a value that represents the underlying private key data. - /// - /// Returns a value that represents the underlying private key data. - public Base64 ToBase64() - { - return Base64.FromByteArray(KeyData); - } + /// + /// Returns a value that represents the underlying private key data. + /// + /// Returns a value that represents the underlying private key data. + public Base64 ToBase64() + { + return Base64.FromByteArray(KeyData); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToHexString(KeyData).ToLower(); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToHexString(KeyData).ToLower(); } } diff --git a/OnixLabs.Security.Cryptography/PrivateKey.cs b/OnixLabs.Security.Cryptography/PrivateKey.cs index 3816671..5a74e98 100644 --- a/OnixLabs.Security.Cryptography/PrivateKey.cs +++ b/OnixLabs.Security.Cryptography/PrivateKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,34 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents the base class for private key implementations. +/// +public abstract partial class PrivateKey { /// - /// Represents the base class for private key implementations. + /// Initializes a new instance of the class. /// - public abstract partial class PrivateKey + /// The private key data. + /// The hash algorithm type for computing signature data. + protected PrivateKey(byte[] data, HashAlgorithmType type) { - /// - /// Initializes a new instance of the class. - /// - /// The private key data. - /// The hash algorithm type for computing signature data. - protected PrivateKey(byte[] data, HashAlgorithmType type) - { - type.GetHashAlgorithmName(); + type.GetHashAlgorithmName(); - KeyData = data; - AlgorithmType = type; - } + KeyData = data; + AlgorithmType = type; + } - /// - /// Gets the underlying private key data. - /// - protected byte[] KeyData { get; } + /// + /// Gets the underlying private key data. + /// + protected byte[] KeyData { get; } - /// - /// Gets the hash algorithm type for computing signature data. - /// - public HashAlgorithmType AlgorithmType { get; } - } + /// + /// Gets the hash algorithm type for computing signature data. + /// + public HashAlgorithmType AlgorithmType { get; } } diff --git a/OnixLabs.Security.Cryptography/PublicKey.Equatable.cs b/OnixLabs.Security.Cryptography/PublicKey.Equatable.cs index 20143eb..66ef8d0 100644 --- a/OnixLabs.Security.Cryptography/PublicKey.Equatable.cs +++ b/OnixLabs.Security.Cryptography/PublicKey.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,63 +16,62 @@ using System.Linq; using OnixLabs.Core.Linq; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PublicKey : IEquatable { - public abstract partial class PublicKey : IEquatable + /// + /// Performs an equality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are equal; otherwise, false. + public static bool operator ==(PublicKey a, PublicKey b) { - /// - /// Performs an equality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are equal; otherwise, false. - public static bool operator ==(PublicKey a, PublicKey b) - { - return Equals(a, b); - } + return Equals(a, b); + } - /// - /// Performs an inequality check between two object instances. - /// - /// Instance a. - /// Instance b. - /// True if the instances are not equal; otherwise, false. - public static bool operator !=(PublicKey a, PublicKey b) - { - return !Equals(a, b); - } + /// + /// Performs an inequality check between two object instances. + /// + /// Instance a. + /// Instance b. + /// True if the instances are not equal; otherwise, false. + public static bool operator !=(PublicKey a, PublicKey b) + { + return !Equals(a, b); + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public virtual bool Equals(PublicKey? other) - { - return ReferenceEquals(this, other) - || other is not null - && other.GetType() == GetType() - && other.KeyData.SequenceEqual(KeyData) - && other.AlgorithmType == AlgorithmType; - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public virtual bool Equals(PublicKey? other) + { + return ReferenceEquals(this, other) + || other is not null + && other.GetType() == GetType() + && other.KeyData.SequenceEqual(KeyData) + && other.AlgorithmType == AlgorithmType; + } - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(object? obj) - { - return Equals(obj as PublicKey); - } + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(object? obj) + { + return Equals(obj as PublicKey); + } - /// - /// Serves as a hash code function for this instance. - /// - /// A hash code for this instance. - public override int GetHashCode() - { - return HashCode.Combine(GetType(), AlgorithmType, KeyData.ComputeContentHashCode()); - } + /// + /// Serves as a hash code function for this instance. + /// + /// A hash code for this instance. + public override int GetHashCode() + { + return HashCode.Combine(GetType(), AlgorithmType, KeyData.GetContentHashCode()); } } diff --git a/OnixLabs.Security.Cryptography/PublicKey.To.cs b/OnixLabs.Security.Cryptography/PublicKey.To.cs index 1d48645..1292aa1 100644 --- a/OnixLabs.Security.Cryptography/PublicKey.To.cs +++ b/OnixLabs.Security.Cryptography/PublicKey.To.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,82 +16,81 @@ using OnixLabs.Core; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PublicKey { - public abstract partial class PublicKey + /// + /// Returns a array that represents the underlying public key data. + /// + /// Returns a array that represents the underlying public key data. + public byte[] ToByteArray() { - /// - /// Returns a array that represents the underlying public key data. - /// - /// Returns a array that represents the underlying public key data. - public byte[] ToByteArray() - { - return KeyData.Copy(); - } + return KeyData.Copy(); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// Returns a value that represents the underlying public key data. - public Base16 ToBase16() - { - return Base16.FromByteArray(KeyData); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// Returns a value that represents the underlying public key data. + public Base16 ToBase16() + { + return Base16.FromByteArray(KeyData); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// Returns a value that represents the underlying public key data. - public Base32 ToBase32() - { - return ToBase32(Base32Alphabet.Default); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// Returns a value that represents the underlying public key data. + public Base32 ToBase32() + { + return ToBase32(Base32Alphabet.Default); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// The Base-32 alphabet to use to encode the public key data. - /// Returns a value that represents the underlying public key data. - public Base32 ToBase32(Base32Alphabet alphabet) - { - return Base32.FromByteArray(KeyData, alphabet); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// The Base-32 alphabet to use to encode the public key data. + /// Returns a value that represents the underlying public key data. + public Base32 ToBase32(Base32Alphabet alphabet) + { + return Base32.FromByteArray(KeyData, alphabet); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// Returns a value that represents the underlying public key data. - public Base58 ToBase58() - { - return ToBase58(Base58Alphabet.Default); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// Returns a value that represents the underlying public key data. + public Base58 ToBase58() + { + return ToBase58(Base58Alphabet.Default); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// The Base-58 alphabet to use to encode the public key data. - /// Returns a value that represents the underlying public key data. - public Base58 ToBase58(Base58Alphabet alphabet) - { - return Base58.FromByteArray(KeyData, alphabet); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// The Base-58 alphabet to use to encode the public key data. + /// Returns a value that represents the underlying public key data. + public Base58 ToBase58(Base58Alphabet alphabet) + { + return Base58.FromByteArray(KeyData, alphabet); + } - /// - /// Returns a value that represents the underlying public key data. - /// - /// Returns a value that represents the underlying public key data. - public Base64 ToBase64() - { - return Base64.FromByteArray(KeyData); - } + /// + /// Returns a value that represents the underlying public key data. + /// + /// Returns a value that represents the underlying public key data. + public Base64 ToBase64() + { + return Base64.FromByteArray(KeyData); + } - /// - /// Returns a that represents the current object. - /// - /// A that represents the current object. - public override string ToString() - { - return Convert.ToHexString(KeyData).ToLower(); - } + /// + /// Returns a that represents the current object. + /// + /// A that represents the current object. + public override string ToString() + { + return Convert.ToHexString(KeyData).ToLower(); } } diff --git a/OnixLabs.Security.Cryptography/PublicKey.Verify.cs b/OnixLabs.Security.Cryptography/PublicKey.Verify.cs index 8c61b91..f8e6e2c 100644 --- a/OnixLabs.Security.Cryptography/PublicKey.Verify.cs +++ b/OnixLabs.Security.Cryptography/PublicKey.Verify.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,76 +14,75 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class PublicKey { - public abstract partial class PublicKey - { - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned data to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public abstract bool IsDataValid(DigitalSignature signature, byte[] unsignedData); + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned data to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public abstract bool IsDataValid(DigitalSignature signature, byte[] unsignedData); - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned hash to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public abstract bool IsHashValid(DigitalSignature signature, byte[] unsignedHash); + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned hash to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public abstract bool IsHashValid(DigitalSignature signature, byte[] unsignedHash); - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned hash to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public bool IsHashValid(DigitalSignature signature, Hash unsignedHash) - { - byte[] unsignedHashBytes = unsignedHash.ToByteArray(); - return IsHashValid(signature, unsignedHashBytes); - } + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned hash to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public bool IsHashValid(DigitalSignature signature, Hash unsignedHash) + { + byte[] unsignedHashBytes = unsignedHash.ToByteArray(); + return IsHashValid(signature, unsignedHashBytes); + } - /// - /// Verifies whether the specified was signed by the private component of this public key. - /// - /// The to verify. - /// he unsigned data to verify. - /// If the specified was not signed by the private component of this public key. - public void VerifyData(DigitalSignature signature, byte[] unsignedData) + /// + /// Verifies whether the specified was signed by the private component of this public key. + /// + /// The to verify. + /// he unsigned data to verify. + /// If the specified was not signed by the private component of this public key. + public void VerifyData(DigitalSignature signature, byte[] unsignedData) + { + if (!IsDataValid(signature, unsignedData)) { - if (!IsDataValid(signature, unsignedData)) - { - throw new CryptographicException("The specified digital signature was not signed with this key."); - } + throw new CryptographicException("The specified digital signature was not signed with this key."); } + } - /// - /// Verifies whether the specified was signed by the private component of this public key. - /// - /// The to verify. - /// he unsigned hash to verify. - /// If the specified was not signed by the private component of this public key. - public void VerifyHash(DigitalSignature signature, byte[] unsignedHash) + /// + /// Verifies whether the specified was signed by the private component of this public key. + /// + /// The to verify. + /// he unsigned hash to verify. + /// If the specified was not signed by the private component of this public key. + public void VerifyHash(DigitalSignature signature, byte[] unsignedHash) + { + if (!IsHashValid(signature, unsignedHash)) { - if (!IsHashValid(signature, unsignedHash)) - { - throw new CryptographicException("The specified digital signature was not signed with this key."); - } + throw new CryptographicException("The specified digital signature was not signed with this key."); } + } - /// - /// Verifies whether the specified was signed by the private component of this public key. - /// - /// The to verify. - /// he unsigned hash to verify. - /// If the specified was not signed by the private component of this public key. - public void VerifyHash(DigitalSignature signature, Hash unsignedHash) - { - byte[] unsignedHashBytes = unsignedHash.ToByteArray(); - VerifyHash(signature, unsignedHashBytes); - } + /// + /// Verifies whether the specified was signed by the private component of this public key. + /// + /// The to verify. + /// he unsigned hash to verify. + /// If the specified was not signed by the private component of this public key. + public void VerifyHash(DigitalSignature signature, Hash unsignedHash) + { + byte[] unsignedHashBytes = unsignedHash.ToByteArray(); + VerifyHash(signature, unsignedHashBytes); } } diff --git a/OnixLabs.Security.Cryptography/PublicKey.cs b/OnixLabs.Security.Cryptography/PublicKey.cs index 7ad2ce9..a763b4d 100644 --- a/OnixLabs.Security.Cryptography/PublicKey.cs +++ b/OnixLabs.Security.Cryptography/PublicKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,34 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents the base class for public key implementations. +/// +public abstract partial class PublicKey { /// - /// Represents the base class for public key implementations. + /// Creates a new instance of the class. /// - public abstract partial class PublicKey + /// The public key data. + /// The hash algorithm type for computing signature data. + protected PublicKey(byte[] data, HashAlgorithmType type) { - /// - /// Creates a new instance of the class. - /// - /// The public key data. - /// The hash algorithm type for computing signature data. - protected PublicKey(byte[] data, HashAlgorithmType type) - { - type.GetHashAlgorithmName(); + type.GetHashAlgorithmName(); - KeyData = data; - AlgorithmType = type; - } + KeyData = data; + AlgorithmType = type; + } - /// - /// Gets the underlying public key data. - /// - protected byte[] KeyData { get; } + /// + /// Gets the underlying public key data. + /// + protected byte[] KeyData { get; } - /// - /// Gets the hash algorithm type for computing signature data. - /// - public HashAlgorithmType AlgorithmType { get; } - } + /// + /// Gets the hash algorithm type for computing signature data. + /// + public HashAlgorithmType AlgorithmType { get; } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.Equatable.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.Equatable.cs index edf568b..d4c66fe 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.Equatable.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,20 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(PrivateKey? other) { - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(PrivateKey? other) - { - return base.Equals(other) - && other is RsaPrivateKey rsaOther - && rsaOther.Padding == Padding; - } + return base.Equals(other) && other is RsaPrivateKey rsaOther && rsaOther.Padding == Padding; } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.Export.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.Export.cs index 2ff2c21..3acf64c 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.Export.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.Export.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,36 +15,35 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Exports the key in PKCS #8 format. + /// + /// Returns the key in PKCS #8 format. + public override byte[] ExportPkcs8Key() + { + using RSA privateKey = RSA.Create(); + + privateKey.ImportRSAPrivateKey(KeyData, out int _); + + return privateKey.ExportPkcs8PrivateKey(); + } + + /// + /// Exports the key in encrypted PKCS #8 format. + /// + /// The password to use for encryption. + /// The parameters required for password based encryption. + /// Returns the key in encrypted PKCS #8 format. + public override byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters) { - /// - /// Exports the key in PKCS #8 format. - /// - /// Returns the key in PKCS #8 format. - public override byte[] ExportPkcs8Key() - { - using RSA privateKey = RSA.Create(); - - privateKey.ImportRSAPrivateKey(KeyData, out int _); - - return privateKey.ExportPkcs8PrivateKey(); - } - - /// - /// Exports the key in encrypted PKCS #8 format. - /// - /// The password to use for encryption. - /// The parameters required for password based encryption. - /// Returns the key in encrypted PKCS #8 format. - public override byte[] ExportPkcs8Key(ReadOnlySpan password, PbeParameters parameters) - { - using RSA privateKey = RSA.Create(); - - privateKey.ImportRSAPrivateKey(KeyData, out int _); - - return privateKey.ExportEncryptedPkcs8PrivateKey(password, parameters); - } + using RSA privateKey = RSA.Create(); + + privateKey.ImportRSAPrivateKey(KeyData, out int _); + + return privateKey.ExportEncryptedPkcs8PrivateKey(password, parameters); } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.From.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.From.cs index 60bd2e5..f3e3317 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.From.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,72 +15,71 @@ using System.Security.Cryptography; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Creates an from the specified key data and hash algorithm type. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPrivateKey FromByteArray(byte[] key, HashAlgorithmType type, RSASignaturePadding padding) { - /// - /// Creates an from the specified key data and hash algorithm type. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPrivateKey FromByteArray(byte[] key, HashAlgorithmType type, RSASignaturePadding padding) - { - return new RsaPrivateKey(key, type, padding); - } + return new RsaPrivateKey(key, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPrivateKey FromBase16(Base16 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPrivateKey FromBase16(Base16 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPrivateKey FromBase32(Base32 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPrivateKey FromBase32(Base32 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPrivateKey FromBase58(Base58 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPrivateKey FromBase58(Base58 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPrivateKey FromBase64(Base64 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPrivateKey FromBase64(Base64 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.Get.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.Get.cs index 3e7ab8f..a9e27cf 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.Get.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.Get.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,22 +14,21 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Gets the public key component from this private key. + /// + /// Returns the public key component from this private key. + public override PublicKey GetPublicKey() { - /// - /// Gets the public key component from this private key. - /// - /// Returns the public key component from this private key. - public override PublicKey GetPublicKey() - { - using RSA privateKey = RSA.Create(); + using RSA privateKey = RSA.Create(); - privateKey.ImportRSAPrivateKey(KeyData, out int _); - byte[] publicKey = privateKey.ExportRSAPublicKey(); + privateKey.ImportRSAPrivateKey(KeyData, out int _); + byte[] publicKey = privateKey.ExportRSAPublicKey(); - return new RsaPublicKey(publicKey, AlgorithmType, Padding); - } + return new RsaPublicKey(publicKey, AlgorithmType, Padding); } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.Import.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.Import.cs index 6001966..7c1782b 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.Import.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.Import.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,153 +15,149 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Imports a PKCS #8 formatted key. + /// + /// The key data to import. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key(ReadOnlySpan data, HashAlgorithmType type, RSASignaturePadding padding) { - /// - /// Imports a PKCS #8 formatted key. - /// - /// The key data to import. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - ReadOnlySpan data, - HashAlgorithmType type, - RSASignaturePadding padding) - { - RSA privateKey = RSA.Create(); + RSA privateKey = RSA.Create(); - privateKey.ImportPkcs8PrivateKey(data, out int _); - byte[] bytes = privateKey.ExportRSAPrivateKey(); + privateKey.ImportPkcs8PrivateKey(data, out int _); + byte[] bytes = privateKey.ExportRSAPrivateKey(); - return FromByteArray(bytes, type, padding); - } + return FromByteArray(bytes, type, padding); + } - /// - /// Imports a PKCS #8 formatted key. - /// - /// The key data to import. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, type, padding); - } + /// + /// Imports a PKCS #8 formatted key. + /// + /// The key data to import. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - ReadOnlySpan data, - ReadOnlySpan password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - RSA privateKey = RSA.Create(); + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + ReadOnlySpan data, + ReadOnlySpan password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + RSA privateKey = RSA.Create(); - privateKey.ImportEncryptedPkcs8PrivateKey(password, data, out int _); - byte[] bytes = privateKey.ExportRSAPrivateKey(); + privateKey.ImportEncryptedPkcs8PrivateKey(password, data, out int _); + byte[] bytes = privateKey.ExportRSAPrivateKey(); - return FromByteArray(bytes, type, padding); - } + return FromByteArray(bytes, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - ReadOnlySpan data, - char[] password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - ReadOnlySpan characters = password.AsSpan(); - return ImportPkcs8Key(data, characters, type, padding); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + ReadOnlySpan data, + char[] password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + ReadOnlySpan characters = password.AsSpan(); + return ImportPkcs8Key(data, characters, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - ReadOnlySpan data, - string password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - ReadOnlySpan characters = password.AsSpan(); - return ImportPkcs8Key(data, characters, type, padding); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + ReadOnlySpan data, + string password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + ReadOnlySpan characters = password.AsSpan(); + return ImportPkcs8Key(data, characters, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - byte[] data, - ReadOnlySpan password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type, padding); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + byte[] data, + ReadOnlySpan password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - byte[] data, - char[] password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type, padding); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + byte[] data, + char[] password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type, padding); + } - /// - /// Imports an encrypted PKCS #8 formatted key. - /// - /// The key data to import. - /// The password to decrypt the key data. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified PKCS #8 key data. - public static RsaPrivateKey ImportPkcs8Key( - byte[] data, - string password, - HashAlgorithmType type, - RSASignaturePadding padding) - { - ReadOnlySpan bytes = data.AsSpan(); - return ImportPkcs8Key(bytes, password, type, padding); - } + /// + /// Imports an encrypted PKCS #8 formatted key. + /// + /// The key data to import. + /// The password to decrypt the key data. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified PKCS #8 key data. + public static RsaPrivateKey ImportPkcs8Key( + byte[] data, + string password, + HashAlgorithmType type, + RSASignaturePadding padding) + { + ReadOnlySpan bytes = data.AsSpan(); + return ImportPkcs8Key(bytes, password, type, padding); } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.Sign.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.Sign.cs index 5a52e67..5463d6d 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.Sign.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.Sign.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,40 +14,39 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPrivateKey { - public sealed partial class RsaPrivateKey + /// + /// Computes a from the specified unsigned data. + /// + /// The unsigned data from which to compute a . + /// Returns a from the specified unsigned data. + public override DigitalSignature SignData(byte[] unsignedData) + { + using RSA privateKey = RSA.Create(); + + privateKey.ImportRSAPrivateKey(KeyData, out int _); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + byte[] signedData = privateKey.SignData(unsignedData, name, Padding); + + return DigitalSignature.FromByteArray(signedData); + } + + /// + /// Computes a from the specified unsigned hash. + /// + /// The unsigned hash from which to compute a . + /// Returns a from the specified unsigned hash. + public override DigitalSignature SignHash(byte[] unsignedHash) { - /// - /// Computes a from the specified unsigned data. - /// - /// The unsigned data from which to compute a . - /// Returns a from the specified unsigned data. - public override DigitalSignature SignData(byte[] unsignedData) - { - using RSA privateKey = RSA.Create(); - - privateKey.ImportRSAPrivateKey(KeyData, out int _); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - byte[] signedData = privateKey.SignData(unsignedData, name, Padding); - - return DigitalSignature.FromByteArray(signedData); - } - - /// - /// Computes a from the specified unsigned hash. - /// - /// The unsigned hash from which to compute a . - /// Returns a from the specified unsigned hash. - public override DigitalSignature SignHash(byte[] unsignedHash) - { - using RSA privateKey = RSA.Create(); - - privateKey.ImportRSAPrivateKey(KeyData, out int _); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - byte[] signedData = privateKey.SignHash(unsignedHash, name, Padding); - - return DigitalSignature.FromByteArray(signedData); - } + using RSA privateKey = RSA.Create(); + + privateKey.ImportRSAPrivateKey(KeyData, out int _); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + byte[] signedData = privateKey.SignHash(unsignedHash, name, Padding); + + return DigitalSignature.FromByteArray(signedData); } } diff --git a/OnixLabs.Security.Cryptography/RsaPrivateKey.cs b/OnixLabs.Security.Cryptography/RsaPrivateKey.cs index 22f05f7..5d6d3e4 100644 --- a/OnixLabs.Security.Cryptography/RsaPrivateKey.cs +++ b/OnixLabs.Security.Cryptography/RsaPrivateKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,27 +14,26 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents an RSA private key. +/// +public sealed partial class RsaPrivateKey : PrivateKey { /// - /// Represents an RSA private key. + /// Creates a new instance of the class. /// - public sealed partial class RsaPrivateKey : PrivateKey + /// The private key data. + /// The hash algorithm type for computing signature data. + /// The for computing signature data. + internal RsaPrivateKey(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) : base(data, type) { - /// - /// Creates a new instance of the class. - /// - /// The private key data. - /// The hash algorithm type for computing signature data. - /// The for computing signature data. - internal RsaPrivateKey(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) : base(data, type) - { - Padding = padding; - } - - /// - /// Gets the for computing signature data. - /// - public RSASignaturePadding Padding { get; } + Padding = padding; } + + /// + /// Gets the for computing signature data. + /// + public RSASignaturePadding Padding { get; } } diff --git a/OnixLabs.Security.Cryptography/RsaPublicKey.Equatable.cs b/OnixLabs.Security.Cryptography/RsaPublicKey.Equatable.cs index dd590ea..21fd875 100644 --- a/OnixLabs.Security.Cryptography/RsaPublicKey.Equatable.cs +++ b/OnixLabs.Security.Cryptography/RsaPublicKey.Equatable.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,20 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPublicKey { - public sealed partial class RsaPublicKey + /// + /// Checks for equality between this instance and another object. + /// + /// The object to check for equality. + /// true if the object is equal to this instance; otherwise, false. + public override bool Equals(PublicKey? other) { - /// - /// Checks for equality between this instance and another object. - /// - /// The object to check for equality. - /// true if the object is equal to this instance; otherwise, false. - public override bool Equals(PublicKey? other) - { - return base.Equals(other) - && other is RsaPublicKey rsaOther - && rsaOther.Padding == Padding; - } + return base.Equals(other) && other is RsaPublicKey rsaOther && rsaOther.Padding == Padding; } } diff --git a/OnixLabs.Security.Cryptography/RsaPublicKey.From.cs b/OnixLabs.Security.Cryptography/RsaPublicKey.From.cs index 14b8ede..b024572 100644 --- a/OnixLabs.Security.Cryptography/RsaPublicKey.From.cs +++ b/OnixLabs.Security.Cryptography/RsaPublicKey.From.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,72 +15,71 @@ using System.Security.Cryptography; using OnixLabs.Core.Text; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPublicKey { - public sealed partial class RsaPublicKey + /// + /// Creates an from the specified key data and hash algorithm type. + /// + /// The key data from which to construct a public key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPublicKey FromByteArray(byte[] key, HashAlgorithmType type, RSASignaturePadding padding) { - /// - /// Creates an from the specified key data and hash algorithm type. - /// - /// The key data from which to construct a public key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPublicKey FromByteArray(byte[] key, HashAlgorithmType type, RSASignaturePadding padding) - { - return new RsaPublicKey(key, type, padding); - } + return new RsaPublicKey(key, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPublicKey FromBase16(Base16 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPublicKey FromBase16(Base16 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPublicKey FromBase32(Base32 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPublicKey FromBase32(Base32 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPublicKey FromBase58(Base58 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPublicKey FromBase58(Base58 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); + } - /// - /// Creates an from the specified value. - /// - /// The key data from which to construct a private key. - /// The for computing signature data. - /// The for computing signature data. - /// Returns an from the specified key data and hash algorithm type. - public static RsaPublicKey FromBase64(Base64 key, HashAlgorithmType type, RSASignaturePadding padding) - { - byte[] bytes = key.ToByteArray(); - return FromByteArray(bytes, type, padding); - } + /// + /// Creates an from the specified value. + /// + /// The key data from which to construct a private key. + /// The for computing signature data. + /// The for computing signature data. + /// Returns an from the specified key data and hash algorithm type. + public static RsaPublicKey FromBase64(Base64 key, HashAlgorithmType type, RSASignaturePadding padding) + { + byte[] bytes = key.ToByteArray(); + return FromByteArray(bytes, type, padding); } } diff --git a/OnixLabs.Security.Cryptography/RsaPublicKey.Verify.cs b/OnixLabs.Security.Cryptography/RsaPublicKey.Verify.cs index 47bcad2..c71ea71 100644 --- a/OnixLabs.Security.Cryptography/RsaPublicKey.Verify.cs +++ b/OnixLabs.Security.Cryptography/RsaPublicKey.Verify.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,42 +14,41 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public sealed partial class RsaPublicKey { - public sealed partial class RsaPublicKey + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned data to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public override bool IsDataValid(DigitalSignature signature, byte[] unsignedData) + { + using RSA publicKey = RSA.Create(); + + publicKey.ImportRSAPublicKey(KeyData, out int _); + byte[] signatureData = signature.ToByteArray(); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + + return publicKey.VerifyData(unsignedData, signatureData, name, Padding); + } + + /// + /// Determines whether the specified was signed by the private component of this public key. + /// + /// The to validate. + /// The unsigned hash to validate. + /// Returns true if the specified was signed by the private component of this public key; otherwise, false. + public override bool IsHashValid(DigitalSignature signature, byte[] unsignedHash) { - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned data to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public override bool IsDataValid(DigitalSignature signature, byte[] unsignedData) - { - using RSA publicKey = RSA.Create(); - - publicKey.ImportRSAPublicKey(KeyData, out int _); - byte[] signatureData = signature.ToByteArray(); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - - return publicKey.VerifyData(unsignedData, signatureData, name, Padding); - } - - /// - /// Determines whether the specified was signed by the private component of this public key. - /// - /// The to validate. - /// The unsigned hash to validate. - /// Returns true if the specified was signed by the private component of this public key; otherwise, false. - public override bool IsHashValid(DigitalSignature signature, byte[] unsignedHash) - { - using RSA publicKey = RSA.Create(); - - publicKey.ImportRSAPublicKey(KeyData, out int _); - byte[] signatureData = signature.ToByteArray(); - HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); - - return publicKey.VerifyHash(unsignedHash, signatureData, name, Padding); - } + using RSA publicKey = RSA.Create(); + + publicKey.ImportRSAPublicKey(KeyData, out int _); + byte[] signatureData = signature.ToByteArray(); + HashAlgorithmName name = AlgorithmType.GetHashAlgorithmName(); + + return publicKey.VerifyHash(unsignedHash, signatureData, name, Padding); } } diff --git a/OnixLabs.Security.Cryptography/RsaPublicKey.cs b/OnixLabs.Security.Cryptography/RsaPublicKey.cs index 1b5089e..1bcba28 100644 --- a/OnixLabs.Security.Cryptography/RsaPublicKey.cs +++ b/OnixLabs.Security.Cryptography/RsaPublicKey.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,27 +14,26 @@ using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Represents an RSA public key. +/// +public sealed partial class RsaPublicKey : PublicKey { /// - /// Represents an RSA public key. + /// Creates a new instance of the class. /// - public sealed partial class RsaPublicKey : PublicKey + /// The public key data. + /// The hash algorithm type for computing signature data. + /// The for computing signature data. + internal RsaPublicKey(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) : base(data, type) { - /// - /// Creates a new instance of the class. - /// - /// The public key data. - /// The hash algorithm type for computing signature data. - /// The for computing signature data. - internal RsaPublicKey(byte[] data, HashAlgorithmType type, RSASignaturePadding padding) : base(data, type) - { - Padding = padding; - } - - /// - /// Gets the for computing signature data. - /// - public RSASignaturePadding Padding { get; } + Padding = padding; } + + /// + /// Gets the for computing signature data. + /// + public RSASignaturePadding Padding { get; } } diff --git a/OnixLabs.Security.Cryptography/Sha3.Create.cs b/OnixLabs.Security.Cryptography/Sha3.Create.cs index 4835ade..d10375c 100644 --- a/OnixLabs.Security.Cryptography/Sha3.Create.cs +++ b/OnixLabs.Security.Cryptography/Sha3.Create.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,64 +12,63 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class Sha3 { - public abstract partial class Sha3 + /// + /// Creates an instance of the algorithm. + /// + /// An instance of the algorithm. + public static Sha3 CreateSha3Hash224() { - /// - /// Creates an instance of the algorithm. - /// - /// An instance of the algorithm. - public static Sha3 CreateSha3Hash224() - { - return new Sha3Hash224(); - } + return new Sha3Hash224(); + } - /// - /// Creates an instance of the algorithm. - /// - /// An instance of the algorithm. - public static Sha3 CreateSha3Hash256() - { - return new Sha3Hash256(); - } + /// + /// Creates an instance of the algorithm. + /// + /// An instance of the algorithm. + public static Sha3 CreateSha3Hash256() + { + return new Sha3Hash256(); + } - /// - /// Creates an instance of the algorithm. - /// - /// An instance of the algorithm. - public static Sha3 CreateSha3Hash384() - { - return new Sha3Hash384(); - } + /// + /// Creates an instance of the algorithm. + /// + /// An instance of the algorithm. + public static Sha3 CreateSha3Hash384() + { + return new Sha3Hash384(); + } - /// - /// Creates an instance of the algorithm. - /// - /// An instance of the algorithm. - public static Sha3 CreateSha3Hash512() - { - return new Sha3Hash512(); - } + /// + /// Creates an instance of the algorithm. + /// + /// An instance of the algorithm. + public static Sha3 CreateSha3Hash512() + { + return new Sha3Hash512(); + } - /// - /// Creates an instance of the algorithm. - /// - /// The output length of the hash in bytes. - /// An instance of the algorithm. - public static Sha3 CreateSha3Shake128(int length) - { - return new Sha3Shake128(length); - } + /// + /// Creates an instance of the algorithm. + /// + /// The output length of the hash in bytes. + /// An instance of the algorithm. + public static Sha3 CreateSha3Shake128(int length) + { + return new Sha3Shake128(length); + } - /// - /// Creates an instance of the algorithm. - /// - /// The output length of the hash in bytes. - /// An instance of the algorithm. - public static Sha3 CreateSha3Shake256(int length) - { - return new Sha3Shake256(length); - } + /// + /// Creates an instance of the algorithm. + /// + /// The output length of the hash in bytes. + /// An instance of the algorithm. + public static Sha3 CreateSha3Shake256(int length) + { + return new Sha3Shake256(length); } } diff --git a/OnixLabs.Security.Cryptography/Sha3.Permute.cs b/OnixLabs.Security.Cryptography/Sha3.Permute.cs index 9885b76..948cf03 100644 --- a/OnixLabs.Security.Cryptography/Sha3.Permute.cs +++ b/OnixLabs.Security.Cryptography/Sha3.Permute.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,142 +14,141 @@ using System.Runtime.CompilerServices; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +public abstract partial class Sha3 { - public abstract partial class Sha3 + /// + /// Performs the FIPS 202 SHA-3 permutation. + /// + /// The state upon which to perform the permutation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Permute(ulong[] state) { - /// - /// Performs the FIPS 202 SHA-3 permutation. - /// - /// The state upon which to perform the permutation. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Permute(ulong[] state) - { - const int hashRounds = 24; + const int hashRounds = 24; - ulong c0, c1, c2, c3, c4, d0, d1, d2, d3, d4; + ulong c0, c1, c2, c3, c4, d0, d1, d2, d3, d4; - ulong[] roundConstants = - { - 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, - 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, - 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, - 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, - 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, - 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008 - }; + ulong[] roundConstants = + { + 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, + 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, + 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008 + }; - for (int round = 0; round < hashRounds; round++) - { - Theta(); - RhoPi(); - Chi(); - Iota(round); - } + for (int round = 0; round < hashRounds; round++) + { + Theta(); + RhoPi(); + Chi(); + Iota(round); + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void Theta() - { - c0 = state[0] ^ state[5] ^ state[10] ^ state[15] ^ state[20]; - c1 = state[1] ^ state[6] ^ state[11] ^ state[16] ^ state[21]; - c2 = state[2] ^ state[7] ^ state[12] ^ state[17] ^ state[22]; - c3 = state[3] ^ state[8] ^ state[13] ^ state[18] ^ state[23]; - c4 = state[4] ^ state[9] ^ state[14] ^ state[19] ^ state[24]; + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + void Theta() + { + c0 = state[0] ^ state[5] ^ state[10] ^ state[15] ^ state[20]; + c1 = state[1] ^ state[6] ^ state[11] ^ state[16] ^ state[21]; + c2 = state[2] ^ state[7] ^ state[12] ^ state[17] ^ state[22]; + c3 = state[3] ^ state[8] ^ state[13] ^ state[18] ^ state[23]; + c4 = state[4] ^ state[9] ^ state[14] ^ state[19] ^ state[24]; - d0 = RotateLeft(c1, 1) ^ c4; - d1 = RotateLeft(c2, 1) ^ c0; - d2 = RotateLeft(c3, 1) ^ c1; - d3 = RotateLeft(c4, 1) ^ c2; - d4 = RotateLeft(c0, 1) ^ c3; + d0 = RotateLeft(c1, 1) ^ c4; + d1 = RotateLeft(c2, 1) ^ c0; + d2 = RotateLeft(c3, 1) ^ c1; + d3 = RotateLeft(c4, 1) ^ c2; + d4 = RotateLeft(c0, 1) ^ c3; - state[00] ^= d0; - state[05] ^= d0; - state[10] ^= d0; - state[15] ^= d0; - state[20] ^= d0; - state[01] ^= d1; - state[06] ^= d1; - state[11] ^= d1; - state[16] ^= d1; - state[21] ^= d1; - state[02] ^= d2; - state[07] ^= d2; - state[12] ^= d2; - state[17] ^= d2; - state[22] ^= d2; - state[03] ^= d3; - state[08] ^= d3; - state[13] ^= d3; - state[18] ^= d3; - state[23] ^= d3; - state[04] ^= d4; - state[09] ^= d4; - state[14] ^= d4; - state[19] ^= d4; - state[24] ^= d4; - } + state[00] ^= d0; + state[05] ^= d0; + state[10] ^= d0; + state[15] ^= d0; + state[20] ^= d0; + state[01] ^= d1; + state[06] ^= d1; + state[11] ^= d1; + state[16] ^= d1; + state[21] ^= d1; + state[02] ^= d2; + state[07] ^= d2; + state[12] ^= d2; + state[17] ^= d2; + state[22] ^= d2; + state[03] ^= d3; + state[08] ^= d3; + state[13] ^= d3; + state[18] ^= d3; + state[23] ^= d3; + state[04] ^= d4; + state[09] ^= d4; + state[14] ^= d4; + state[19] ^= d4; + state[24] ^= d4; + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void RhoPi() - { - ulong final = RotateLeft(state[1], 1); + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + void RhoPi() + { + ulong final = RotateLeft(state[1], 1); - state[01] = RotateLeft(state[06], 44); - state[06] = RotateLeft(state[09], 20); - state[09] = RotateLeft(state[22], 61); - state[22] = RotateLeft(state[14], 39); - state[14] = RotateLeft(state[20], 18); - state[20] = RotateLeft(state[02], 62); - state[02] = RotateLeft(state[12], 43); - state[12] = RotateLeft(state[13], 25); - state[13] = RotateLeft(state[19], 08); - state[19] = RotateLeft(state[23], 56); - state[23] = RotateLeft(state[15], 41); - state[15] = RotateLeft(state[04], 27); - state[04] = RotateLeft(state[24], 14); - state[24] = RotateLeft(state[21], 02); - state[21] = RotateLeft(state[08], 55); - state[08] = RotateLeft(state[16], 45); - state[16] = RotateLeft(state[05], 36); - state[05] = RotateLeft(state[03], 28); - state[03] = RotateLeft(state[18], 21); - state[18] = RotateLeft(state[17], 15); - state[17] = RotateLeft(state[11], 10); - state[11] = RotateLeft(state[07], 06); - state[07] = RotateLeft(state[10], 03); - state[10] = final; - } + state[01] = RotateLeft(state[06], 44); + state[06] = RotateLeft(state[09], 20); + state[09] = RotateLeft(state[22], 61); + state[22] = RotateLeft(state[14], 39); + state[14] = RotateLeft(state[20], 18); + state[20] = RotateLeft(state[02], 62); + state[02] = RotateLeft(state[12], 43); + state[12] = RotateLeft(state[13], 25); + state[13] = RotateLeft(state[19], 08); + state[19] = RotateLeft(state[23], 56); + state[23] = RotateLeft(state[15], 41); + state[15] = RotateLeft(state[04], 27); + state[04] = RotateLeft(state[24], 14); + state[24] = RotateLeft(state[21], 02); + state[21] = RotateLeft(state[08], 55); + state[08] = RotateLeft(state[16], 45); + state[16] = RotateLeft(state[05], 36); + state[05] = RotateLeft(state[03], 28); + state[03] = RotateLeft(state[18], 21); + state[18] = RotateLeft(state[17], 15); + state[17] = RotateLeft(state[11], 10); + state[11] = RotateLeft(state[07], 06); + state[07] = RotateLeft(state[10], 03); + state[10] = final; + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void Chi() + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + void Chi() + { + for (int i = 0; i < 25; i += 5) { - for (int i = 0; i < 25; i += 5) - { - c0 = state[0 + i] ^ ((~state[1 + i]) & state[2 + i]); - c1 = state[1 + i] ^ ((~state[2 + i]) & state[3 + i]); - c2 = state[2 + i] ^ ((~state[3 + i]) & state[4 + i]); - c3 = state[3 + i] ^ ((~state[4 + i]) & state[0 + i]); - c4 = state[4 + i] ^ ((~state[0 + i]) & state[1 + i]); + c0 = state[0 + i] ^ ((~state[1 + i]) & state[2 + i]); + c1 = state[1 + i] ^ ((~state[2 + i]) & state[3 + i]); + c2 = state[2 + i] ^ ((~state[3 + i]) & state[4 + i]); + c3 = state[3 + i] ^ ((~state[4 + i]) & state[0 + i]); + c4 = state[4 + i] ^ ((~state[0 + i]) & state[1 + i]); - state[0 + i] = c0; - state[1 + i] = c1; - state[2 + i] = c2; - state[3 + i] = c3; - state[4 + i] = c4; - } + state[0 + i] = c0; + state[1 + i] = c1; + state[2 + i] = c2; + state[3 + i] = c3; + state[4 + i] = c4; } + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void Iota(int round) - { - state[0] ^= roundConstants[round]; - } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + void Iota(int round) + { + state[0] ^= roundConstants[round]; + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - ulong RotateLeft(ulong x, byte y) - { - return (x << y) | (x >> (64 - y)); - } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + ulong RotateLeft(ulong x, byte y) + { + return (x << y) | (x >> (64 - y)); } } } diff --git a/OnixLabs.Security.Cryptography/Sha3.cs b/OnixLabs.Security.Cryptography/Sha3.cs index 67abda7..34f8a7f 100644 --- a/OnixLabs.Security.Cryptography/Sha3.cs +++ b/OnixLabs.Security.Cryptography/Sha3.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,151 +15,150 @@ using System; using System.Security.Cryptography; -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 hash for the input data. +/// +public abstract partial class Sha3 : HashAlgorithm { /// - /// Computes the FIPS 202 SHA-3 hash for the input data. + /// The delimiter used for hash implementations. /// - public abstract partial class Sha3 : HashAlgorithm - { - /// - /// The delimiter used for hash implementations. - /// - protected const int HashDelimiter = 0x06; - - /// - /// The delimiter used for Shake implementations. - /// - protected const int ShakeDelimiter = 0x1f; - - /// - /// The rate in bytes of the sponge state. - /// - private readonly int rateBytes; - - /// - /// The state delimiter. - /// - private readonly int delimiter; - - /// - /// The length of the hash in bits. - /// - private readonly int bitLength; - - /// - /// The state block size. - /// - private int blockSize; - - /// - /// The state input pointer. - /// - private int inputPointer; - - /// - /// The state output pointer. - /// - private int outputPointer; - - /// - /// The permutable sponge state. - /// - private ulong[] state = Array.Empty(); - - /// - /// The hash result. - /// - private byte[] result = Array.Empty(); - - /// - /// Creates a new instance of the class. - /// - /// The rate in bytes of the sponge state. - /// The state delimiter. - /// The output length of the hash in bits. - protected Sha3(int rateBytes, int delimiter, int bitLength) - { - this.rateBytes = rateBytes; - this.delimiter = delimiter; - this.bitLength = bitLength; - } + protected const int HashDelimiter = 0x06; - /// - /// Initializes an implementation of the class. - /// - public override void Initialize() - { - blockSize = default; - inputPointer = default; - outputPointer = default; - state = new ulong[25]; - result = new byte[bitLength / 8]; - } + /// + /// The delimiter used for Shake implementations. + /// + protected const int ShakeDelimiter = 0x1f; - /// - /// Routes data written to the object into the hash algorithm for computing the hash. - /// - /// The input to compute the hash code for. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the byte array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - Initialize(); + /// + /// The rate in bytes of the sponge state. + /// + private readonly int rateBytes; - while (cbSize > 0) - { - blockSize = Math.Min(cbSize, rateBytes); + /// + /// The state delimiter. + /// + private readonly int delimiter; + + /// + /// The length of the hash in bits. + /// + private readonly int bitLength; - for (int index = ibStart; index < blockSize; index++) - { - byte x = Convert.ToByte(Buffer.GetByte(state, index) ^ array[index + inputPointer]); - Buffer.SetByte(state, index, x); - } + /// + /// The state block size. + /// + private int blockSize; - inputPointer += blockSize; - cbSize -= blockSize; + /// + /// The state input pointer. + /// + private int inputPointer; - if (blockSize != rateBytes) continue; - Permute(state); - blockSize = 0; - } - } + /// + /// The state output pointer. + /// + private int outputPointer; + + /// + /// The permutable sponge state. + /// + private ulong[] state = Array.Empty(); + + /// + /// The hash result. + /// + private byte[] result = Array.Empty(); - /// - /// Finalizes the hash computation after the last data is processed by the cryptographic stream object. - /// - /// The computed hash code. - protected override byte[] HashFinal() + /// + /// Creates a new instance of the class. + /// + /// The rate in bytes of the sponge state. + /// The state delimiter. + /// The output length of the hash in bits. + protected Sha3(int rateBytes, int delimiter, int bitLength) + { + this.rateBytes = rateBytes; + this.delimiter = delimiter; + this.bitLength = bitLength; + } + + /// + /// Initializes an implementation of the class. + /// + public override void Initialize() + { + blockSize = default; + inputPointer = default; + outputPointer = default; + state = new ulong[25]; + result = new byte[bitLength / 8]; + } + + /// + /// Routes data written to the object into the hash algorithm for computing the hash. + /// + /// The input to compute the hash code for. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the byte array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + Initialize(); + + while (cbSize > 0) { - byte pad = Convert.ToByte(Buffer.GetByte(state, blockSize) ^ delimiter); - Buffer.SetByte(state, blockSize, pad); + blockSize = Math.Min(cbSize, rateBytes); - if (((delimiter & 0x80) != 0) && blockSize == (rateBytes - 1)) + for (int index = ibStart; index < blockSize; index++) { - Permute(state); + byte x = Convert.ToByte(Buffer.GetByte(state, index) ^ array[index + inputPointer]); + Buffer.SetByte(state, index, x); } - pad = Convert.ToByte(Buffer.GetByte(state, rateBytes - 1) ^ 0x80); - Buffer.SetByte(state, rateBytes - 1, pad); + inputPointer += blockSize; + cbSize -= blockSize; + + if (blockSize != rateBytes) continue; Permute(state); + blockSize = 0; + } + } + + /// + /// Finalizes the hash computation after the last data is processed by the cryptographic stream object. + /// + /// The computed hash code. + protected override byte[] HashFinal() + { + byte pad = Convert.ToByte(Buffer.GetByte(state, blockSize) ^ delimiter); + Buffer.SetByte(state, blockSize, pad); + + if (((delimiter & 0x80) != 0) && blockSize == (rateBytes - 1)) + { + Permute(state); + } + + pad = Convert.ToByte(Buffer.GetByte(state, rateBytes - 1) ^ 0x80); + Buffer.SetByte(state, rateBytes - 1, pad); + Permute(state); + + int outputBytesLeft = bitLength / 8; - int outputBytesLeft = bitLength / 8; + while (outputBytesLeft > 0) + { + blockSize = Math.Min(outputBytesLeft, rateBytes); + Buffer.BlockCopy(state, 0, result, outputPointer, blockSize); + outputPointer += blockSize; + outputBytesLeft -= blockSize; - while (outputBytesLeft > 0) + if (outputBytesLeft > 0) { - blockSize = Math.Min(outputBytesLeft, rateBytes); - Buffer.BlockCopy(state, 0, result, outputPointer, blockSize); - outputPointer += blockSize; - outputBytesLeft -= blockSize; - - if (outputBytesLeft > 0) - { - Permute(state); - } + Permute(state); } - - return result; } + + return result; } } diff --git a/OnixLabs.Security.Cryptography/Sha3Hash224.cs b/OnixLabs.Security.Cryptography/Sha3Hash224.cs index 1080236..a2a375e 100644 --- a/OnixLabs.Security.Cryptography/Sha3Hash224.cs +++ b/OnixLabs.Security.Cryptography/Sha3Hash224.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 224-bit hash for the input data. +/// +public sealed class Sha3Hash224 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 224-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Hash224 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 144; + private const int RateBytes = 144; - /// - /// The length of the hash in bits. - /// - private const int BitLength = 224; + /// + /// The length of the hash in bits. + /// + private const int BitLength = 224; - /// - /// Creates a new instance of the class. - /// - public Sha3Hash224() : base(RateBytes, HashDelimiter, BitLength) - { - } + /// + /// Creates a new instance of the class. + /// + public Sha3Hash224() : base(RateBytes, HashDelimiter, BitLength) + { } } diff --git a/OnixLabs.Security.Cryptography/Sha3Hash256.cs b/OnixLabs.Security.Cryptography/Sha3Hash256.cs index 222c2a9..c81f188 100644 --- a/OnixLabs.Security.Cryptography/Sha3Hash256.cs +++ b/OnixLabs.Security.Cryptography/Sha3Hash256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 256-bit hash for the input data. +/// +public sealed class Sha3Hash256 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 256-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Hash256 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 136; + private const int RateBytes = 136; - /// - /// The length of the hash in bits. - /// - private const int BitLength = 256; + /// + /// The length of the hash in bits. + /// + private const int BitLength = 256; - /// - /// Creates a new instance of the class. - /// - public Sha3Hash256() : base(RateBytes, HashDelimiter, BitLength) - { - } + /// + /// Creates a new instance of the class. + /// + public Sha3Hash256() : base(RateBytes, HashDelimiter, BitLength) + { } } diff --git a/OnixLabs.Security.Cryptography/Sha3Hash384.cs b/OnixLabs.Security.Cryptography/Sha3Hash384.cs index d60a022..373d70d 100644 --- a/OnixLabs.Security.Cryptography/Sha3Hash384.cs +++ b/OnixLabs.Security.Cryptography/Sha3Hash384.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 384-bit hash for the input data. +/// +public sealed class Sha3Hash384 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 384-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Hash384 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 104; + private const int RateBytes = 104; - /// - /// The length of the hash in bits. - /// - private const int BitLength = 384; + /// + /// The length of the hash in bits. + /// + private const int BitLength = 384; - /// - /// Creates a new instance of the class. - /// - public Sha3Hash384() : base(RateBytes, HashDelimiter, BitLength) - { - } + /// + /// Creates a new instance of the class. + /// + public Sha3Hash384() : base(RateBytes, HashDelimiter, BitLength) + { } } diff --git a/OnixLabs.Security.Cryptography/Sha3Hash512.cs b/OnixLabs.Security.Cryptography/Sha3Hash512.cs index c7d2971..528e9a1 100644 --- a/OnixLabs.Security.Cryptography/Sha3Hash512.cs +++ b/OnixLabs.Security.Cryptography/Sha3Hash512.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,28 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 512-bit hash for the input data. +/// +public sealed class Sha3Hash512 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 512-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Hash512 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 72; + private const int RateBytes = 72; + + /// + /// The length of the hash in bits. + /// + private const int BitLength = 512; - /// - /// The length of the hash in bits. - /// - private const int BitLength = 512; - - /// - /// Creates a new instance of the class. - /// - public Sha3Hash512() : base(RateBytes, HashDelimiter, BitLength) - { - } + /// + /// Creates a new instance of the class. + /// + public Sha3Hash512() : base(RateBytes, HashDelimiter, BitLength) + { } } diff --git a/OnixLabs.Security.Cryptography/Sha3Shake128.cs b/OnixLabs.Security.Cryptography/Sha3Shake128.cs index 44865f2..ca3e692 100644 --- a/OnixLabs.Security.Cryptography/Sha3Shake128.cs +++ b/OnixLabs.Security.Cryptography/Sha3Shake128.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,29 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 Shake 128-bit hash for the input data. +/// +public sealed class Sha3Shake128 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 Shake 128-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Shake128 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 168; + private const int RateBytes = 168; - /// - /// The length multiplier of the hash in bits. - /// - private const int BitLengthMultiplier = 8; + /// + /// The length multiplier of the hash in bits. + /// + private const int BitLengthMultiplier = 8; - /// - /// Creates a new instance of the class. - /// - /// The hash output length in bytes. - public Sha3Shake128(int length) : base(RateBytes, ShakeDelimiter, length * BitLengthMultiplier) - { - } + /// + /// Creates a new instance of the class. + /// + /// The hash output length in bytes. + public Sha3Shake128(int length) : base(RateBytes, ShakeDelimiter, length * BitLengthMultiplier) + { } } diff --git a/OnixLabs.Security.Cryptography/Sha3Shake256.cs b/OnixLabs.Security.Cryptography/Sha3Shake256.cs index 858ecd5..fb82f5c 100644 --- a/OnixLabs.Security.Cryptography/Sha3Shake256.cs +++ b/OnixLabs.Security.Cryptography/Sha3Shake256.cs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 ONIXLabs +// Copyright 2020-2022 ONIXLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,29 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace OnixLabs.Security.Cryptography +namespace OnixLabs.Security.Cryptography; + +/// +/// Computes the FIPS 202 SHA-3 Shake 256-bit hash for the input data. +/// +public sealed class Sha3Shake256 : Sha3 { /// - /// Computes the FIPS 202 SHA-3 Shake 256-bit hash for the input data. + /// The rate in bytes of the sponge state. /// - public sealed class Sha3Shake256 : Sha3 - { - /// - /// The rate in bytes of the sponge state. - /// - private const int RateBytes = 136; + private const int RateBytes = 136; - /// - /// The length multiplier of the hash in bits. - /// - private const int BitLengthMultiplier = 8; + /// + /// The length multiplier of the hash in bits. + /// + private const int BitLengthMultiplier = 8; - /// - /// Creates a new instance of the class. - /// - /// The hash output length in bytes. - public Sha3Shake256(int length) : base(RateBytes, ShakeDelimiter, length * BitLengthMultiplier) - { - } + /// + /// Creates a new instance of the class. + /// + /// The hash output length in bytes. + public Sha3Shake256(int length) : base(RateBytes, ShakeDelimiter, length * BitLengthMultiplier) + { } } diff --git a/README.md b/README.md index 465b274..ec13de8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![ONIX Labs](https://raw.githubusercontent.com/onix-labs/onix-labs.github.io/master/content/logo/master_full_md.png) +![ONIX Labs](https://raw.githubusercontent.com/onix-labs/onixlabs-website/main/src/assets/images/logo/full/original/original-md.png) # ONIXLabs Core APIs for .NET