C# 哈希字节到 Java -- 将 SQL Server HashByte 转换为 Java

标签 c# java sql-server cryptography

寻求帮助将此 C# 代码转换为 Java

我有字节数组,但需要帮助编码转换为 BigInteger。 希望为 Hadoop 创建 UDF;

C# 代码 输出,这与 SQL Server 相同

//A4-B7-83-01-00-59-25-A8-B5-7C-F7-16-E6-69-CF-14-A2-2E-22-09
//-6330555844639082588

// Unicode
byte[] byteArray = Encoding.UTF8.GetBytes("JAO21V279RSNHYGX23L0");
//Console.WriteLine(byteArray);
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] hashedPasswordBytes = sha.ComputeHash(byteArray);
//Console.WriteLine(hashedPasswordBytes);
Console.WriteLine("1: " + BitConverter.ToString(hashedPasswordBytes));
//Console.WriteLine(BitConverter.ToInt64(hashedPasswordBytes,0));
long value = BitConverter.ToInt64(hashedPasswordBytes, 0);
Console.WriteLine("2: " + value);
if (BitConverter.IsLittleEndian)
    Array.Reverse(hashedPasswordBytes);
Console.WriteLine("3: " + BitConverter.ToString(hashedPasswordBytes));
value = BitConverter.ToInt64(hashedPasswordBytes, 0);
Console.WriteLine("4: " + value);

1:A4-B7-83-01-00-59-25-A8-B5-7C-F7-16-E6-69-CF-14-A2-2E-22-09 2:-6330555844639082588 翻转的值(value)观 3:09-22-2E-A2-14-CF-69-E6-16-F7-7C-B5-A8-25-59-00-01-83-B7-A4 4: -1843714884904279543 -- 正确的 BigInt

SQL Server 代码

DECLARE @InputString VARCHAR(MAX) = 'JAO21V279RSNHYGX23L0'

SELECT CONVERT(BIGINT, HashBytes('SHA1', @InputString)) , HashBytes('SHA1', @InputString)

-1843714884904279543 0xA4B78301005925A8B57CF716E669CF14A22E2209

Java 输出 strHash:1a41b71831011001591251a81b517c1f71161e61691cf1141a212e122109

我到目前为止拥有的Java代码 导入 java.nio.ByteBuffer; 导入 java.nio.ByteOrder; 导入 java.security.MessageDigest; 导入java.security.NoSuchAlgorithmException; 导入 java.lang.System.*; 导入静态java.lang.System.out; 导入 java.math.BigInteger; 导入 java.nio.charset.Charset;

class JceSha1Test {

  private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

  public static void main(String[] a) {
      try {
        String strHash = "JAO21V279RSNHYGX23L0";        
        strHash = encryptPassword(strHash);        
        System.out.println("strHash: " + strHash);
      } catch (Exception e) {
         System.out.println("Exception: "+e);
      }
   }
  public static String encryptPassword(String password) {
    String returnValue = null;
    byte[] buf = password.getBytes(UTF8_CHARSET);

    ByteBuffer bb = ByteBuffer.wrap( buf );
    MessageDigest algorithm=null;
    try {
      algorithm = MessageDigest.getInstance("SHA-1");

    } catch (NoSuchAlgorithmException e) {
      //sClassLog.logException(e);
    }
    algorithm.reset();
    algorithm.update(buf);
    byte[] digest = algorithm.digest();
    returnValue = "";

    for (int byteIdx = 0; byteIdx < digest.length; byteIdx++) {
      //System.out.println( Integer.toHexString(digest[byteIdx]) );
      //returnValue += Integer.toHexString(digest[byteIdx] + 256  & 0xFF);
      //returnValue += Integer.toHexString((digest[byteIdx] + 256   & 0xFF) + 0x100 );
      //returnValue += Integer.toHexString( ( digest[byteIdx] & 255 ) );
      //returnValue += Integer.toHexString( ( 0xFF & digest[byteIdx] ) );
      //returnValue += Integer.toHexString( ( digest[byteIdx] & 0xFF ) );      
      returnValue += Integer.toString( ( digest[byteIdx] & 0xFF ) + 0x100, 16).substring( 1 );      
      //returnValue += Integer.toHexString( ( digest[byteIdx] + 256 ) ); // Orig
    }
    return returnValue;    
  }
//A4-B7-83-01-00-59-25-A8-B5-7C-F7-16-E6-69-CF-14-A2-2E-22-09
//-1843714884904279543
}

