在iOS中获得AES128 / CBC / PKCS5

时间:2015-02-10 11:35:51

标签: ios encryption aes security-framework

我必须拨打具有以下加密要求 AES128 / CBC / PKCS5Padding 的安全服务器,但iOS中提供的CCCrypt或CommonCrypto库提供带CBC模式的PKCS7Padding。

任何想法如何实现此加密,因为服务器是第三方,其实现无法更改。我正在使用自定义IV。

请求代码在这里。

NSString* exampleXML = @"<my xml file contents>"
const char myByteArray1[] = {
    0x12,0x13,0x14,0x15,
    0x16,0x17,0x18,0x19,
    0x12,0x13,0x14,0x15,
    0x16,0x17,0x18,0x19 };

NSData *iv = [NSData dataWithBytes:myByteArray length:sizeof(myByteArray)];

NSString* headPadding=@"GH12RT25Y2";
int* status=nil;

NSString* encryptionKey=@"FTH25GFD658ERT21YHU21==2";
NSString* base64encodedPass=[[encryptionKey dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]; // Base64 Encode

// Using NSData+CommonCrypto.h
NSData * encrypted = [[exampleXml dataUsingEncoding:NSUTF8StringEncoding] dataEncryptedUsingAlgorithm:kCCAlgorithmAES128 key:base64encodedPass initializationVector:iv options:kCCOptionPKCS7Padding error:status];

NSMutableData *headData =[NSMutableData dataWithData:[headPadding dataUsingEncoding:NSUTF8StringEncoding]];
[headData appendData:encrypted]; 


NSURL *sRequestURL = [NSURL URLWithString:@"myurl.com"];

NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:sRequestURL];
NSString *sMessageLength = [NSString stringWithFormat:@"%lu", (unsigned long)[headData length]];

[myRequest addValue: @"text/xml;  charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// [myRequest addValue: @"text/xml" forHTTPHeaderField:@"Content-Type"];

[myRequest addValue: sMessageLength forHTTPHeaderField:@"Content-Length"];
[myRequest setHTTPMethod:@"POST"];
[myRequest setHTTPBody:headData];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
[theConnection start];

回复说:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Couldn't parse stream.</faultstring></soap:Fault></soap:Body></soap:Envelope>

1 个答案:

答案 0 :(得分:0)

你有没有试过看它是否有效?在许多情况下,两者可以交换而不会出现问题。填充发生在最后,所以如果你只是垃圾,它不是引起问题的填充。