Enabling garbage collection support.
[ITFoundation.git] / ITCategory-NSData.m
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>
6
7 @implementation NSData (ITFoundationCategory)
8
9 + (id)dataWithBase64:(NSString *)base64 {
10         return [[[self alloc] initWithBase64:base64] autorelease];
11 }
12
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);
18
19         NSMutableData *data = [NSMutableData data];
20         char inbuf[512];
21         int inlen;
22         while ((inlen = BIO_read(mem, inbuf, sizeof(inbuf))) > 0) {
23                 [data appendBytes:inbuf length:inlen];
24         }
25
26         BIO_free_all(mem);
27         return [self initWithData:data];
28 }
29
30 - (NSString *)hexadecimalRepresentation {
31         int dataLength = [self length];
32         int stringLength = dataLength * 2;
33         
34         char *dataBytes = [self bytes];
35         char hexString[stringLength];
36         
37         int i;
38         for (i=0; i < dataLength; i++) {
39                 sprintf(hexString + (i * 2), "%02x", dataBytes[i]);
40         }
41         
42         return [NSString stringWithCString:hexString length:stringLength];
43 }
44
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);
50     
51     BIO_write(mem, [self bytes], [self length]);
52     BIO_flush(mem);
53     
54     char *base64Char;
55     long base64Length = BIO_get_mem_data(mem, &base64Char);
56     NSString *base64String = [NSString stringWithCString:base64Char length:base64Length];
57     
58     BIO_free_all(mem);
59     return base64String;
60 }
61
62 - (NSData *)MD5 {
63         int length = 16;
64         unsigned char digest[length];
65         MD5([self bytes], [self length], digest);
66         return [NSData dataWithBytes:&digest length:length];
67 }
68
69 - (NSData *)SHA1 {
70         int length = 20;
71         unsigned char digest[length];
72         SHA1([self bytes], [self length], digest);
73         return [NSData dataWithBytes:&digest length:length];
74 }
75
76 @end