在iOS上使用MD5密钥解密3DES ECB

时间:2011-01-20 15:25:11

标签: ios objective-c cryptography 3des ecb

我正在尝试从iOS应用程序中的.NET服务器解密数据。数据已在ECB模式下使用3DES加密。我能够在Android上成功解密相同的数据,但在IOS上我只是不断获得垃圾输出。

我比较了iOS和Android之间的加密字节和消化的密钥字节,它们看起来是一样的(尽管我必须将签名的Java字节转换为十六进制表示,以便能够与xcode debugger进行比较)。但是,Java加密对象的级别比Common Crypto高,所以我不确定我是否正确准备了密钥。请查看以下代码 - 欢迎任何反馈。

//read the encrypted data from file into NSData
NSString *servicesPath = [NSString stringWithString:[[AppMobiDelegate applicationDocumentsDirectory] stringByAppendingPathComponent:@"services.xml"]];
NSData *servicesData = [NSData dataWithContentsOfFile:servicesPath];

//setup crypto objects
const void *vEncryptedText = [servicesData bytes];
size_t encryptedTextBufferSize = [servicesData length];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (encryptedTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);

//get a cstring with key data
const char *cStr = [@"FAKEKEY" cStringUsingEncoding:UTF8String];

//make a 16 byte array to put the md5 digested data into    
unsigned char md5[CC_MD5_DIGEST_LENGTH];
bzero( md5, sizeof(md5) );
CC_MD5( cStr, strlen(cStr), md5 );
//make a 24 byte array so we have correct size for 3des key and copy digest data in
unsigned char key[kCCKeySize3DES];
bzero( key, sizeof(key) );
memcpy(key, md5, sizeof(md5));  

//decrypt data and return string 
ccStatus = CCCrypt(kCCDecrypt,
    kCCAlgorithm3DES,
    kCCOptionECBMode, //kCCOptionPKCS7Padding kCCOptionECBMode
    key, //vKey md5
    kCCKeySize3DES,
    NULL,
    vEncryptedText,
    encryptedTextBufferSize,
    (void *)bufferPtr,
    bufferPtrSize,
    &movedBytes);

if (ccStatus == kCCParamError) return @"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED";

NSString *result = [[[NSString alloc] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
return result;

0 个答案:

没有答案