Skip to content

Add SymmetricAlgorithm.SetKey(ROSpan) #113146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ public class AesCipherOneShotTests : SymmetricOneShotBase
public void OneShotRoundtrip(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize);

[Theory]
[MemberData(nameof(TestCases))]
public void OneShotRoundtrip_ViaSetKey(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize, viaSetKey: true);

[Theory]
[MemberData(nameof(TestCases))]
public void TryDecryptOneShot_DestinationTooSmall(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,35 @@ public static void DecryptKnownCFB128_128()
TestAesDecrypt(CipherMode.CFB, s_aes128Key, s_aes256CbcIv, encryptedBytes, s_multiBlockBytes, 128);
}

[Fact]
public static void SetKey_Sanity()
{
using (Aes one = AesFactory.Create())
using (Aes two = AesFactory.Create())
{
byte[] key = new byte[16];
RandomNumberGenerator.Fill(key);
one.SetKey(key);
two.Key = key;
two.IV = one.IV;

using (ICryptoTransform e1 = one.CreateEncryptor())
using (ICryptoTransform e2 = two.CreateEncryptor())
using (ICryptoTransform d1 = one.CreateDecryptor())
using (ICryptoTransform d2 = two.CreateDecryptor())
{
byte[] c1 = e1.TransformFinalBlock(key, 0, key.Length);
byte[] c2 = e2.TransformFinalBlock(key, 0, key.Length);
Assert.Equal(c1, c2);

byte[] p1 = d1.TransformFinalBlock(c1, 0, c1.Length);
byte[] p2 = d2.TransformFinalBlock(c2, 0, c2.Length);
Assert.Equal(p1, p2);
Assert.Equal(key, p1);
}
}
}

[Fact]
public static void VerifyInPlaceEncryption()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ public static void InvalidKeySizes(int invalidKeySize, bool skipOnNetfx)

e = Record.Exception(() => aes.CreateDecryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");

e = Record.Exception(() => aes.Key = key);
Assert.True(e is CryptographicException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");

e = Record.Exception(() => aes.SetKey(key));
Assert.True(e is CryptographicException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");
}
}

Expand Down Expand Up @@ -197,6 +203,38 @@ public static void InvalidIVSizes(int invalidIvSize, bool skipOnNetfx)
}
}

[Fact]
public static void SetKey_SetsKey()
{
using (Aes aes = AesFactory.Create())
{
byte[] key = new byte[16];
RandomNumberGenerator.Fill(key);

aes.SetKey(key);
Assert.Equal(key, aes.Key);
}
}

[Fact]
public static void SetKey_SetsKeySize()
{
Span<byte> bigKey = stackalloc byte[32];
RandomNumberGenerator.Fill(bigKey);

using (Aes aes = AesFactory.Create())
{
foreach (KeySizes keySize in aes.LegalKeySizes)
{
for (int i = keySize.MinSize; i <= keySize.MaxSize; i += keySize.SkipSize)
{
aes.SetKey(bigKey.Slice(0, i / 8));
Assert.Equal(i, aes.KeySize);
}
}
}
}

[Fact]
public static void VerifyKeyGeneration_Default()
{
Expand Down Expand Up @@ -406,6 +444,66 @@ public static void Cfb8ModeCanDepadCfb128Padding()
}
}

[Theory]
[InlineData(128)]
[InlineData(192)]
[InlineData(256)]
public static void SetKeySize_MakesRandomKey(int keySize)
{
for (int i = 0; i < 2; i++)
{
bool createEncryptorFirst = i == 0;
byte[] one;
byte[] exported;
byte[] iv;

using (Aes aes = AesFactory.Create())
{
aes.KeySize = keySize;

if (createEncryptorFirst)
{
using (ICryptoTransform enc = aes.CreateEncryptor())
{
one = enc.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
}

iv = aes.IV;
}
else
{
iv = aes.IV;
one = aes.EncryptCbc(ReadOnlySpan<byte>.Empty, iv);
}

exported = aes.Key;
}

Assert.Equal(keySize / 8, exported.Length);
byte[] two;

using (Aes aes = AesFactory.Create())
{
aes.IV = iv;
aes.Key = exported;

if (createEncryptorFirst)
{
two = aes.EncryptCbc(ReadOnlySpan<byte>.Empty, iv);
}
else
{
using (ICryptoTransform enc = aes.CreateEncryptor())
{
two = enc.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
}
}
}

Assert.Equal(one, two);
}
}

