我正在使用下面的方法在 iOS 中加密一个字符串
-(NSString *) encrypt:(NSString *) data
{
const void *vplainText;
size_t plainTextBufferSize = [data length];
vplainText = (const void *) [data UTF8String];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
Byte iv [] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef};
NSString *key = @"complexkey";
const void *vkey = (const void *) [key UTF8String];
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding | kCCOptionECBMode,
vkey,
kCCKeySizeDES,
iv,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *result = [myData base64Encoding];
// url encode the result
return (__bridge NSString *) CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef) result,
NULL,
(__bridge CFStringRef) @"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
}
在 php 上,我将字符串解密如下 -
$decrypted = mcrypt_decrypt(MCRYPT_DES, 'complexkey', base64_decode(urldecode($encrypted)), MCRYPT_MODE_ECB);
这似乎在 75% 的时间里都能正常工作,我不确定为什么它在其他时候会失败。有什么线索吗?谢谢您的帮助!