如何解密iOS中的DES加密字符串?

时间:2011-08-24 07:55:09

标签: iphone ios ipad

我使用PHP在DES算法中使用PKCS#7填充来加密字符串。

我想知道如何在iOS中使用CCCrypt来解密DES加密字符串。如果您能提供一些示例代码来帮助我,请欣赏它。

感谢。

1 个答案:

答案 0 :(得分:-1)

- (NSData *)encryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;
size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer = malloc(bufferSize);

CCCryptorStatus result = CCCrypt( kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer, bufferSize,
                                 &numBytesEncrypted);
NSData *output = [NSData dataWithBytes:buffer length:numBytesEncrypted];
free(buffer);
if( result == kCCSuccess )
{
    NSLog(@"encoded str %@",[output base64EncodedStringWithOptions:0]);
    return output;
} else {
    NSLog(@"Failed DES encrypt...");
    return nil;
}
}
- (NSData *) decryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;

size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer_decrypt = malloc(bufferSize);
CCCryptorStatus result = CCCrypt( kCCDecrypt , kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer_decrypt, bufferSize,
                                 &numBytesEncrypted );

NSData *output = [NSData dataWithBytes:buffer_decrypt length:numBytesEncrypted];
free(buffer_decrypt);
if( result == kCCSuccess )
{
    NSString *decodedString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
    NSLog(@"decoded str %@",decodedString);
    return output;
} else {
    NSLog(@"Failed DES decrypt ...");
    return nil;
}
}

- 然后你可以调用像

这样的方法
  [self decryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:[self encryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:["YOUR--INPUT__STRING" dataUsingEncoding:NSUTF8StringEncoding]]];

- " qwertykey"是提供的密钥