今天终于把iOS平台下的DES加密算法调通了,在这里记录一下。说一下我遇到的问题吧。
第一,关于传参,Objective-C和C,C++一样,不能把值类型数组做为参数,传给另一个方法,方法的返回值的类型也一样不可以是值类型数组。一旦这么做了,接受参数的方法只能获取数组中的首元素。
解决方法是用 NSMutableData 把值类型的数组包一层,代码如下:
NSMutableData* bufkeyData = [NSMutableDatadataWithLength:2];
int* bufkey = bufkeyData.mutableBytes;
传参 [self make_key:bufkeyData number:j]; 取值 int* bufkey = bufkeyData.mutableBytes;
第二,NSData 与 Byte[]之间的转换
NSData *btsData = [in_str dataUsingEncoding:NSUTF8StringEncoding];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [btsData bytes], len);
NSMutableData *bts2Data = [NSMutableDatadataWithLength:len];
[bts2Data initWithBytes:byteData length:len];
第三,i386架构下定义值类型变量需赋初值
下面是头文件:
//
// DesEncrypt.h
// DesEncryptDemo
//
// Created by fred yu on 9/2/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
enumDesStrategy {
DesSimple = 1,
Des3 = 2,
DesCBC = 3,
DesTwoKeys = 4
};
typedef enum DesStrategy DesStrategy;
@interface DesEncrypt : NSObject {
NSMutableArray *keyArray;
}
-(NSData *)des:(NSData *)input_data key:(NSString *)key encrypt:(bool)encrypt;
//Encrypt
-(NSString*)encrypt:(NSString *)in_str key:(NSString *)key desMode:(DesStrategy)desMode str2:(NSString *)str2;
//Decrypt
-(NSString*)decrypt:(NSString *)in_str key:(NSString *)key desMode:(DesStrategy)desMode str2:(NSString *)str2;
//DesCBC
-(NSMutableData *)desCBC:(NSMutableData *)input_data key:(NSString *)key_str iv:(NSString *)iv encrypt:(bool)encrypt;
-(NSMutableData *)des:(NSMutableData *)data key:(NSMutableData *)key iv:(NSMutableData *)iv encrypt:(bool)encrypt;
//DesCreateKeys
-(void)desCreateKeys:(NSMutableData *)key;
//make_data
-(void)make_data:(NSMutableData *)data number:(int)number;
//make_key
-(NSMutableData *)make_key:(NSMutableData *)in_key number:(int)number;
//handle_data
-(NSMutableData *)handle_data:(NSMutableData *)data encrypt:(bool)encrypt;
//change_data
-(NSMutableData *)change_data:(NSMutableData *)olddata change_tbType:(int)change_tbType;
@end
测试代码及输出结果:
#import <Foundation/Foundation.h>
#import "DesEncrypt.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePoolalloc] init];
// insert code here...
DesEncrypt * desEncrypt = [[DesEncrypt alloc] init];
NSString *key1 = @"23245321";
NSString *key2 = @"77585210";
NSString *msg = @"abcdefghijk";
NSLog(@"消息: %@",msg);
NSString *s = [desEncrypt encrypt:msg key:key1 desMode:DesCBC str2:key2];
NSLog(@"经过加密处理: %@",s);
NSString *ss = [desEncrypt decrypt:s key:key1 desMode:DesCBC str2:key2];
NSLog(@"经过解密处理: %@",ss);
[pool drain];
return 0;
}
fred-yus-MacBook-Pro:~ fred$ /Users/fred/Documents/DesEncryptDemo/build/Debug/DesEncryptDemo ; exit;
2011-09-05 13:05:08.552 DesEncryptDemo[6085:903] 消息: abcdefghijk
2011-09-05 13:05:08.555 DesEncryptDemo[6085:903] 经过加密处理: vL5Am3KcszqpJdB594OrkA==
2011-09-05 13:05:08.555 DesEncryptDemo[6085:903] 经过解密处理: abcdefghijk
logout