简体   繁体   English

将 MD5 - base64 从 JAVA 转换为 PHP

[英]Convert MD5 - base64 From JAVA to PHP

I have a problem converting this Java code that generate md5-base64 to php.我在将生成 md5-base64 的 Java 代码转换为 php 时遇到问题。

I'd try more then 5 hours but without success.我会尝试超过 5 个小时,但没有成功。

This is the java code:这是Java代码:

public static void main(String[] args) {
        // TODO code application logic here

        try {
            String string = "customString";
            String format = "20190101000000";
            StringBuilder sb = new StringBuilder();
            sb.append(format);
            sb.append(string);
            String sb2 = sb.toString();

            byte[] bytes = sb2.getBytes();
            byte[] bArr = new byte[16];
            MessageDigest instance2 = MessageDigest.getInstance("MD5");
            instance2.update(bytes, 0, bytes.length);
            instance2.digest(bArr, 0, 16);

            PrintStream printStream6 = System.out;
            String a2 = Base64.getEncoder().encodeToString(bArr);
            if (a2.length() >= 20) {
                a2 = a2.substring(0, 19).trim();
            }
            StringBuilder sb8 = new StringBuilder();
            sb8.append("MD5 16: ");
            sb8.append(a2);
            printStream6.println(sb8.toString());

        } catch (Exception e) {
            System.out.println(e);
        }

    }

And this is my php这是我的 php

<?php

$string = 'customString';
$format = '20190101000000';

$res = $format . $string;
$md5 = md5($res, true);
echo $md5;
echo '------------------';

$base = base64_encode($md5);
echo $base;
echo '------------------';

$result = substr($base, 0, 19);
echo $result;
echo '------------------';

The Java result is 1B2M2Y8AsgTpgAmY7Ph and php is iSKxA+7Y1mMnHhwf0yb Java 结果是1B2M2Y8AsgTpgAmY7Ph ,php 是iSKxA+7Y1mMnHhwf0yb

Check for charset encodings.检查字符集编码。 In Java Strings are usually UTF-8 encoded.在 Java 中,字符串通常是 UTF-8 编码的。 But when you transform to byte[] in sb2.getBytes();但是当你在 sb2.getBytes(); 中转换为 byte[] 时; it is using platform default charset (eg ISO-8859-1).它使用平台默认字符集(例如 ISO-8859-1)。

You have to provide the charset in java to have a determined behavior:您必须在 java 中提供字符集才能确定行为:

sb2.getBytes(java.nio.charset.Charset.forName("UTF-8");

or, the other way round, if goal isn't simply to make both reproduce same output, but you have to implement a PHP solution compatible with your existing Java solution, convert the PHP UTF-8 string to correct charset before md5(...).或者,反过来说,如果目标不仅仅是让两者都重现相同的输出,而且您必须实现与现有 Java 解决方案兼容的 PHP 解决方案,请将 PHP UTF-8 字符串转换为 md5(.. .) Therefore use iconv method.因此使用 iconv 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM