@@ -446,27 +446,23 @@ public static Task WriteAsync(this Stream stream, byte[] bytes, CancellationToke
446446 public static Task WriteAsync ( this Stream stream , string text , CancellationToken token = default ) =>
447447 MemoryProvider . Instance . WriteAsync ( stream , text . AsSpan ( ) , token ) ;
448448
449- public static string ToMd5Hash ( this Stream stream )
449+ public static byte [ ] ToMd5Bytes ( this Stream stream )
450450 {
451- var hash = System . Security . Cryptography . MD5 . Create ( ) . ComputeHash ( stream ) ;
452- var sb = StringBuilderCache . Allocate ( ) ;
453- foreach ( byte b in hash )
451+ #if NET6_0_OR_GREATER
452+ if ( stream is MemoryStream ms )
453+ return System . Security . Cryptography . MD5 . HashData ( ms . GetBufferAsSpan ( ) ) ;
454+ #endif
455+ if ( stream . CanSeek )
454456 {
455- sb . Append ( b . ToString ( "x2" ) ) ;
457+ stream . Position = 0 ;
456458 }
457- return StringBuilderCache . ReturnAndFree ( sb ) ;
459+ return System . Security . Cryptography . MD5 . Create ( ) . ComputeHash ( stream ) ;
458460 }
459461
460- public static string ToMd5Hash ( this byte [ ] bytes )
461- {
462- var hash = System . Security . Cryptography . MD5 . Create ( ) . ComputeHash ( bytes ) ;
463- var sb = StringBuilderCache . Allocate ( ) ;
464- foreach ( byte b in hash )
465- {
466- sb . Append ( b . ToString ( "x2" ) ) ;
467- }
468- return StringBuilderCache . ReturnAndFree ( sb ) ;
469- }
462+ public static string ToMd5Hash ( this Stream stream ) => ToMd5Bytes ( stream ) . ToHex ( ) ;
463+
464+ public static string ToMd5Hash ( this byte [ ] bytes ) =>
465+ System . Security . Cryptography . MD5 . Create ( ) . ComputeHash ( bytes ) . ToHex ( ) ;
470466
471467 /// <summary>
472468 /// Returns bytes in publiclyVisible MemoryStream
0 commit comments