iOS blowfish加密解密
阿新 • • 發佈:2017-12-01
調用 str ext smu led itl nserror data per
遇到一個需求,支付密碼提交到服務器時使用blowfish加密,網上資料很少,找到的代碼也跟在線加密出來的結果對不上,在線加密(用來確認加密結果是否有誤):
blowfish在線加密
Blowfish加密模式:ECB
填充模式:PKCS5Padding
輸出:base64
字符集:UTF8
最後在stackoverflow上找到了正解:
https://stackoverflow.com/questions/30860101/how-to-implement-blowfish-ecb-algorithm-pkcs5-padding-in-ios
是調用了原生API,自己稍微封裝了下,寫成NSString分類,分類.m文件中內容如下:
#import <CommonCrypto/CommonCryptor.h> //核心代碼 + (NSData *)doBlowfish:(NSData *)dataIn context:(CCOperation)kCCEncrypt_or_kCCDecrypt key:(NSData *)key options:(CCOptions)options iv:(NSData *)iv error:(NSError**)error { CCCryptorStatus ccStatus = kCCSuccess; size_t cryptBytes = 0; NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeBlowfish]; ccStatus = CCCrypt( kCCEncrypt_or_kCCDecrypt, kCCAlgorithmBlowfish, options, key.bytes, key.length, (iv)?nil:iv.bytes, dataIn.bytes, dataIn.length, dataOut.mutableBytes, dataOut.length, &cryptBytes); if (ccStatus == kCCSuccess) { dataOut.length = cryptBytes; } else { if (error) { *error = [NSError errorWithDomain:@"kEncryptionError" code:ccStatus userInfo:nil]; } dataOut = nil; } return dataOut; } //返回的是base64字符串-加密 - (NSString *)blowFishEncodingWithKey:(NSString *)pkey{ if (pkey.length<8 || pkey.length>56) { NSLog(@"key值的長度必須在[8,56]之間"); return nil; } NSError *error; NSData *key = [pkey dataUsingEncoding:NSUTF8StringEncoding]; NSString *stringOriginal = self; NSData *dataOriginal = [stringOriginal dataUsingEncoding:NSUTF8StringEncoding];; // NSLog(@"key %@", key); // NSLog(@"stringOriginal %@", stringOriginal); // NSLog(@"dataOriginal %@", dataOriginal); NSData *dataEncrypted = [NSString doBlowfish:dataOriginal context:kCCEncrypt key:key options:kCCOptionPKCS7Padding | kCCOptionECBMode iv:nil error:&error]; // NSLog(@"dataEncrypted %@", dataEncrypted); NSString *encryptedBase64String = [dataEncrypted base64EncodedStringWithOptions:0]; // NSLog(@"encryptedBase64String %@", encryptedBase64String); return encryptedBase64String; } //需要base64字符串調用,返回的是解密結果-解密 - (NSString *)blowFishDecodingWithKey:(NSString *)pkey{ if (pkey.length<8 || pkey.length>56) { NSLog(@"key值的長度必須在[8,56]之間"); return nil; } NSError *error; NSData *key = [pkey dataUsingEncoding:NSUTF8StringEncoding]; NSData *dataToDecrypt = [[NSData alloc] initWithBase64EncodedString:self options:0]; NSData *dataDecrypted = [NSString doBlowfish:dataToDecrypt context:kCCDecrypt key:key options:kCCOptionPKCS7Padding | kCCOptionECBMode iv:nil error:&error]; // NSLog(@"dataDecrypted %@", dataDecrypted); NSString *stringDecrypted = [[NSString alloc] initWithData:dataDecrypted encoding:NSUTF8StringEncoding]; // NSLog(@"stringDecrypted %@", stringDecrypted); return stringDecrypted; }
使用時只需:
NSString * base64 = [@"123456" blowFishEncodingWithKey:@"12345678"]; NSString * result = [base64 blowFishDecodingWithKey:@"12345678"]; NSLog(@"加密後的base64:%@ 解密結果:%@",base64,result);
相關參考資料:
簡書(我試過這個,加密出來的結果跟網站上的結果差一部分,暫時不知道原因)
iOS blowfish加密解密