Skip to content

Instantly share code, notes, and snippets.

@software-mariodiana
Last active January 2, 2019 18:24
Show Gist options
  • Save software-mariodiana/e088cce12b56bff47742bdd57567a3ff to your computer and use it in GitHub Desktop.
Save software-mariodiana/e088cce12b56bff47742bdd57567a3ff to your computer and use it in GitHub Desktop.
How to hash plaintext.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
NSString* const MDXHashSalt = @"usesomekindofsecret";
@interface MDXHash : NSObject
- (NSString *)createHash:(NSString *)plaintext;
@end
@implementation MDXHash
- (NSString *)createHash:(NSString *)plaintext
{
// Combine password with salt.
NSMutableData* buffer = [NSMutableData dataWithData:[plaintext dataUsingEncoding:NSUTF8StringEncoding]];
[buffer appendData:[MDXHashSalt dataUsingEncoding:NSUTF8StringEncoding]];
NSData* digest = [self createHashFromData:buffer];
// Adapted from: https://ademcan.net/blog/2018/08/03/how-to-convert-a-nsdata-hexstring-to-a-nsstring-in-objective-c/
NSMutableString* sb = [[NSMutableString alloc] initWithCapacity:([digest length] * 2)];
const unsigned char* bytes = (const unsigned char *)[digest bytes];
for (int i = 0; i < [digest length]; i++) {
[sb appendFormat:@"%02lx", (unsigned long)bytes[i]];
}
return [NSString stringWithString:sb];
}
- (NSData *)createHashFromData:(NSData *)data
{
// Adapted from: https://stackoverflow.com/a/6228385/155167
unsigned char hash[CC_SHA256_DIGEST_LENGTH];
if (CC_SHA256([data bytes], (CC_LONG)[data length], hash)) {
NSData* sha = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH];
return sha;
}
// We don't want to return nil.
return [[NSData alloc] init];
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
id hasher = [[MDXHash alloc] init];
NSString* result = [hasher createHash:@"Hello, World!"];
NSLog(@"%@", result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment