开发者

Objective C SHA512 hash of two NSData

开发者 https://www.devze.com 2023-02-24 17:13 出处:网络
Here is a Java code, which computes SHA512 hash of a byte array with salt: private static String DIGEST_ALGORITHM = \"SHA-512\";

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 {...}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消