Skip to content

Instantly share code, notes, and snippets.

@tudormunteanu
Created February 4, 2013 14:27
Show Gist options
  • Save tudormunteanu/4706999 to your computer and use it in GitHub Desktop.
Save tudormunteanu/4706999 to your computer and use it in GitHub Desktop.
#import "IPBinaryEncrypter.h"
#define BUFFER_SIZE 1024
@implementation IPBinaryEncrypter
// Yes, let's try new curly brackets style :)
// and see if I can improve 7 years of coding
- (void) decryptFile:(NSString *)filePath
withCompletion:(void (^)(void))completion
failure:(void (^)(void))failure
{
NSString *outputPath = [filePath stringByAppendingString:@"_dec.zip"];
__block NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:outputPath append:YES];
__block NSError *decryptionError = nil;
[outputStream open];
__block NSUInteger totalBytesRead = 0;
RNOpenSSLDecryptor *decryptor = [[RNOpenSSLDecryptor alloc] initWithSettings:kRNCryptorAES256Settings
password:@"1234"
handler:^(RNCryptor *cryptor, NSData *data)
{
totalBytesRead += data.length;
[outputStream write:data.bytes maxLength:data.length];
if (cryptor.isFinished)
{
//close the outputStream
[outputStream close];
decryptionError = cryptor.error;
completion();
}
}];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:filePath];
[inputStream open];
Byte buffer[BUFFER_SIZE];
while ([inputStream hasBytesAvailable])
{
int bytesRead = [inputStream read:buffer maxLength:BUFFER_SIZE];
NSData *data = [NSData dataWithBytes:buffer length:bytesRead];
[decryptor addData:data];
}
[decryptor finish];
[inputStream close];
}
- (void) encryptFile:(NSString *)filePath
withCompletion:(void (^)(void))completion
failure:(void (^)(void))failure
{
NSString *outputPath = [filePath stringByAppendingString:@"_enc.zip"];
__block NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:outputPath append:YES];
__block NSError *decryptionError = nil;
[outputStream open];
__block NSUInteger totalBytesRead = 0;
RNOpenSSLEncryptor *encryptor = [[RNOpenSSLEncryptor alloc] initWithSettings:kRNCryptorAES256Settings
password:@"1234"
handler:^(RNCryptor *cryptor, NSData *data)
{
totalBytesRead += data.length;
[outputStream write:data.bytes maxLength:data.length];
if (cryptor.isFinished)
{
//close the outputStream
[outputStream close];
decryptionError = cryptor.error;
completion();
}
}];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:filePath];
[inputStream open];
Byte buffer[BUFFER_SIZE];
while ([inputStream hasBytesAvailable])
{
int bytesRead = [inputStream read:buffer maxLength:BUFFER_SIZE];
NSData *data = [NSData dataWithBytes:buffer length:bytesRead];
[encryptor addData:data];
}
[encryptor finish];
[inputStream close];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment