如何在Android中散列字符串? [英] How to hash a string in Android?

查看:96
本文介绍了如何在Android中散列字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,并且在发送到数据库之前有一些我想要加密的字符串。我希望一些安全,易于实现的东西,每次传递相同的数据时都会生成相同的东西,并且最好会导致一个字符串保持恒定的长度,无论传递给它的字符串有多大。也许我正在寻找一个散列。

I am working on an Android app and have a couple strings that I would like to encrypt before sending to a database. I'd like something that's secure, easy to implement, will generate the same thing every time it's passed the same data, and preferably will result in a string that stays a constant length no matter how large the string being passed to it is. Maybe I'm looking for a hash.

推荐答案

这段代码为任何给定的字符串计算md5

This snippet calculate md5 for any given string

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

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i=0; i<messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();

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

来源: http://www.androidsnippets.com/snippets/52/index.html

希望这对你有用

这篇关于如何在Android中散列字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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