iOS Objective-C PBEWithMD5AndDES

2019-02-27  本文已影响0人  TreviD

参考来源:https://stackoverflow.com/questions/7152995/pbewithmd5anddes-encryption-in-ios

声明:这是我工(赶)作(鸭)需(子)要(上架),在接触oc不到半个月情况下完成的,有任何错误敬请谅解并欢迎指出


正文

废话不多说,直接上代码

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonCryptor.h>


+(NSData*) cryptPBEWithMD5AndDES:(CCOperation)op usingData:(NSData*)data withPassword:(NSString*)password andSalt:(NSData*)salt andIterating:(int)numIterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH];
    memset(md5, 0, CC_MD5_DIGEST_LENGTH);
    NSData* passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [passwordData bytes], [passwordData length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (int i=1; i<numIterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    size_t cryptoResultDataBufferSize = [data length] + kCCBlockSizeDES;
    unsigned char cryptoResultDataBuffer[cryptoResultDataBufferSize];
    size_t dataMoved = 0;

    unsigned char iv[kCCBlockSizeDES];
    memcpy(iv, md5 + (CC_MD5_DIGEST_LENGTH/2), sizeof(iv)); //iv is the second half of the MD5 from building the key

    CCCryptorStatus status =
        CCCrypt(op, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, (CC_MD5_DIGEST_LENGTH/2), iv, [data bytes], [data length],
            cryptoResultDataBuffer, cryptoResultDataBufferSize, &dataMoved);

    if(0 == status) {
        return [NSData dataWithBytes:cryptoResultDataBuffer length:dataMoved];
    } else {
        return NULL;
    }
}

直接stackoverflow上扒下来的代码。
Java部分代码可以参考 JAVA加解密14-对称加密算法-PBE算法 (来自 K1024)


简单测试

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *dataStr = @"hello, world";
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        NSData *salt = [@"salt" dataUsingEncoding:NSUTF8StringEncoding];
        // 加密
        NSData *encryptData = [test cryptPBEWithMD5AndDES:(kCCEncrypt) usingData:data withPassword:@"passwd" andSalt:salt andIterating:20];
        NSLog(@"%@", encryptData);
        
        //解密
        NSData *decryptData=[test cryptPBEWithMD5AndDES:(kCCDecrypt) usingData:encryptData withPassword:@"passwd" andSalt:salt andIterating:20];
        NSLog(@"%@", decryptData);
        
        NSLog(@"text:%@",[[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding]);
    }
    return 0;
}

输出

2019-02-27 20:49:43.566299+0800 OcDemo[5046:282195] <99ffe825 57031ab9 980bfb8e 33baefc1>
2019-02-27 20:49:43.566527+0800 OcDemo[5046:282195] <68656c6c 6f2c2077 6f726c64>
2019-02-27 20:49:43.566580+0800 OcDemo[5046:282195] text:hello, world
Program ended with exit code: 0

几点注意

上一篇 下一篇

猜你喜欢

热点阅读