Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android中散列字符串?_Java_Android_Hash_Cryptography - Fatal编程技术网

Java 如何在Android中散列字符串?

Java 如何在Android中散列字符串?,java,android,hash,cryptography,Java,Android,Hash,Cryptography,我正在开发一个Android应用程序,在发送到数据库之前,我想对一些字符串进行加密。我想要一个安全、易于实现的东西,每次传递相同的数据时都会生成相同的内容,最好是生成一个长度不变的字符串,不管传递给它的字符串有多大。也许我在寻找散列。此代码段为任何给定字符串计算md5 public String md5(String s) { try { // Create MD5 Hash MessageDigest digest = java.security.Mes

我正在开发一个Android应用程序,在发送到数据库之前,我想对一些字符串进行加密。我想要一个安全、易于实现的东西,每次传递相同的数据时都会生成相同的内容,最好是生成一个长度不变的字符串,不管传递给它的字符串有多大。也许我在寻找散列。

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

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 "";
}
公共字符串md5(字符串s){
试一试{
//创建MD5散列
MessageDigest=java.security.MessageDigest.getInstance(“MD5”);
更新(s.getBytes());
字节messageDigest[]=digest.digest();
//创建十六进制字符串
StringBuffer hexString=新的StringBuffer();
对于(inti=0;i
private static char[]hextable={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
公共静态字符串byteArrayToHex(字节[]数组){
字符串s=“”;
对于(int i=0;i>4)&0xF]+hextable[di&0xF];
}
返回s;
}
公共静态字符串摘要(字符串、字符串算法){
MessageDigest m=null;
试一试{
m=MessageDigest.getInstance(算法);
}捕获(无算法异常){
e、 printStackTrace();
返回s;
}
m、 更新(s.getBytes(),0,s.length());
返回bytearraytochex(m.digest());
}
公共静态字符串md5(字符串s){
报税摘要(“MD5”);
}
上面的from()函数有缺陷。如果messageDigest中的一个数字不是两个字符的十六进制值(即0x09),它不能正常工作,因为它没有用0填充。如果你四处搜索,你会发现该函数并抱怨它不工作。这里有一个更好的,我稍微修改了一下:

public static String md5(String s) 
{
    MessageDigest digest;
    try
    {
        digest = MessageDigest.getInstance("MD5");
        digest.update(s.getBytes(Charset.forName("US-ASCII")),0,s.length());
        byte[] magnitude = digest.digest();
        BigInteger bi = new BigInteger(1, magnitude);
        String hash = String.format("%0" + (magnitude.length << 1) + "x", bi);
        return hash;
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    return "";
}
公共静态字符串md5(字符串s)
{
信息摘要;
尝试
{
digest=MessageDigest.getInstance(“MD5”);
update(s.getBytes(Charset.forName(“US-ASCII”)),0,s.length();
字节[]大小=摘要。摘要();
BigInteger bi=新的BigInteger(1,幅值);

String hash=String.format(“%0”+(magnize.length以上答案几乎100%正确。使用unicode将失败

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
        byte utf8_bytes[] = tag_xml.getBytes();
        digest.update(utf8_bytes,0,utf8_bytes.length);
        hash = new BigInteger(1, digest.digest()).toString(16);
    } 
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

需要字节数组中的长度,而不是字符串。

单个函数中的甜甜圈解决方案:

private static char[] hextable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

private static String md5(String s)
{
    MessageDigest digest;
    try
    {
        digest = MessageDigest.getInstance("MD5");
        digest.update(s.getBytes(), 0, s.length());
        byte[] bytes = digest.digest();

        String hash = "";
        for (int i = 0; i < bytes.length; ++i)
        {
            int di = (bytes[i] + 256) & 0xFF;
            hash = hash + hextable[(di >> 4) & 0xF] + hextable[di & 0xF];
        }

        return hash;
    }
    catch (NoSuchAlgorithmException e)
    {
    }

    return "";
}
private static char[]hextable={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
私有静态字符串md5(字符串s)
{
信息摘要;
尝试
{
digest=MessageDigest.getInstance(“MD5”);
更新(s.getBytes(),0,s.length());
字节[]字节=摘要。摘要();
字符串哈希=”;
对于(int i=0;i>4)&0xF]+hextable[di&0xF];
}
返回散列;
}
捕获(无算法异常)
{
}
返回“”;
}
对于作者来说已经晚了,但在此之前,我得到了
整数.toHexString(0xff&b)
,它从十六进制字符串中去掉了前导0。这让我挣扎了很长时间。希望对一些人有用。

非工作方法:

public static 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 "";
}
public static final String md5(final String toEncrypt) {
    try {
        final MessageDigest digest = MessageDigest.getInstance("md5");
        digest.update(toEncrypt.getBytes());
        final byte[] bytes = digest.digest();
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(String.format("%02X", bytes[i]));
        }
        return sb.toString().toLowerCase();
    } catch (Exception exc) {
        return ""; // Impossibru!
    }
}

结果:
1865e62e7129927f6e4c0d9bff1004f0
(长度32)

对于@Donut solution,对于UTF-8编码字符(例如:é),您必须使用
getBytes(“UTF-8”)
。下面是我对摘要方法的更正:

private static char[] hextable = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


public static String byteArrayToHex(byte[] array) {
    String s = "";
    for (int i = 0; i < array.length; ++i) {
        int di = (array[i] + 256) & 0xFF; // Make it unsigned
        s = s + hextable[(di >> 4) & 0xF] + hextable[di & 0xF];
    }
    return s;
}

public static String digest(String s, String algorithm) {
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return s;
    }

    try {
        m.update(s.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        m.update(s.getBytes());
    }
    return byteArrayToHex(m.digest());
}

public static String md5(String s) {
    return digest(s, "MD5");
}
private static char[]hextable={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
公共静态字符串byteArrayToHex(字节[]数组){
字符串s=“”;
对于(int i=0;i>4)&0xF]+hextable[di&0xF];
}
返回s;
}
公共静态字符串摘要(字符串、字符串算法){
MessageDigest m=null;
试一试{
m=MessageDigest.getInstance(算法);
}捕获(无算法异常){
e、 printStackTrace();
返回s;
}
试一试{
m、 更新(s.getBytes(“UTF-8”);
}捕获(不支持的编码异常e){
e、 printStackTrace();
m、 更新(s.getBytes());
}
返回bytearraytochex(m.digest());
}
公共静态字符串md5(字符串s){
报税摘要(“MD5”);
}

以下内容在Android上对我有效,但没有截断任何0的infront:

MessageDigest md = null;
String digest = null;
    try {
        md = MessageDigest.getInstance("MD5");

        byte[] hash = md.digest(myStringToEncode.getBytes("UTF-8")); //converting byte array to Hexadecimal String
        StringBuilder sb = new StringBuilder(2*hash.length);

        for(byte b : hash){
            sb.append(String.format("%02x", b&0xff));
        }

        digest = sb.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

return digest;

如果您正在使用番石榴:

public String generateMd5(String input) {
    HashFunction hf = Hashing.md5();
    Hasher hasher = hf.newHasher();

    HashCode hc = hasher.putString(input, StandardCharsets.UTF_8).hash();

    return hc.toString();
}

如果您没有安全约束,只想将字符串转换为唯一的int。 我写这篇文章是因为我在这里寻找并达到了这个目的

String my_key
int my_key.hashCode()
如果你有多达10个字符,它甚至是独一无二的 另见

此文件不缺少“0”


散列是单向的,如果你想解密不能以恒定长度存储的数据,我知道。它是为了验证,我只需要能够比较一个值和另一个值,不需要“撤消”它。我知道我没有说我是否计划解密,所以谢谢你的回答。无意冒犯,但你问题的标题误导了MD5,好吧,它被认为是不可逆的。通常你会用它散列一些东西,通常是密码或类似的东西,然后验证密码,你将运行相同的加密并将结果与之进行比较存储的内容。此代码无法正常工作。某些“0”生成的字符串中缺少字符。我不知道为什么,但情况就是这样。此代码失败时有一种特殊情况。当两位十六进制数中的第一位为零时。此代码更好:这将导致我尝试过的问题。当我使用此函数时,Difference is only 0-->会给我结果(字符串为:a)结果:cc175b9c0f1b6a831c399e269772661 0CC175B9C0F1B6A831C399E269772661与@SertalpBilal一致,正确答案在这里
public String generateMd5(String input) {
    HashFunction hf = Hashing.md5();
    Hasher hasher = hf.newHasher();

    HashCode hc = hasher.putString(input, StandardCharsets.UTF_8).hash();

    return hc.toString();
}
String my_key
int my_key.hashCode()
  public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }