我有JAVA和VB中的代码可以工作。我需要用PHP做同样的事情,我该怎么做
工作正常的VB代码:我有JAVA和VB中的代码可以工作。我需要用PHP做同样的事情,我该怎么做,java,php,vb.net,Java,Php,Vb.net,工作正常的VB代码: Public Function Encrypt(ByVal Data As String) As Byte() Dim md5Hasher As New MD5CryptoServiceProvider() Dim hashedBytes As Byte() Dim encoder As New UTF8Encoding() hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Data)
Public Function Encrypt(ByVal Data As String) As Byte()
Dim md5Hasher As New MD5CryptoServiceProvider()
Dim hashedBytes As Byte()
Dim encoder As New UTF8Encoding()
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Data))
Return hashedBytes
End Function
byte[] bytes = stringToConvert.getBytes("UTF-8");
MessageDigest m = MessageDigest.getInstance("MD5");
hashedBytes = m.digest(bytes);
工作正常的JAVA代码:
Public Function Encrypt(ByVal Data As String) As Byte()
Dim md5Hasher As New MD5CryptoServiceProvider()
Dim hashedBytes As Byte()
Dim encoder As New UTF8Encoding()
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Data))
Return hashedBytes
End Function
byte[] bytes = stringToConvert.getBytes("UTF-8");
MessageDigest m = MessageDigest.getInstance("MD5");
hashedBytes = m.digest(bytes);
我在PHP中尝试的东西不起作用,我想我知道为什么
我认为这是因为:
Java中的字符存储为Unicode 16位序列。在PHP中,它们是单字节序列。
这是我尝试过的代码
$UTFbString = UTF8_encode($bString);
$hashedBytes = md5($UTFbString, true);
好的,我发现如果我用这个方法
function ascii_to_dec($str)
{
for ($i = 0, $j = strlen($str); $i < $j; $i++) {
$dec_array[] = ord($str{$i});
}
return $dec_array;
}
这样做的JAVA代码如下所示
MessageDigest digester = MessageDigest.getInstance("MD5");
byte[] bytes = new byte[8192];
int byteCount;
while ((byteCount = in.read(bytes)) > 0) {
digester.update(bytes, 0, byteCount);
}
byte[] digest = digester.digest();
关于在PHP中实现类似的东西有什么建议吗 试试看:
<?php
$hashedBytes = base64_encode(md5($bString, true))
虽然我不确定为什么要使用字节数组作为md5哈希,但我的解决方案如下:
<?php
$stringToConvert = "äöüß";
$md5 = md5(utf8_encode($stringToConvert), true);
for($i = 0; $i < strlen($md5); $i++) {
$c = ord($md5[$i]);
$b[] = $c > 127 ? $c-256 : $c;
}
print_r($b);
?>
所有输出VB.code、JAVA代码和PHP代码的输出必须匹配。这并没有产生期望的结果。这取决于您如何进行匹配。我试着把它匹配成从-127到127的数字。如果希望输出正确匹配,请使用标准md5输出模式。由32个字符[0-f]组成的字符串。在PHP中,它只是$stringToConvert=“äöüß”$md5=md5(utf8_编码($stringToConvert));或者不使用utf8_encode(),这取决于您在PHP中读取字符串的方式。所有输出来自JAVA和VB代码以及PHP代码的输出必须匹配。我想这可能是接近我需要的,但没有得到我想要的结果。