【问题标题】:SHA256 key generator in iphoneiPhone中的SHA256密钥生成器
【发布时间】:2010-06-22 13:37:24
【问题描述】:

我想使用 SHA256 生成一个具有 N 次迭代的密钥。

他们输入的应该是我的“密码” + “随机数”

我看过苹果提供的 Crypto 示例,但它似乎没有满足我的要求(或者可能我没有正确获得它)。

我也浏览了以下链接,但没有使用 SHA256 生成密钥的方法 http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html

等待一些提示。

问候

【问题讨论】:

    标签: iphone objective-c cryptography openssl aes


    【解决方案1】:

    试试这个,它对我有用

    1) 获取平面文本输入的哈希

    -(NSString*)sha256HashFor:(NSString*)input
    {   
        const char* str = [input UTF8String];
        unsigned char result[CC_SHA256_DIGEST_LENGTH];
        CC_SHA256(str, strlen(str), result);
    
        NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
        for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
        {
            [ret appendFormat:@"%02x",result[i]];
        }
        return ret;
    }
    

    2) 获取 NSData 的哈希作为输入

    注意:-我使用的是NSData类,所以代码如下

    - (NSString *)SHA256_HASH {
    if (!self) return nil;
    
    unsigned char hash[CC_SHA256_DIGEST_LENGTH];
    if ( CC_SHA256([(NSData*)self bytes], [(NSData*)self length], hash) ) {
        NSData *sha2 = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH]; 
    
        // description converts to hex but puts <> around it and spaces every 4 bytes
        NSString *hash = [sha2 description];
        hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
        // hash is now a string with just the 40char hash value in it
        //NSLog(@"hash = %@",hash);
    
        // Format SHA256 fingerprint like
        // 00:00:00:00:00:00:00:00:00
        int keyLength=[hash length];
        NSString *formattedKey = @"";
        for (int i=0; i<keyLength; i+=2) {
            NSString *substr=[hash substringWithRange:NSMakeRange(i, 2)];
            if (i!=keyLength-2) 
                substr=[substr stringByAppendingString:@":"];
            formattedKey = [formattedKey stringByAppendingString:substr];
        }
    
        return formattedKey;
    }
    return nil;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-13
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多