@@ -26,9 +26,6 @@ internal sealed partial class DefaultHybridCache : HybridCache
26
26
{
27
27
internal const int DefaultExpirationMinutes = 5 ;
28
28
29
- // reserve non-printable characters from keys, to prevent potential L2 abuse
30
- private static readonly char [ ] _keyReservedCharacters = Enumerable . Range ( 0 , 32 ) . Select ( i => ( char ) i ) . ToArray ( ) ;
31
-
32
29
[ System . Diagnostics . CodeAnalysis . SuppressMessage ( "Style" , "IDE0032:Use auto property" , Justification = "Keep usage explicit" ) ]
33
30
private readonly IDistributedCache ? _backendCache ;
34
31
[ System . Diagnostics . CodeAnalysis . SuppressMessage ( "Style" , "IDE0032:Use auto property" , Justification = "Keep usage explicit" ) ]
@@ -255,6 +252,26 @@ private static ValueTask<T> RunWithoutCacheAsync<TState, T>(HybridCacheEntryFlag
255
252
return null ;
256
253
}
257
254
255
+ // reserve non-printable characters from keys, to prevent potential L2 abuse
256
+ private static bool ContainsReservedCharacters ( ReadOnlySpan < char > key )
257
+ {
258
+ const char MaxControlChar = ( char ) 31 ;
259
+
260
+ #if NET8_0_OR_GREATER
261
+ return key . IndexOfAnyInRange ( ( char ) 0 , MaxControlChar ) >= 0 ;
262
+ #else
263
+ foreach ( char c in key )
264
+ {
265
+ if ( c <= MaxControlChar )
266
+ {
267
+ return true ;
268
+ }
269
+ }
270
+
271
+ return false ;
272
+ #endif
273
+ }
274
+
258
275
private bool ValidateKey ( string key )
259
276
{
260
277
if ( string . IsNullOrWhiteSpace ( key ) )
@@ -269,7 +286,7 @@ private bool ValidateKey(string key)
269
286
return false ;
270
287
}
271
288
272
- if ( key . IndexOfAny ( _keyReservedCharacters ) >= 0 )
289
+ if ( ContainsReservedCharacters ( key . AsSpan ( ) ) )
273
290
{
274
291
_logger . KeyInvalidContent ( ) ;
275
292
return false ;
0 commit comments