如何SHA1哈希值的字符串中的Andr​​oid? [英] How to SHA1 hash a string in Android?

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

问题描述

在目标C我一直在使用下面的code哈希的字符串:

In Objective C I've been using the following code to hash a string:

-(NSString *) sha1:(NSString*)stringToHash {    
    const char *cStr = [stringToHash UTF8String];
    unsigned char result[20];
    CC_SHA1( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
        result[0], result[1], result[2], result[3], 
        result[4], result[5], result[6], result[7],
        result[8], result[9], result[10], result[11],
        result[12], result[13], result[14], result[15],
        result[16], result[17], result[18], result[19]
        ];  
}

现在我需要同样为Android,但不能找出如何做到这一点。我一直在寻找,例如在此:让SHA1加密在Android  但是这并没有给我相同的结果,在iPhone上。任何人都可以点我朝着正确的方向?

Now I need the same for Android but can't find out how to do it. I've been looking for example at this: Make SHA1 encryption on Android ? but that doesn't give me the same result as on iPhone. Can anyone point me in the right direction?

推荐答案

您不需要的Andorid这一点。你可以做它在简单的Java。

You don't need andorid for this. You can just do it in simple java.

您是否尝试过一个简单的Java例子,看看它返回正确的SHA1。

Have you tried a simple java example and see if this returns the right sha1.

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AeSimpleSHA1 {
    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
}

也分享你的期望SHA1应该的。也许ObjectC这样做是错误的。

Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong.

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

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