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

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

问题描述

在 Objective C 中,我一直使用以下代码对字符串进行哈希处理:

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 设备,但不知道如何去做.我一直在寻找这样的例子:在 Android 上进行 SHA1 加密?但这并没有给我与 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");
        byte[] textBytes = text.getBytes("iso-8859-1");
        md.update(textBytes, 0, textBytes.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散列Android中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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