iOS开发中DES/CBC加密

iOS开发中DES/CBC/PKCS5Padding方式的加密

<pre><code>

import <CommonCrypto/CommonCryptor.h>

+(NSString **)encryptUseDES:(NSString *)plainText andKey:(NSString *)authKey andIv:(NSString *)authIv{

const void *iv  = (const void *) [authIv UTF8String];

NSString *ciphertext = nil;

NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];

NSUInteger dataLength = [textData length];

unsigned char buffer[1024];

memset(buffer, 0, sizeof(char));

size_t numBytesEncrypted = 0;

CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                      kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding,
                                      [authKey UTF8String],
                                      kCCKeySizeDES,
                                      iv,
                                      [textData bytes],
                                      dataLength,
                                      buffer,
                                      1024,
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
    NSString *oriStr = [NSString stringWithFormat:@"%@",data];
    NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@"< >"];
    ciphertext = [[oriStr componentsSeparatedByCharactersInSet:cSet] componentsJoinedByString:@""];

}

return ciphertext;

}

二、

-(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
{

      NSString *ciphertext = nil;

      const char  *textBytes = [plainText UTF8String];
      NSUInteger dataLength = [plainText length];
      unsigned char buffer[1024];
      memset(buffer, 0, sizeof(char));
      const void *iv = (const void *)[key UTF8String];
      size_t numBytesEncrypted = 0;

      CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding,
                                      [key UTF8String], kCCKeySizeDES,
                                      iv,
                                      textBytes, dataLength,
                                      buffer, 1024,
                                      &numBytesEncrypted);


      if (cryptStatus == kCCSuccess) {
      NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
      ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
}
      return ciphertext;

}

推荐阅读更多精彩内容