3

我正在尝试加密 xml 字符串。加密完成后解密加密的 d 我将字符串作为 ALIGNMENT。
我不明白是什么原因

(NSString*) doCipher:(NSString*)plainText:(CCOperation)encryptOrDecrypt {

const void *vplainText;
size_t plainTextBufferSize;

if (encryptOrDecrypt == kCCDecrypt)
{
    NSData *EncryptData = [NSData dataFromBase64String:plainText];
    plainTextBufferSize = [EncryptData length];
    vplainText = [EncryptData bytes];
}
else
{
    plainTextBufferSize = [plainText length];
    vplainText = (const void *) [plainText UTF8String];
}

CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t iv[kCCBlockSize3DES];

bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));

NSString *key = @"123456789012345678901234";
NSString *initVec = @"init Vec";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];

ccStatus = CCCrypt(encryptOrDecrypt,
                   kCCAlgorithm3DES,
                   kCCOptionPKCS7Padding,
                   vkey, //"123456789012345678901234", //key
                   kCCKeySize3DES,
                   vinitVec, //"init Vec", //iv,
                   vplainText, //"Your Name", //plainText,
                   plainTextBufferSize,
                   (void *)bufferPtr,
                   bufferPtrSize,
                   &movedBytes);
//if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
//else/
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;

if (encryptOrDecrypt == kCCDecrypt)
{
    result = [ [NSString alloc] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding];
}
else
{
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    result = [myData base64EncodedString];
}    
return result;    
}
4

1 回答 1

4

kCCAlignmentError means that the data you are passing is not correctly padded (specifically that the entire data length including padding is not a multiple of the block size). The most likely cause is that you are truncating your encrypted data somewhere, possibly outside of this routine.

You should check your encrypted data at each step and make sure that it is always a multiple of the block size (8 bytes). You'll need to base64-decode before checking the length.

于 2013-10-09T13:41:25.580 回答