美文网首页
iOS实现DES加密代码片段

iOS实现DES加密代码片段

作者: 欢博 | 来源:发表于2018-04-14 20:06 被阅读5次

#import "DESUtils.h"

@implementation DESUtils

+(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key

{

    NSString *plaintext = nil;

    NSData *cipherdata = [Base64 decode:cipherText];

    unsigned char buffer[1024];

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

    size_t numBytesDecrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,

                                          kCCOptionPKCS7Padding,

                                          [key UTF8String], kCCKeySizeDES,

                                          (Byte *)[[key dataUsingEncoding:NSUTF8StringEncoding] bytes],

                                          [cipherdata bytes], [cipherdata length],

                                          buffer, 1024,

                                          &numBytesDecrypted);

    if(cryptStatus == kCCSuccess) {

        NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];

        plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];

    }

    return plaintext;

}

+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key

{

     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,

                                          [key UTF8String], kCCKeySizeDES,

                                          (Byte *)[[key dataUsingEncoding:NSUTF8StringEncoding] bytes],

                                          [textData bytes], dataLength,

                                          buffer, 1024,

                                          &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {

        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];

        ciphertext = [Base64  encode:data];

    }

    return ciphertext;

}

@end

相关文章

网友评论

      本文标题:iOS实现DES加密代码片段

      本文链接:https://www.haomeiwen.com/subject/kyfrkftx.html