44
55using Microsoft . AspNetCore . Http ;
66using Microsoft . AspNetCore . WebUtilities ;
7+ using Microsoft . Extensions . Caching . Memory ;
8+ using Microsoft . Extensions . Options ;
79using System ;
8- using System . Buffers ;
910using System . Collections . Generic ;
1011using System . Linq ;
1112using System . Security . Cryptography ;
1213using System . Text ;
13- using System . Threading . Tasks ;
1414
1515namespace ImageWizard . Utils ;
1616
@@ -29,6 +29,8 @@ public HMACSHA256UrlSignature(bool includeHost)
2929 IncludeHost = includeHost ;
3030 }
3131
32+ private IMemoryCache _cache = new MemoryCache ( Options . Create ( new MemoryCacheOptions ( ) { SizeLimit = 10_000 } ) ) ;
33+
3234 /// <summary>
3335 /// Signature depend on remote hostname? (Default: false)
3436 /// </summary>
@@ -73,6 +75,15 @@ public string Encrypt(byte[] key, ImageWizardRequest request)
7375 input = GetUrlValue ( request . Url ) ;
7476 }
7577
78+ //signature already exists in cache?
79+ if ( _cache . TryGetValue ( input , out string ? cachedKey ) == true )
80+ {
81+ if ( cachedKey != null )
82+ {
83+ return cachedKey ;
84+ }
85+ }
86+
7687 int inputLength = Encoding . UTF8 . GetByteCount ( input ) ;
7788
7889 Span < byte > inputBuffer = inputLength <= 128 ? stackalloc byte [ inputLength ] : new byte [ inputLength ] ;
@@ -86,6 +97,15 @@ public string Encrypt(byte[] key, ImageWizardRequest request)
8697 HMACSHA256 . HashData ( key , inputBuffer , hashBuffer ) ;
8798
8899 //convert to Base64Url
89- return WebEncoders . Base64UrlEncode ( hashBuffer ) ;
100+ string keyBase64Url = WebEncoders . Base64UrlEncode ( hashBuffer ) ;
101+
102+ //add signature to cache
103+ _cache . Set ( input , keyBase64Url , new MemoryCacheEntryOptions ( )
104+ {
105+ Size = 1 ,
106+ SlidingExpiration = TimeSpan . FromHours ( 1 )
107+ } ) ;
108+
109+ return keyBase64Url ;
90110 }
91111}
0 commit comments