QNDes.m 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // QNDes.m
  3. // HappyDNS
  4. //
  5. // Created by bailong on 15/8/1.
  6. // Copyright (c) 2015年 Qiniu Cloud Storage. All rights reserved.
  7. //
  8. #import <CommonCrypto/CommonCryptor.h>
  9. #import "QNDes.h"
  10. @interface QNDes ()
  11. @property (nonatomic, strong) NSData *key;
  12. @end
  13. @implementation QNDes
  14. - (NSData *)encrypt:(NSData *)data {
  15. const void *input = data.bytes;
  16. size_t inputSize = data.length;
  17. size_t bufferSize = (inputSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
  18. uint8_t *buffer = malloc(bufferSize * sizeof(uint8_t));
  19. memset((void *)buffer, 0x0, bufferSize);
  20. size_t movedBytes = 0;
  21. const void *vkey = _key.bytes;
  22. CCCryptorStatus ccStatus = CCCrypt(kCCEncrypt,
  23. kCCAlgorithmDES,
  24. kCCOptionECBMode | kCCOptionPKCS7Padding,
  25. vkey,
  26. kCCKeySizeDES,
  27. NULL,
  28. input,
  29. inputSize,
  30. (void *)buffer,
  31. bufferSize,
  32. &movedBytes);
  33. if (ccStatus != kCCSuccess) {
  34. NSLog(@"error code %d", ccStatus);
  35. free(buffer);
  36. return nil;
  37. }
  38. NSData *encrypted = [NSData dataWithBytes:(const void *)buffer length:(NSUInteger)movedBytes];
  39. free(buffer);
  40. return encrypted;
  41. }
  42. - (NSData *)decrpyt:(NSData *)raw {
  43. const void *input = raw.bytes;
  44. size_t inputSize = raw.length;
  45. size_t bufferSize = 1024;
  46. uint8_t *buffer = malloc(bufferSize * sizeof(uint8_t));
  47. memset((void *)buffer, 0x0, bufferSize);
  48. size_t movedBytes = 0;
  49. const void *vkey = _key.bytes;
  50. CCCryptorStatus ccStatus = CCCrypt(kCCDecrypt,
  51. kCCAlgorithmDES,
  52. kCCOptionECBMode | kCCOptionPKCS7Padding,
  53. vkey,
  54. kCCKeySizeDES,
  55. NULL,
  56. input,
  57. inputSize,
  58. (void *)buffer,
  59. bufferSize,
  60. &movedBytes);
  61. if (ccStatus != kCCSuccess) {
  62. NSLog(@"error code %d", ccStatus);
  63. free(buffer);
  64. return nil;
  65. }
  66. NSData *decrypted = [NSData dataWithBytes:(const void *)buffer length:(NSUInteger)movedBytes];
  67. free(buffer);
  68. return decrypted;
  69. }
  70. - (instancetype)init:(NSData *)key {
  71. if (self = [super init]) {
  72. _key = key;
  73. }
  74. return self;
  75. }
  76. @end