Skip to content
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

RSABCrypt: Improve errors with public key only #100658

Merged
merged 2 commits into from
Apr 5, 2024
Merged
Changes from all 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 @@ -20,6 +20,7 @@ internal sealed class RSABCrypt : RSA

private SafeBCryptKeyHandle? _key;
private int _lastKeySize;
private bool _publicOnly;
vcsjones marked this conversation as resolved.
Show resolved Hide resolved

internal RSABCrypt()
{
Expand Down Expand Up @@ -51,11 +52,11 @@ private SafeBCryptKeyHandle GetKey()

SafeBCryptKeyHandle newKey = Interop.BCrypt.BCryptGenerateKeyPair(s_algHandle, keySize);
Interop.BCrypt.BCryptFinalizeKeyPair(newKey);
SetKey(newKey);
SetKey(newKey, publicOnly: false);
return newKey;
}

private void SetKey(SafeBCryptKeyHandle newKey)
private void SetKey(SafeBCryptKeyHandle newKey, bool publicOnly)
{
Debug.Assert(!newKey.IsInvalid);

Expand All @@ -65,6 +66,7 @@ private void SetKey(SafeBCryptKeyHandle newKey)

SafeBCryptKeyHandle? oldKey = Interlocked.Exchange(ref _key, newKey);
ForceSetKeySize(keySize);
_publicOnly = publicOnly;
oldKey?.Dispose();
}

Expand Down Expand Up @@ -112,7 +114,7 @@ public override void ImportParameters(RSAParameters parameters)
CryptoPool.Return(keyBlob);
}

SetKey(newKey);
SetKey(newKey, publicOnly: parameters.D is null);
}

public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
Expand Down Expand Up @@ -190,6 +192,8 @@ public override bool TryDecrypt(
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}

ThrowIfPublicOnly();

switch (padding.Mode)
{
case RSAEncryptionPaddingMode.Pkcs1:
Expand Down Expand Up @@ -261,6 +265,7 @@ public override bool TrySignHash(
string? hashAlgorithmName = hashAlgorithm.Name;
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithmName, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfPublicOnly();

SafeBCryptKeyHandle key = GetKey();

Expand Down Expand Up @@ -426,5 +431,13 @@ private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_lastKeySize < 0, this);
}

private void ThrowIfPublicOnly()
{
if (_publicOnly)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
}
}
}
Loading