iOS des加密
CCCryptorStatus CCCrypt(
CCOperation op,
CCAlgorithm alg,
CCOptions options,
const void *key,
size_t keyLength,
const void *iv,
const void *dataIn,
size_t dataInLength,
void *dataOut,
size_t dataOutAvailable,
size_t *dataOutMoved)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);
网上找来的一个加密解密的文件(稍微改了一下):
.h文件:
+ (NSString *)encryptWithText:(NSString *)sText theKey:(NSString *)aKey;
+ (NSString *)decryptWithText:(NSString *)sText theKey:(NSString *)aKey;
.m文件:
+ (NSString *)encrypt:(NSString *)sText encryptOrDecrypt:(CCOperation)encryptOperation key:(NSString *)key
{
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOperation == kCCDecrypt)
{
NSData *decryptData = [GTMBase64 decodeData:[sTextdataUsingEncoding:NSUTF8StringEncoding]];
//NSData *decryptData = [GTMBase64 decodeString:sText ];
plainTextBufferSize = [decryptData length];
vplainText = [decryptData bytes];
}
else
{
NSData* encryptData = [sText dataUsingEncoding:NSUTF8StringEncoding];
plainTextBufferSize = [encryptData length];
vplainText = (const void *)[encryptData bytes];
}
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
NSString *initVec = @"12345678";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];
CCCryptorStatus ccStatus = CCCrypt(encryptOperation,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey,
kCCKeySize3DES,
vinitVec,
vplainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSLog(@"%d",ccStatus);
NSString *result = nil;
if (ccStatus == kCCSuccess)
{
if (encryptOperation == kCCDecrypt)
{
result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtrlength:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding] ;
}
else
{
NSData *data = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [GTMBase64 stringByEncodingData:data];
// NSLog(@"result:%@",result);
// NSData *temp = [GTMBase64 decodeString:result];
}
}
return result;
}
+ (NSString *)encryptWithText:(NSString *)sText theKey:(NSString *)aKey
{
return [self encrypt:sText encryptOrDecrypt:kCCEncrypt key:aKey];
}
+ (NSString *)decryptWithText:(NSString *)sText theKey:(NSString *)aKey
{
return [self encrypt:sText encryptOrDecrypt:kCCDecrypt key:aKey];
}