dongtuliao6760 2012-09-08 09:12
浏览 116
已采纳

IOS DES加密和PHP解密无法可靠地工作

I'm encrypting a string in iOS using the method below


-(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);
}

And on php, I'm decrypting the string as follows -


$decrypted = mcrypt_decrypt(MCRYPT_DES, 'complexkey', base64_decode(urldecode($encrypted)), MCRYPT_MODE_ECB);

This seems to work correctly 75% of the time and I'm not sure why it fails at other times. Any clues? Thanks for the help!

  • 写回答

2条回答 默认 最新

  • dongtu0088 2012-09-08 19:30
    关注

    It turns out that there was nothing wrong in the encryption/decryption I was doing. Rather the issue was that urldecode() in PHP wasn't decoding '%2B' to '+' (but instead to ' '). I switched from urldecode() to rawurldecode() in PHP and everything is working fine now!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