MD5哈希在Android中Android

2023-09-12 09:07:43 作者:∞帞蕥。

我有一个简单的android客户端,需要'交谈',以一个简单的C#HTTP侦听器。我想通过传递用户名/密码在POST请求提供身份验证的基本水平。

I have a simple android client which needs to 'talk' to a simple C# HTTP listener. I want to provide a basic level of authentication by passing username/password in POST requests.

MD5散列是微不足道的在C#中,并提供足够的安全性满足我的需求,但我似乎无法找到如何在安卓端做到这一点。

MD5 hashing is trivial in C# and provides enough security for my needs but I can't seem to find how to do this at the android end.

编辑:只是为了满足人们对MD5的弱点的关注 - 在C#服务器上我的Andr​​oid客户端的用户的PC上运行。在许多情况下,他们将访问使用Wi-Fi在自己的局域网服务器,但是,在自己的风险,他们可以选择从互联网访问它。另外,服务器上的服务需要使用直通的MD5到第三方应用程序,我无法控制的。

Just to address the concerns raised about MD5 weakness - the C# server runs on the PCs of the users of my android client. In many cases, they'll be accessing the server using wi-fi on their own LANs but, at their own risk, they may choose to access it from the internet. Also the service on the server needs to use pass-through for the MD5 to a 3rd party application I have no control over.

推荐答案

这里是你可以用一个实现(更新为使用更多的最新Java约定 - 为:每循环,的StringBuilder 而不是的StringBuffer ):

Here is an implementation you can use (updated to use more up to date Java conventions - for:each loop, StringBuilder instead of StringBuffer):

public static final String md5(final String s) {
    final String MD5 = "MD5";
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance(MD5);
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

虽然不建议对涉及安全,甚至基层系统(MD5 被认为是坏了,可容易利用的),有时不够基本任务。

Although it is not recommended for systems that involve even the basic level of security (MD5 is considered broken and can be easily exploited), it is sometimes enough for basic tasks.