Objective C SHA512 hash of two NSData

自作多情 提交于 2020-01-22 17:07:07

问题


Here is a Java code, which computes SHA512 hash of a byte array with salt:

private static String DIGEST_ALGORITHM = "SHA-512";

    public static byte[] getHash(final byte[] data, final byte[] salt) throws NoSuchAlgorithmException
{
    final MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    md.reset();
    if (salt != null)
    {
        md.update(salt);
    }
    return md.digest(data);

In Objective C, I use this algorithm for compute the hash of an NSData:

@implementation NSData (CommonDigest)

- (NSData *) SHA512Hash {
unsigned char hash[CC_SHA512_DIGEST_LENGTH];
(void) CC_SHA512( [self bytes], (CC_LONG)[self length], hash );
return ( [NSData dataWithBytes: hash length: CC_SHA512_DIGEST_LENGTH] );
}

This works perfectly, computes the same hash, as the Java code, if I use the same single data (i.e. the salt is nil in the Java code). The problem is that, if I want to computes hash of two NSData, i.e. there is a salt (the second parameter in the Java code is not nil). You can see that in the Java code, if the salt is not null, it performs an update, and then call the digest method. Somewhere I read that, this operation is equal with merging the two byte array (the data and salt arrays with System.arraycopy), and call the digest on the result array. However, if I do this in Objective C (with NSMutableData appendData method), I don't get the same result. How can I fix this? I can see in the CommonDigest class, there are similar methods, but I don't know, how can I use these...I think of these methods:

extern int CC_SHA512_Init(CC_SHA512_CTX *c);
extern int CC_SHA512_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len);
extern int CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *c);
extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md);

So I would like to create a method like this:

@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {...}

回答1:


I haven’t run this code and compared it with a Java implementation but it should work:

@implementation NSData (CommonDigest)

- (NSData *)SHA512HashWithSalt:(NSData *)salt {
    unsigned char hash[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512_CTX context;
    CC_SHA512_Init(&context);
    if ([salt length]) {
        CC_SHA512_Update(&context, [salt bytes], (CC_LONG)[salt length]);
    }
    CC_SHA512_Update(&context, [self bytes], (CC_LONG)[self length]);
    CC_SHA512_Final(hash, &context);
    return [NSData dataWithBytes:hash length:CC_SHA512_DIGEST_LENGTH];
}

@end


来源:https://stackoverflow.com/questions/5632632/objective-c-sha512-hash-of-two-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!