1

我必须在我的代码中使用 Blowfish 算法进行加密和解密。调用解密方法后blowfishDecrypt,我得到了值,但是当我将它转换为NSStringNSData时,它总是给我null

我正在使用以下代码:

-(void)methodCalled
{
   syncTime=@"c7c937169084b20c3ff882dcda193a59";
   NSData* data = [syncTime dataUsingEncoding:NSUTF8StringEncoding];
   NSData* data2 = [@"R=U!LH$O2B#" dataUsingEncoding:NSUTF8StringEncoding];
   NSData* dycryptData=[self blowfishDecrypt:data usingKey:data2];

   // prints <0eec37b6 2b76c2df cdf72356 0f033ed8 d6bd37dd 5223bf66 5c318ebe 07f3cf71>
   NSLog(@"%@",dycryptData);

   NSString *dSync=[[NSString alloc] initWithBytes:[dycryptData bytes] 
                                     length:[dycryptData length] 
                                     encoding:NSUTF8StringEncoding];

   // prints (null)
   NSLog(@"Sync timeis %@",dSync);
} 



-(NSData *)blowfishDecrypt:(NSData *)messageData 
                  usingKey:(NSData *)secretKeyData {

    NSMutableData *decryptedData = [messageData mutableCopy];
    BLOWFISH_CTX ctx;
    Blowfish_Init (&ctx, (unsigned char*)[secretKeyData bytes], [secretKeyData length]);

    NSRange aLeftRange, aRightRange;
    NSData *aLeftBox, *aRightBox;
    unsigned long dl = 0, dr = 0;

    for (int i = 0; i< [decryptedData length]; i += 8) { // Divide data into octets...
        // …and then into quartets
        aLeftRange = NSMakeRange(i, 4);
        aRightRange = NSMakeRange(i + 4, 4);

        aLeftBox = [decryptedData subdataWithRange:aLeftRange];
        aRightBox = [decryptedData subdataWithRange:aRightRange];

        // Convert bytes into unsigned long
        [aLeftBox getBytes:&dl length:sizeof(unsigned long)];
        [aRightBox getBytes:&dr length:sizeof(unsigned long)];

        // Decipher
        Blowfish_Decrypt(&ctx, &dl, &dr);

        // Put bytes back
        [decryptedData replaceBytesInRange:aLeftRange withBytes:&dl];
        [decryptedData replaceBytesInRange:aRightRange withBytes:&dr];
    }

    return decryptedData;
}

可以找到 Blowfish 库代码,例如。这里

4

1 回答 1

2

HINT#1 //一般答案

NSString为此目的提供了一个初始化程序。您可以使用此处的文档查看更多信息。

NSString * dSync = [[NSString alloc] initWithData: dycryptData 
                                      encoding:NSUTF8StringEncoding];

假设您使用 ARC。

HINT#2 //这个特定问题的答案

我尝试了您的代码并确认上述 NSString 转换返回 null。那么为什么它不起作用呢?dycryptData 是表示为十六进制的字节流,因此我尝试了以下操作并收到了所需的结果:

int dycryptData_len = [dycryptData length];
NSMutableString *dSync_hex = [NSMutableString stringWithCapacity:dycryptData_len*2];
const unsigned char *dycryptData_bytes = [dycryptData bytes];
for (int i = 0; i < dycryptData_len; ++i) {
    [dSync_hex appendFormat:@"%02x", dycryptData_bytes[i]];
}

NSLog(@"dSync_hex=%@",dSync_hex);

我可以在日志输出中看到这个结果:

dSync_hex=0eec37b62b76c2dfcdf723560f033ed8d6bd37dd5223bf665c318ebe07f3cf71

于 2013-09-24T13:03:05.307 回答