Last active
January 2, 2019 18:24
-
-
Save software-mariodiana/e088cce12b56bff47742bdd57567a3ff to your computer and use it in GitHub Desktop.
How to hash plaintext.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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