CommonCrypto加密

如果你也碰巧遇到后台选择的加密方式是DES的ECB模式,下面3种方式仅供参考;

/*使用CCCrypt(CCOperation op, CCAlgorithm alg, CCOptions options,
         const void *key, size_t keyLength, const void *iv,
         const void *dataIn, size_t dataInLength, void *dataOut,
         size_t dataOutAvailable, size_t *dataOutMoved);
注意这里的options,如果使用的CBC模式加密直接写kCCOptionPKCS7Padding;
*/

+(NSString *) encryptUseDES:(NSString *)clearText salt:(NSString *)key 
{
    NSData *data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
 
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          nil,
                                          [data bytes],
                                          [data length],
                                          buffer,
                                          1024,
                                          &numBytesEncrypted);
 
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData *dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        plainText = [DESUtil getHexStrFrom:dataTemp];
        return plainText;
    }else{
        NSLog(@"DES加密失败");
    }
    return plainText;
}

/*
CCCryptorStatus CCCryptorCreateWithMode(
    CCOperation     op,             // kCCEncrypt, kCCDecrypt 
    CCMode          mode,
    CCAlgorithm     alg,
    CCPadding       padding,
    const void      *iv,            // optional initialization vector 
    const void      *key,           // raw key material 
    size_t          keyLength,
    const void      *tweak,         // raw tweak material 
    size_t          tweakLength,
    int             numRounds,      // 0 == default 
    CCModeOptions   options,
    CCCryptorRef    *cryptorRef)    // RETURNED 
API_AVAILABLE(macos(10.7), ios(5.0));

CCCryptorGetOutputLength
CCCryptorUpdate
CCCryptorFinal
CCCryptorRelease
*/
+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
{
    NSString *ciphertext = nil;
    NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSUInteger dataLength = [textData length];
    CCCryptorRef cryptor = nil;
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    
    CCCryptorStatus cryptStatus = CCCryptorCreateWithMode(kCCEncrypt,
                                                          kCCModeECB,
                                                          kCCAlgorithmDES,
                                                          kCCOptionPKCS7Padding ,
                                                          NULL,
                                                          keyData.bytes,
                                                          keyData.length,
                                                          NULL,
                                                          0,
                                                          0,
                                                          0,
                                                          &cryptor);
    size_t bufsize = CCCryptorGetOutputLength(cryptor, dataLength, YES);
    size_t bufused = 0;
    size_t bytesTotal = 0;
    void * buf = malloc( bufsize );
    cryptStatus = CCCryptorUpdate(cryptor, textData.bytes, textData.length, buf, bufsize, &bufused);
    bytesTotal += bufused;
    cryptStatus = CCCryptorFinal(cryptor, buf + bufused, bufsize - bufused, &bufused);
    bytesTotal += bufused;
    if (cryptStatus == kCCSuccess) {
        NSLog(@"DES加密成功");
        NSData *data = [NSData dataWithBytes:buf length:bytesTotal];
        CCCryptorRelease(cryptor);
        NSLog(@"data:%@",data);
        ciphertext = [DESUtil getHexStrFrom:data];
    }else{
        NSLog(@"DES加密失败");
    }
    return ciphertext;
}

/*
借助第三方库 IDZSwiftCommonCrypto
这里的options参数同方法一,看选择什么模式
*/
func encrypt(text:String,salt:String) -> String? {
        let key = Array(salt.utf8)
        let bytes = Array(text.utf8)
        let cryptor = Cryptor(operation: .encrypt, algorithm: .des, options: [.ECBMode,.PKCS7Padding], key: key, iv:[UInt8]())
        if let encrypted = cryptor.update(byteArray: bytes)?.final() {
            let data = Data(encrypted)
            return DESUtil.getHexStr(from: data)
        }
        return nil
   }

//最后附赠一个data转16进制的方法;网上看到的几个都多少有点问题;
//Objective_C
+(NSString *) getHexStrFrom:(NSData*)data
{
    NSMutableString *str = [NSMutableString string];
    [data enumerateByteRangesUsingBlock:^(const void * _Nonnull bytes, NSRange byteRange, BOOL * _Nonnull stop) {
        for (NSInteger i=0;i String {
        var str = ""
        data.enumerateBytes { (bytes, index, stop) in
            let dataBytes = bytes
            for index in 0..

你可能感兴趣的:(CommonCrypto加密)