简体   繁体   中英

generate sha256 hash for a string in objective C equivalent to C# without using key

In c# I am doing

 HashAlgorithm hash=SHA256.create();
    string myHash = Convert.ToBase64String( hasher.ComputeHash(Encoding.UTF8.GetBytes("hello")));

and in objective c I am doing

const unsigned char arr[32];
        CC_SHA256([@"hello" UTF8String], 32, &arr);
        NSMutableData *HM = [NSData dataWithBytes:(const void *)arr length:32];
        NSLog(@"macHah  %@",[HM base64EncodingWithLineLength:0]);

but both of them generates different hash

Try using the following :

- (NSData *)sha256:(NSData *)data
{
    unsigned char hash[CC_SHA256_DIGEST_LENGTH];
    if ( CC_SHA256([data bytes], [data length], hash) )
    {
        NSData *hashData = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH];
        return hashData;
    }
    return nil;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM