Creare un hash MD5 da una NSString
Quando si crea un sistema di registrazione e login, con qualsiasi linguaggio si tratti, è sempre bene salvare l'hash della password, e non la password in chiaro.
Oggi vediamo come calcolare l'hsh MD5 di una NSString in Objective-C.
L'SDK per iPhone e iPad già dispone gli strumenti adatti per usare MD5.
Bisogna solo attivarli.
Create una classe apposita; la mi si chiama StrMD5.
L'interfaccia sarà così:
#import <Foundation/Foundation.h>
@interface NSString (StrMD5)
- (NSString*) MD5;
@end
Come vedete l'interfaccia è dichiarata come estensione di NSString.
Ha poi un solo metodo, che è quello che calcolerà l'hash.
L'implementazione della classe sarà così:
#import "StrMD5.h"
#import <CommonCrypto/CommonDigest.h>@implementation NSString(StrMD5)
- (NSString*) MD5 {
// PUNTATORE A UNA STRING COME UTF8
const char *ptr = [self UTF8String];
// CREAZIONE DI UN ARRAY DI BYTE DI TIPO UNSIGNED CHAR
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// CREAZIONE DELL'HASH
CC_MD5(ptr, strlen(ptr), md5Buffer);
// CONVERSIONE DEL VALORE DEL VALORE MD5 INA UNA NSSTRING
NSMutableString *output = [NSMutableString stringWithCapacity: CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", md5Buffer[i]];
}
return output;
}@end
A questo punto non ci rimane che richiamare questo metodo.
Ad esempio alla pressione del tasto:
- (IBAction)btnLogin:(id)sender {
NSString *strPwd = [txtPwd text];
NSLog(@"%@", [strPwd MD5]);
}
Dove txtPwd è la mia UITextField.
objective-c nsstring md5 uitextfield uibutton
Commentami!