感谢您的帮助!

///////////////////////////******************** *********/////////////////////////

我的最终代码与 SQL Server 中的 HashBytes 匹配:

package com.cb.hiveudf;

import java.nio.ByteBuffer; 
import java.nio.ByteOrder; 
import java.security.MessageDigest; 
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.LongWritable;


/**
 * Implementation of the HashBytes UDF found in many databases.
 */

@Description(name = "hashBytes", 
    value = "_FUNC_(Charset, Value) - assigns a unique Biginterger to each string to which it is applied",
    extended = "Example:\n "
    + "  > SELECT name, _FUNC_(\"UTF-16LE\", value) hashkey FROM src" + "  ")

public class UDFHashBytes extends UDF {
 private final LongWritable result = new LongWritable(); 

    public LongWritable evaluate(Text input) throws Exception {
        if (input == null) 
        {
              return null;
        } 
        else 
        {
            String hashstring = input.toString();
            byte[] buf = hashstring.getBytes("UTF-8");
            MessageDigest algorithm=null;
            algorithm = MessageDigest.getInstance("SHA-1");          
            algorithm.reset();
            algorithm.update(buf);
            byte[] digest = algorithm.digest();  
            if(java.nio.ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) {
              for (int i = 0, j = digest.length - 1; i < j; i++, j--)  
              {  
                byte b = digest[i];  
                digest[i] = digest[j];  
                digest[j] = b;  
              } 
            }    
            ByteBuffer bb = ByteBuffer.wrap( digest );
            if(java.nio.ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) 
            {
              bb.order(ByteOrder.LITTLE_ENDIAN);
            }    

            result.set(bb.getLong());
            return result;
        }
    }
}

最佳答案

好吧,我希望你仍然能认出一些代码:)

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

final class JceSha1Test {
    public static void main(final String ... args) {
        final String strHashInput = "JAO21V279RSNHYGX23L0";
        final byte[] strHash = hashPassword(strHashInput);
        System.out.println("strHash: " + toHex(strHash));
        final ByteBuffer strHashBuffer = ByteBuffer.wrap(strHash);
        strHashBuffer.order(ByteOrder.LITTLE_ENDIAN);
        final long test = strHashBuffer.getLong();
        System.out.println(test);
    }

    public static byte[] hashPassword(final String password) {
        final byte[] encodedPassword = password.getBytes(StandardCharsets.UTF_8);
        final MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
        return algorithm.digest(encodedPassword);
    }

    public static String toHex(final byte[] data) {
        final StringBuilder sb = new StringBuilder(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            sb.append(String.format("%02X", data[i]));
        }
        return sb.toString();
    }
}

关于C# 哈希字节到 Java -- 将 SQL Server HashByte 转换为 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23612593/

相关文章:

c# - 如何在 Web Api 中使用 Httpclient 并响应 Ok 获取对象

c# - 为分布式事务处理协调器 (msdtc.exe) 添加防火墙规则

java - 如何从 Struts 2 中的 select 标签映射多个值?

python - SQLAlchemy/pandas to_sql for SQLServer——在主数据库中创建表

c# - 如何最小化锁定同时保持数据库相关操作是原子的

c# - 在 C# 中比较 RGB 颜色

c# - 使用 Npgsql 插入重复记录

java - ScheduledExecutorService 固定费率的计划未按预期准确运行

java - Amazon DynamoDB 获取属性值为...的项目(Java API)

python - 将 pandas 数据框插入 SQL 临时表