iOS中特定字符串的SHA1 [英] SHA1 for Specific String in iOS

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

问题描述

根据我的要求:


  1. 输入字符串必须转换为字节值。

  2. 字符串的每个字符(16位值)必须转换为低8位。

  3. 然后通过字节数组计算Sha1。

  4. 生成的SHA-1转换为40个字符的字符串。

  1. The input string has to be converted into Byte Values.
  2. Each character of string , which are 16 bit values , has to be converted to low 8 bits.
  3. The Sha1 is then computed over the byte Array.
  4. The resulting SHA-1 is converted into a 40 character string.

我知道如何将字符串转换为SHA1,但剩下的部分对我来说有点暗淡。
我已经能够完成最后两个步骤。

I know how to convert a string into SHA1 , but the rest of part is a bit gloomy to me. I have been able to do the last two steps.

unsigned char digest[CC_SHA1_DIGEST_LENGTH];
NSData *dataString = [yourString dataUsingEncoding: NSUTF8StringEncoding]; 

if (CC_SHA1([dataString bytes], [dataString length], digest)) {
   //Sha1 is calculated & stored in digest.
}

任何帮助都将不胜感激。

Any help will be appreciated.

推荐答案

我创建了这个函数,可以根据你的要求正常工作。你只需要输入一个字符串。

I have created this function , which works fine according to your requirement . You just have to input a string.

#import <CommonCrypto/CommonDigest.h>

- (NSString *)calculateSHA:(NSString *)yourString
{
    const char *ptr = [yourString UTF8String];

    int i =0;
    int len = strlen(ptr);
    Byte byteArray[len];
    while (i!=len)
    {
        unsigned eachChar = *(ptr + i);
        unsigned low8Bits = eachChar & 0xFF;

        byteArray[i] = low8Bits;
        i++;
    }


    unsigned char digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(byteArray, len, digest);

    NSMutableString *hex = [NSMutableString string];
    for (int i=0; i<20; i++)
        [hex appendFormat:@"%02x", digest[i]];

    NSString *immutableHex = [NSString stringWithString:hex];

    return immutableHex;
}

然后你只需要调用上面的方法。

Then you just have to call the above method.

[self calculateSHA:yourString];

这篇关于iOS中特定字符串的SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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