我需要将用VisualBasic编写的旧代码翻译成Java。 VB代码:
Dim mySHA256 As Object
Dim asc As Object
Dim TextToHash() As Byte
Dim mybytes() As Byte
Dim objXML As Object
Dim objNode As Object
Dim strResult As String
Set asc = CreateObject("System.Text.UTF8Encoding")
Set mySHA256 = CreateObject("System.Security.Cryptography.SHA256Managed")
TextToHash = asc.GetBytes_4(sTextToHash)
mybytes = mySHA256.ComputeHash_2(TextToHash)
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
strResult = objNode.Text
对我来说,这看起来非常神奇。我需要在Java中使用相同的哈希(strResult)。我的Java看起来像这样:
byte[] bytes = text.getBytes( "UTF-8" );
MessageDigest messageDigest = MessageDigest.getInstance( "SHA-256" );
byte[] hash = messageDigest.digest( bytes );
StringBuffer hexString = new StringBuffer();
for( int i = 0; i < hash.length; i++ )
{
String hex = Integer.toHexString( 0xff & hash[ i ] );
if( hex.length() == 1 )
{
hexString.append( '0' );
}
hexString.append( hex );
}
有谁知道怎么做?
答案 0 :(得分:0)
我找到了解决方案。正确的Java代码应如下所示:
byte[] bytes = text.getBytes( "UTF-8" );
MessageDigest messageDigest = MessageDigest.getInstance( "SHA-256" );
byte[] hash = messageDigest.digest( bytes );
String result = Base64.getEncoder().encodeToString(hash);