1 #import "ITCategory-NSData.h"
2 #import <openssl/bio.h>
3 #import <openssl/evp.h>
4 #import <openssl/md5.h>
5 #import <openssl/sha.h>
7 @implementation NSData (ITFoundationCategory)
9 + (id)dataWithBase64:(NSString *)base64 {
10 return [[[self alloc] initWithBase64:base64] autorelease];
13 - (id)initWithBase64:(NSString *)base64 {
14 BIO *mem = BIO_new_mem_buf((void *)[base64 cString], [base64 cStringLength]);
15 BIO *b64 = BIO_new(BIO_f_base64());
16 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
17 mem = BIO_push(b64, mem);
19 NSMutableData *data = [NSMutableData data];
22 while ((inlen = BIO_read(mem, inbuf, sizeof(inbuf))) > 0) {
23 [data appendBytes:inbuf length:inlen];
27 return [self initWithData:data];
30 - (NSString *)hexadecimalRepresentation {
31 int dataLength = [self length];
32 int stringLength = dataLength * 2;
34 char *dataBytes = [self bytes];
35 char hexString[stringLength];
38 for (i=0; i < dataLength; i++) {
39 sprintf(hexString + (i * 2), "%02x", dataBytes[i]);
42 return [NSString stringWithCString:hexString length:stringLength];
45 - (NSString *)base64 {
46 BIO *mem = BIO_new(BIO_s_mem());
47 BIO *b64 = BIO_new(BIO_f_base64());
48 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
49 mem = BIO_push(b64, mem);
51 BIO_write(mem, [self bytes], [self length]);
55 long base64Length = BIO_get_mem_data(mem, &base64Char);
56 NSString *base64String = [NSString stringWithCString:base64Char length:base64Length];
64 unsigned char digest[length];
65 MD5([self bytes], [self length], digest);
66 return [NSData dataWithBytes:&digest length:length];
71 unsigned char digest[length];
72 SHA1([self bytes], [self length], digest);
73 return [NSData dataWithBytes:&digest length:length];