//
//  DES.m
//  zhuxun
//
//  Created by Justine on 16/6/23.
//
//

#import "DES.h"
#import "MD5.h"
#define skey         @"abcdef01"
@implementation DES
const Byte iv[8] = {0xEF, 0x24, 0x36, 0x08, 0x70, 0xBB,  0x8D, 0xFF};
//加密方法-default key
+(NSString *) encryptUseDES:(NSString *)plainText
{
    
    NSString *ciphertext = nil;
    NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [textData length];
    NSUInteger bufferLength = dataLength;
    
    //如果数据长度是8的倍数则直接声明对应长度的缓冲区空间,反之填充
    NSUInteger remainder = dataLength%8;
    if(remainder != 0){
        //假设长度为65 为8余1 则填充8-1(余数)7 65+7 = 72
        bufferLength = bufferLength+(kCCBlockSizeDES-remainder);
    }
    bufferLength = bufferLength+1024;
    unsigned char buffer[bufferLength];
    //unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          //kCCOptionECBMode,
                                          kCCOptionPKCS7Padding,
                                          
                                          [skey UTF8String], kCCKeySizeDES,
                                          iv,
                                          [textData bytes], dataLength,
                                          buffer, bufferLength,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        //NSString *utf8str = [[NSString alloc] initWithData:data encoding:kCFStringEncodingUTF8];
        //NSLog(@"加密成功 未base64 utf8 值 %@",utf8str);
        ciphertext = [GTMBase64 stringByEncodingData:data];
        NSLog(@"加密成功base64 后:     %@",ciphertext);
    }
    
    return ciphertext;
}

//解密方法
//Des解密-default key
+(NSString *)decryptUseDES:(NSString *)cipherText
{
    NSString *plaintext = nil;
    NSData *cipherdata = [GTMBase64 decodeString:cipherText];
    NSUInteger bufferLength = [cipherdata length];
    NSUInteger remainder = bufferLength%8;
    if(remainder != 0){
        //假设长度为65 为8余1 则填充8-1(余数)7 65+7 = 72
        bufferLength = bufferLength+(kCCBlockSizeDES-remainder);
    }
    bufferLength = bufferLength+1024;
    unsigned char buffer[bufferLength];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,              //  加密/解密
                                          kCCAlgorithmDES,         //  加密根据哪个标准（des，3des，aes。。。。）
                                          //kCCOptionECBMode,
                                          kCCOptionPKCS7Padding,   //  选项分组密码算法
                                          
                                          [skey UTF8String],        //  密钥
                                          kCCKeySizeDES,           //  DES 密钥的大小
                                          iv,                      //  可选的初始矢量
                                          [cipherdata bytes],      //  数据的存储单元
                                          [cipherdata length],     // 数据的大小
                                          buffer, bufferLength,
                                          &numBytesDecrypted);
    if(cryptStatus == kCCSuccess)
    {
        NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
        NSLog(@"解密成功:     %@",plaintext);
        
    }
    return plaintext;
}
#warning 为什么有些情况无法加密----2016-08-01 18:09 MD5:2A559C9E887AE2F9D6C9C4A65520F0F0,KEY:5520F0F0,CONTENT:(null),原content:Skskndnd
//加密方法
+(NSString *) encryptUseDES:(NSString *)plainText withRandomKey:(NSString *)randomKey
{
    NSString *ciphertext = nil;
    NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [textData length];
    NSUInteger bufferLength = dataLength;
    NSUInteger remainder = bufferLength%8;
    if(remainder != 0){
        //假设长度为65 为8余1 则填充8-1(余数)7 65+7 = 72
        bufferLength = bufferLength+(kCCBlockSizeDES-remainder);
    }
    bufferLength = bufferLength+1024;
    unsigned char buffer[bufferLength];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          //kCCOptionECBMode,
                                          kCCOptionPKCS7Padding,
                                          
                                          [randomKey UTF8String], kCCKeySizeDES,
                                          iv,
                                          [textData bytes], dataLength,
                                          buffer, bufferLength,
                                          &numBytesEncrypted);
    //kCCBufferTooSmall
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        //NSString *utf8str = [[NSString alloc] initWithData:data encoding:kCFStringEncodingUTF8];
        //NSLog(@"加密成功 未base64 utf8 值 %@",utf8str);
        ciphertext = [GTMBase64 stringByEncodingData:data];
        NSLog(@"加密成功base64 后:     %@",ciphertext);
    }else{
    #warning 为什么有些情况无法加密----2016-08-01 18:09 MD5:2A559C9E887AE2F9D6C9C4A65520F0F0,KEY:5520F0F0,CONTENT:(null),原content:Skskndnd
        NSLog(@"加密失败");
    }
    
    return ciphertext;
}
//解密方法
+(NSString *)decryptUseDES:(NSString *)cipherText withRandomKey:(NSString *)randomKey
{
    NSString *plaintext = nil;
    NSData *cipherdata = [GTMBase64 decodeString:cipherText];
    NSUInteger bufferLength = [cipherdata length];
    NSUInteger remainder = bufferLength%8;
    if(remainder != 0){
        //假设长度为65 为8余1 则填充8-1(余数)7 65+7 = 72
        bufferLength = bufferLength+(kCCBlockSizeDES-remainder);
    }
    bufferLength = bufferLength+1024;
    unsigned char buffer[bufferLength];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,              //  加密/解密
                                          kCCAlgorithmDES,         //  加密根据哪个标准（des，3des，aes。。。。）
                                          //kCCOptionECBMode,
                                          kCCOptionPKCS7Padding,   //  选项分组密码算法
                                          
                                          [randomKey UTF8String],        //  密钥
                                          kCCKeySizeDES,           //  DES 密钥的大小
                                          iv,                      //  可选的初始矢量
                                          [cipherdata bytes],      //  数据的存储单元
                                          [cipherdata length],     // 数据的大小
                                          buffer, bufferLength,
                                          &numBytesDecrypted);
    if(cryptStatus == kCCSuccess)
    {
        NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
        NSLog(@"解密成功:     %@",plaintext);
        
    }
    return plaintext;
}

