gpt4 book ai didi

ios 3DES加密/解密CBC

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

我需要一些有关此 3DES 解密的帮助。我已经创建了一些用于解密的代码,但我无法让它正常工作。这是我第一次尝试加密,我不知道我到底做错了什么。

我正在从服务器接收用于解密的 key (这是 key 的示例值:0F7BC98767FF9A01F2B2AD1CD644AD33 - 它是随机生成字节的十六进制表示)。

这是我用来解密消息的方法:

-(NSString*)doCipher:(NSString*)message key:(NSString*)key operation:(CCOperation)encryptOrDecrypt {

const void *messageData;
size_t messageBufferSize;

if (encryptOrDecrypt == kCCDecrypt){
NSData *messageEncryptData= [NSData dataWithBase64EncodedString:message];
messageBufferSize= [messageEncryptData length];
messageData= [messageEncryptData bytes];
}
else{
messageBufferSize= message.length;
messageData = [[[message dataUsingEncoding: NSUTF8StringEncoding]mutableCopy] bytes];
}

CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;

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

uint8_t iv[kCCBlockSize3DES];
memset((void *) iv, 0x0, (size_t) sizeof(iv));



NSData *keyData = [[key dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];

ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding & kCCModeCBC,
(const void *)[keyData bytes],
kCCKeySize3DES,
iv,
messageData,
messageBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);

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";

NSLog(@"bufferPtr: %s", bufferPtr);

NSString *s = [[NSString alloc] initWithFormat:@"%s", bufferPtr];
return s;
}

-- 编辑 ---这是我从该方法收到的输出:

bufferPtr: Ã' ÕÏÁU

--- 编辑 2 -----我将 key 长度固定为 24 字节长,但现在最终结果是空字符串

最佳答案

我发现了我的问题。这是我阅读 key 的方式。

我创建了这个将十六进制字符串转换为 NSData 的方法:

+ (NSData *)dataFromHexString: (NSString *) hex {
const char *chars = [hex UTF8String];
int i = 0, len = hex.length;

NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
char byteChars[3] = {'\0','\0','\0'};
unsigned long wholeByte;

while (i < len) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}

return data;
}

然后这就是我设法解密该死的东西的方法:

NSData *keyData = [Utilities dataFromHexString:key];

ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
[keyData bytes],
[keyData length],
iv,
messageData,
messageBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);

抱歉浪费您的时间:)

关于ios 3DES加密/解密CBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27296851/

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