HashHelper.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace XUnity.AutoTranslator.Plugin.Core.Utilities
  7. {
  8. internal static class HashHelper
  9. {
  10. private static readonly SHA1Managed SHA1 = new SHA1Managed();
  11. private static readonly uint[] Lookup32 = CreateLookup32();
  12. public static string Compute( byte[] data )
  13. {
  14. var hash = SHA1.ComputeHash( data );
  15. var hex = ByteArrayToHexViaLookup32( hash );
  16. return hex.Substring( 0, 10 );
  17. }
  18. private static uint[] CreateLookup32()
  19. {
  20. var result = new uint[ 256 ];
  21. for( int i = 0 ; i < 256 ; i++ )
  22. {
  23. string s = i.ToString( "X2" );
  24. result[ i ] = ( (uint)s[ 0 ] ) + ( (uint)s[ 1 ] << 16 );
  25. }
  26. return result;
  27. }
  28. private static string ByteArrayToHexViaLookup32( byte[] bytes )
  29. {
  30. var lookup32 = Lookup32;
  31. var result = new char[ bytes.Length * 2 ];
  32. for( int i = 0 ; i < bytes.Length ; i++ )
  33. {
  34. var val = lookup32[ bytes[ i ] ];
  35. result[ 2 * i ] = (char)val;
  36. result[ 2 * i + 1 ] = (char)( val >> 16 );
  37. }
  38. return new string( result );
  39. }
  40. }
  41. }