private static void ValidateTransformProperties(Aes aes, ICryptoTransform transform)
{
Assert.NotNull(transform);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ public class DesCipherOneShotTests : SymmetricOneShotBase
public void OneShotRoundtrip(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize);

[Theory]
[MemberData(nameof(TestCases))]
public void OneShotRoundtrip_ViaSetKey(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize, viaSetKey: true);

[Theory]
[MemberData(nameof(TestCases))]
public void TryDecryptOneShot_DestinationTooSmall(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,5 +651,34 @@ public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);
Assert.Equal(ExpectedOutput, decrypted);
}

[Fact]
public static void SetKey_Sanity()
{
using (DES one = DESFactory.Create())
using (DES two = DESFactory.Create())
{
byte[] key = new byte[one.KeySize / 8];
RandomNumberGenerator.Fill(key);
one.SetKey(key);
two.Key = key;
two.IV = one.IV;

using (ICryptoTransform e1 = one.CreateEncryptor())
using (ICryptoTransform e2 = two.CreateEncryptor())
using (ICryptoTransform d1 = one.CreateDecryptor())
using (ICryptoTransform d2 = two.CreateDecryptor())
{
byte[] c1 = e1.TransformFinalBlock(key, 0, key.Length);
byte[] c2 = e2.TransformFinalBlock(key, 0, key.Length);
Assert.Equal(c1, c2);

byte[] p1 = d1.TransformFinalBlock(c1, 0, c1.Length);
byte[] p2 = d2.TransformFinalBlock(c2, 0, c2.Length);
Assert.Equal(p1, p2);
Assert.Equal(key, p1);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public class RC2CipherOneShotTests : SymmetricOneShotBase
public void OneShotRoundtrip(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode);

[Theory]
[MemberData(nameof(TestCases))]
public void OneShotRoundtrip_ViaSetKey(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize, viaSetKey: true);

[Theory]
[MemberData(nameof(TestCases))]
public void TryDecryptOneShot_DestinationTooSmall(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -402,5 +402,34 @@ public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);
Assert.Equal(ExpectedOutput, decrypted);
}

[Fact]
public static void SetKey_Sanity()
{
using (RC2 one = RC2Factory.Create())
using (RC2 two = RC2Factory.Create())
{
byte[] key = new byte[one.KeySize / 8];
RandomNumberGenerator.Fill(key);
one.SetKey(key);
two.Key = key;
two.IV = one.IV;

using (ICryptoTransform e1 = one.CreateEncryptor())
using (ICryptoTransform e2 = two.CreateEncryptor())
using (ICryptoTransform d1 = one.CreateDecryptor())
using (ICryptoTransform d2 = two.CreateDecryptor())
{
byte[] c1 = e1.TransformFinalBlock(key, 0, key.Length);
byte[] c2 = e2.TransformFinalBlock(key, 0, key.Length);
Assert.Equal(c1, c2);

byte[] p1 = d1.TransformFinalBlock(c1, 0, c1.Length);
byte[] p2 = d2.TransformFinalBlock(c2, 0, c2.Length);
Assert.Equal(p1, p2);
Assert.Equal(key, p1);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Security.Cryptography;
using Microsoft.DotNet.XUnitExtensions;
using Test.Cryptography;
using Xunit;

namespace System.Security.Cryptography.Tests
Expand All @@ -18,12 +14,26 @@ public abstract class SymmetricOneShotBase
protected abstract byte[] IV { get; }
protected abstract SymmetricAlgorithm CreateAlgorithm();

protected void OneShotRoundtripTest(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0)
protected void OneShotRoundtripTest(
byte[] plaintext,
byte[] ciphertext,
PaddingMode padding,
CipherMode mode,
int feedbackSize = 0,
bool viaSetKey = false)
{
using (SymmetricAlgorithm alg = CreateAlgorithm())
{
int paddingSizeBytes = mode == CipherMode.CFB ? feedbackSize / 8 : alg.BlockSize / 8;
alg.Key = Key;

if (viaSetKey)
{
alg.SetKey(Key);
}
else
{
alg.Key = Key;
}

// Set the instance to use a different mode and padding than what will be used
// in the one-shots to test that the one shot "wins".
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public class TripleDESCipherOneShotTests : SymmetricOneShotBase
public void OneShotRoundtrip(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize);

[Theory]
[MemberData(nameof(TestCases))]
public void OneShotRoundtrip_ViaSetKey(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
OneShotRoundtripTest(plaintext, ciphertext, padding, mode, feedbackSize, viaSetKey: true);

[Theory]
[MemberData(nameof(TestCases))]
public void TryDecryptOneShot_DestinationTooSmall(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,35 @@ public static void TripleDESInvalidKeySizes()
}
}

[Fact]
public static void SetKey_Sanity()
{
using (TripleDES one = TripleDESFactory.Create())
using (TripleDES two = TripleDESFactory.Create())
{
byte[] key = new byte[one.KeySize / 8];
RandomNumberGenerator.Fill(key);
one.SetKey(key);
two.Key = key;
two.IV = one.IV;

using (ICryptoTransform e1 = one.CreateEncryptor())
using (ICryptoTransform e2 = two.CreateEncryptor())
using (ICryptoTransform d1 = one.CreateDecryptor())
using (ICryptoTransform d2 = two.CreateDecryptor())
{
byte[] c1 = e1.TransformFinalBlock(key, 0, key.Length);
byte[] c2 = e2.TransformFinalBlock(key, 0, key.Length);
Assert.Equal(c1, c2);

byte[] p1 = d1.TransformFinalBlock(c1, 0, c1.Length);
byte[] p2 = d2.TransformFinalBlock(c2, 0, c2.Length);
Assert.Equal(p1, p2);
Assert.Equal(key, p1);
}
}
}

[Theory]
[InlineData(PaddingMode.None)]
[InlineData(PaddingMode.Zeros)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,18 @@ public static void Cfb8ModeCanDepadCfb64Padding()
Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, decrypted);
}
}

[Fact]
public static void SetKey_SetsKey()
{
using (TripleDES des = TripleDESFactory.Create())
{
byte[] key = new byte[des.KeySize / 8];
RandomNumberGenerator.Fill(key);

des.SetKey(key);
Assert.Equal(key, des.Key);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2743,6 +2743,8 @@ protected virtual void Dispose(bool disposing) { }
public int GetCiphertextLengthCbc(int plaintextLength, System.Security.Cryptography.PaddingMode paddingMode = System.Security.Cryptography.PaddingMode.PKCS7) { throw null; }
public int GetCiphertextLengthCfb(int plaintextLength, System.Security.Cryptography.PaddingMode paddingMode = System.Security.Cryptography.PaddingMode.None, int feedbackSizeInBits = 8) { throw null; }
public int GetCiphertextLengthEcb(int plaintextLength, System.Security.Cryptography.PaddingMode paddingMode) { throw null; }
public void SetKey(System.ReadOnlySpan<byte> key) { }
protected virtual void SetKeyCore(System.ReadOnlySpan<byte> key) { }
public bool TryDecryptCbc(System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> iv, System.Span<byte> destination, out int bytesWritten, System.Security.Cryptography.PaddingMode paddingMode = System.Security.Cryptography.PaddingMode.PKCS7) { throw null; }
protected virtual bool TryDecryptCbcCore(System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> iv, System.Span<byte> destination, System.Security.Cryptography.PaddingMode paddingMode, out int bytesWritten) { throw null; }
public bool TryDecryptCfb(System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> iv, System.Span<byte> destination, out int bytesWritten, System.Security.Cryptography.PaddingMode paddingMode = System.Security.Cryptography.PaddingMode.None, int feedbackSizeInBits = 8) { throw null; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public override PaddingMode Padding
set { _impl.Padding = value; }
}

protected override void SetKeyCore(ReadOnlySpan<byte> key) => _impl.SetKey(key);

public override KeySizes[] LegalBlockSizes => _impl.LegalBlockSizes;
public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes;
public override ICryptoTransform CreateEncryptor() => _impl.CreateEncryptor();
Expand Down
Loading
Loading