适用于 iPhone 的 Objective-C 中的 Sha256

发布于 2024-09-19 09:25:48 字数 438 浏览 10 评论 0原文

当我使用此代码创建字符串的 sha256 时,

unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@"hello"];
NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256(inputData.bytes, inputData.length, hashedChars);

它正确返回哈希,但我需要插入这样的字符串 \x00\x25\x53 ,在这种情况下,该函数返回 sha256空字符串,因为指定的编码不能用于转换接收者。

现在,我的问题是:如何插入这个特殊字符来生成正确的哈希值?谢谢

When I use this code to create a sha256 of a string

unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@"hello"];
NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256(inputData.bytes, inputData.length, hashedChars);

It returns the hash correctly, but I need to insert a string like this \x00\x25\x53 and in this case, the function returns a sha256 of empty string because the specified encoding cannot be used to convert the receiver.

Now, my question is:How to insert this special characters for generate a correct hash? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黎夕旧梦 2024-09-26 09:25:48

试试这个,它对我有用

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;
}

Try this, it worked for me

1) To get a hash for plain text input

-(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) To get hash for NSData as input

Note:- I have used NSData category, so the code is as follow

    - (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;
}
动听の歌 2024-09-26 09:25:48

重要的是要知道您需要导入:

#import <CommonCrypto/CommonDigest.h>

希望这有帮助!

It's important to know that you need to import:

#import <CommonCrypto/CommonDigest.h>

Hope this help!

等风也等你 2024-09-26 09:25:48

那么您可能应该使用 NSData 而不是 NSString 。你从哪里得到那个字符串?

You probably should use NSData instead of NSString then. Where do you get that string from?

烟柳画桥 2024-09-26 09:25:48

有人在 Swift 3.0 中寻找解决方案。这是

extension String {

// MARK: - SHA256
func get_sha256_String() -> String {
    guard let data = self.data(using: .utf8) else {
        print("Data not available")
        return ""
    }
    return getHexString(fromData: digest(input: data as NSData))
}

private func digest(input : NSData) -> NSData {
    let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
    var hashValue = [UInt8](repeating: 0, count: digestLength)
    CC_SHA256(input.bytes, UInt32(input.length), &hashValue)
    return NSData(bytes: hashValue, length: digestLength)
}

private  func getHexString(fromData data: NSData) -> String {
    var bytes = [UInt8](repeating: 0, count: data.length)
    data.getBytes(&bytes, length: data.length)

    var hexString = ""
    for byte in bytes {
        hexString += String(format:"%02x", UInt8(byte))
    }
    return hexString
}}

如何使用它

let signatures = "yourStringToBeConverted".get_sha256_String()

也不要忘记在Bridging-Header.h中导入#import >

Some one looking the solution in Swift 3.0. here is

extension String {

// MARK: - SHA256
func get_sha256_String() -> String {
    guard let data = self.data(using: .utf8) else {
        print("Data not available")
        return ""
    }
    return getHexString(fromData: digest(input: data as NSData))
}

private func digest(input : NSData) -> NSData {
    let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
    var hashValue = [UInt8](repeating: 0, count: digestLength)
    CC_SHA256(input.bytes, UInt32(input.length), &hashValue)
    return NSData(bytes: hashValue, length: digestLength)
}

private  func getHexString(fromData data: NSData) -> String {
    var bytes = [UInt8](repeating: 0, count: data.length)
    data.getBytes(&bytes, length: data.length)

    var hexString = ""
    for byte in bytes {
        hexString += String(format:"%02x", UInt8(byte))
    }
    return hexString
}}

How to Use it

let signatures = "yourStringToBeConverted".get_sha256_String()

also don't forgot to import #import <CommonCrypto/CommonHMAC.h> in your Bridging-Header.h

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文