Android中的MD5哈希 [英] MD5 hashing in Android

查看:20
本文介绍了Android中的MD5哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 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# 中是微不足道的,并为我的需要提供足够的安全性,但我似乎无法在 android 端找到如何做到这一点.

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# 服务器在我的 android 客户端用户的 PC 上运行.在许多情况下,他们将在自己的 LAN 上使用 wi-fi 访问服务器,但他们可能会选择从 Internet 访问服务器,风险自负.此外,服务器上的服务需要将 MD5 传递给我无法控制的第 3 方应用程序.

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 约定 - for:each 循环,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 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 is被认为是损坏的并且很容易被利用),有时对于基本任务来说已经足够了.

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.

这篇关于Android中的MD5哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