【问题标题】:Objective c decode encrypted dataObjective c 解码加密数据
【发布时间】:2014-11-23 21:12:47
【问题描述】:

我从 REST Web 服务调用中收到一段加密的 json。以下 ruby​​ 代码将响应正确解码回 json。接收到的数据首先进行base64解码,然后前16个字节被当作iv,其余的作为数据。密钥首先被去十六进制(缺乏更好的表达)。

encrypted = Base64.decode64(res) #base 64 decode

de_cipher = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
de_cipher.decrypt
de_cipher.key = [key].pack('H*') #de-hex the key
de_cipher.iv = encrypted[0..15] # the first 16 bytes is the IV

descrypted = de_cipher.update(encrypted) << de_cipher.final;
json_string = descrypted[16 .. (descrypted.size - 1)] #taking away the first 16, rest is data

ruby 代码只是为我理解数据做准备。我真正需要的是调用这个网络服务并在 iPhone 上的目标 c 中解码。但到目前为止还没有运气,我无法将收到的字符串解密为正确的 json。以下是我所拥有的:

//self.responseData is received through NSURLConnection, pretty sure it is piece together correctly. But there is \r\n at the end, which made it not correct length for base64, so I took the last two bytes away.
NSString *str = [[[NSString alloc] initWithData:[self.responseData subdataWithRange:(NSRange){0, self.responseData.length - 2}] encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"tvm get token response = [%@]",str);

//CreateDataWithHexString is something I found on stack overflow, supposed to reverse hex string to binary
NSString * key =[[MyProfile sharedInstance] getOneProperty:TVM_KEY];
//NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
NSData *keyData = [self CreateDataWithHexString:key];

//base64 decode the received string
NSData * whole = [[NSData alloc] initWithBase64EncodedString:str options:0];
NSData * iv = [whole subdataWithRange:(NSRange){0, 16}];
NSData * data = [whole subdataWithRange:(NSRange){16, whole.length - 16}];

CCCryptorStatus ccStatus   = kCCSuccess;
size_t          cryptBytes = 0;    // Number of bytes moved to buffer.
NSMutableData  *dataOut    = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];

ccStatus = CCCrypt(kCCDecrypt,
                   kCCAlgorithmAES128,
                   kCCOptionPKCS7Padding,
                   keyData.bytes,
                   kCCKeySizeAES128,
                   iv.bytes,
                   data.bytes,
                   data.length,
                   dataOut.mutableBytes,
                   dataOut.length,
                   &cryptBytes);

if (ccStatus == kCCSuccess) {
    dataOut.length = cryptBytes;
    NSString * json = [dataOut base64Encoding];
    NSLog(@"json = [%@]", dataOut);
    NSLog(@"json = [%@]", json);
}
else {

密钥最初生成如下,希望像上面那样去十六进制:

CFUUIDRef theKeyUUID = CFUUIDCreate(NULL);
CFStringRef keyuuid = CFUUIDCreateString(NULL, theKeyUUID);
CFRelease(theKeyUUID);
//server side expect a uuid without those -'s.
NSString * key = [(__bridge NSString *)keyuuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
CFRelease(keyuuid); 

下面是我在堆栈溢出时发现的 CreateDataWithHexString,希望它在这里是为了正确的目的:

-(NSData *)CreateDataWithHexString:(NSString *)inputString
{
NSUInteger inLength = [inputString length];

unichar *inCharacters = alloca(sizeof(unichar) * inLength);
[inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];

UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));

NSInteger i, o = 0;
UInt8 outByte = 0;
for (i = 0; i < inLength; i++) {
    UInt8 c = inCharacters[i];
    SInt8 value = -1;

    if      (c >= '0' && c <= '9') value =      (c - '0');
    else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A');
    else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a');

    if (value >= 0) {
        if (i % 2 == 1) {
            outBytes[o++] = (outByte << 4) | value;
            outByte = 0;
        } else {
            outByte = value;
        }

    } else {
        if (o != 0) break;
    }
}

return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES];
}

【问题讨论】:

    标签: objective-c rest encryption hex encryption-symmetric


    【解决方案1】:

    最后解密部分没问题,但显示错误。都是因为这一行:

    NSString * json = [dataOut base64Encoding]; 
    

    我看的不是解密数据,而是它的Base64 编码字符串,显然它看起来不像是一个有效的JSON

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2015-11-09
      • 1970-01-01
      • 2016-01-21
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多