+ (NSString *)returnKeyValue
{
    //    double ts = [[NSDate date] timeIntervalSince1970]*1000;//毫秒
    //    NSString *sts = [NSString stringWithFormat:@"%f",ts];
    //    NSString *sktsmd5 =[MD5 getMD5:[NSString stringWithFormat:@"%@%f",skey,ts]];
    //    // string = "ak==test110" + step1md5 +
    //    NSDictionary *dict = @{@"ak":@"ak==test110",
    //                           @"md5": sktsmd5,
    //                           @"ts": sts
    //                           };
    //    NSString *sdict = nil;
    //    NSError *error;
    //    NSData *sdata = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    //    if(!sdata){
    //        NSLog(@"Got an error: %@", error);
    //        assert(error);
    //    }else{
    //      sdict = [[NSString alloc] initWithData:sdata encoding:NSUTF8StringEncoding];
    //
    //    }
    //
    //    NSString *base = [DES encryptUseDES:sdict];//加密解密方法内含结果NSlog
    //    NSLog(@"######\n%@",base);
    //    base = [NSString stringWithFormat:@"Basic %@",base];
    //NSString *Authorization: Basic xxxxxxxxxx
    double ts = [[NSDate date] timeIntervalSince1970]*1000;//毫秒
    NSString *sts = [NSString stringWithFormat:@"%f",ts];
    NSString *sktsmd5 =[MD5 getMD5:[NSString stringWithFormat:@"%@%f",skey,ts]];
    // string = "ak==test110" + step1md5 +
    NSDictionary *dict = @{@"ak":@"ak==test110",
                           @"md5": sktsmd5,
                           @"ts": sts,
                           };
    NSString *sdict = nil;
    NSError *error;
    NSData *sdata = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if(!sdata){
        NSLog(@"Got an error: %@", error);
        assert(error);
    }else{
        sdict = [[NSString alloc] initWithData:sdata encoding:NSUTF8StringEncoding];
        
    }
    
    NSString *base = [DES encryptUseDES:sdict];//加密解密方法内含结果NSlog
    
    return base;
}

+ (NSString *)cloudStorageReturnKeyValue
{
    NSString *basicAuthStr = [NSString stringWithFormat:@"%@:%@",Login_Name,@"Ab123456"];
    NSData * basicAuthData = [basicAuthStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString * basicAuthValue = [NSString stringWithFormat:@"Basic %@",[basicAuthData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    return basicAuthValue;
}


+ (NSString *)cloudStorageDownUpReturnKeyValue
{
    NSString *basicAuthStr = [NSString stringWithFormat:@"%@:%@",@"4f860649600a47508379639dba82327d",@"f3b58f6b935b4acd9d9e795864ad10d4"];
    NSData * basicAuthData = [basicAuthStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString * basicAuthValue = [NSString stringWithFormat:@"Basic %@",[basicAuthData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    
 
    return basicAuthValue;
}
@end
