iOS DES ECB模式对称加密解密
最近忙于android和iOS的项目,写完了android的DES 的ECB模式加密解密(相关连接www.zzzyk.com/kf/201210/162060.html),又回到了Ios上面,因为本人也是最近今年开始研究ios的,所以Ios上面好多东西都不懂,进过了半年的研究,终于吧ios的DES 的ECB模式对称加密解密搞定了,本人遇到的问题很严重的问题,网上写的好多16进制数转化位字节都有问题的,经过本人研究发现他们有一个地方写错了,导致解密后的NSString 位null,我的代码已经修复了这个问题,下面贴出源代码供大家参考:
首先贴出加密类的头文件:
01.//
02.// DesUtil.h
03.// Author:spring sky
04.// QQ:840950105
05.// Email:vipa1888@163.com
06.//
07.
08.#import <Foundation/Foundation.h>
09.
10.@inte易做图ce DesUtil : NSObject
11./**
12. DES加密
13. */
14.+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;
15.
16./**
17. DES解密
18. */
19.+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;
20.
21.
22.
23.@end
//
// DesUtil.h
// Author:spring sky
// QQ:840950105
// Email:vipa1888@163.com
//
#import <Foundation/Foundation.h>
@inte易做图ce DesUtil : NSObject
/**
DES加密
*/
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;
/**
DES解密
*/
+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;
@end
加密类的实现类:
01.//
02.// DesUtil.m
03.// Author:spring sky
04.// QQ:840950105
05.// Email:vipa1888@163.com
06.//
07.
08.#import "DesUtil.h"
09.#import <CommonCrypto/CommonCryptor.h>
10.#import "ConverUtil.h"
11.@implementation DesUtil
12.
13.
14.static Byte iv[] = {1,2,3,4,5,6,7,8};
15./*
16. DES加密
17. */
18.+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
19.{
20. NSString *ciphertext = nil;
21. NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding];
22. NSUInteger dataLength = [clearText length];
23. unsigned char buffer[1024];
24. memset(buffer, 0, sizeof(char));
25. size_t numBytesEncrypted = 0;
26.
27.
28. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
29. kCCOptionECBMode,
30. [key UTF8String], kCCKeySizeDES,
31. iv,
32. [textData bytes] , dataLength,
33. buffer, 1024,
34. &numBytesEncrypted);
35. if (cryptStatus == kCCSuccess) {
36. NSLog(@"DES加密成功");
37. NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
38. Byte* bb = (Byte*)[data bytes];
39. ciphertext = [ConverUtil parseByteArray2HexString:bb];
40. }else{
41. NSLog(@"DES加密失败");
42. }
43. return ciphertext;
44.}
45.
46./**
47. DES解密
48. */
49.+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key
50.{
51. NSString *cleartext = nil;
52. NSData *textData = [ConverUtil parseHexToByteArray:plainText];
53. NSUInteger dataLength = [textData length];
54. unsigned char buffer[1024];
55. memset(buffer, 0, sizeof(char));
56. size_t numBytesEncrypted = 0;
57.
58.
59. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
60. kCCOptionECBMode,
61. [key UTF8String], kCCKeySizeDES,
62. iv,
63. [textData bytes] , dataLength,
64. buffer, 1024,
65. &numBytesEncrypted);
66. if (crypt
补充:综合编程 , 安全编程 ,