gpt4 book ai didi

iphone - 河豚算法 objective-c

转载 作者:行者123 更新时间:2023-11-29 10:54:37 24 4
gpt4 key购买 nike

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

我正在使用以下代码:

-(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 库代码,例如。 here

最佳答案

HINT#1//一般答案

NSString 为此目的提供了一个初始化器。可以看到more info using the docs here.

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

关于iphone - 河豚算法 objective-c ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com