开发中遇到需要对密码加密之后,进行上传的问题。然后了解了一下可用,会用到的加密方式。
1.异或加密
设置字符串“t”为加密所需KEY,进行加密(根据需求不同进行替换)
2.DES加密
Base64codeFunc.h
Base64codeFunc.m 导入iOS自带加密库<CommonCrypto/CommonCryptor.h>
DES加密方法实现:
DES解密方法实现:
DES文本数据加密:
DES文本数据解密:
base64格式字符串转文本数据:
文本数据转换为base64格式字符串:
3.MD5加密
4.AES加密
+(NSData *)AES256ParmEncryptWithKey:(NSString *)key Encrypttext:(NSData *)text //加密
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [text length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[text bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
+ (NSData *)AES256ParmDecryptWithKey:(NSString *)key Decrypttext:(NSData *)text //解密
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [text length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[text bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}
+(NSString *) aes256_encrypt:(NSString *)key Encrypttext:(NSString *)text
{
const char *cstr = [text cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:text.length];
//对数据进行加密
NSData *result = [LanAES AES256ParmEncryptWithKey:key Encrypttext:data];
//转换为2进制字符串
if (result && result.length > 0) {
Byte *datas = (Byte*)[result bytes];
NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
for(int i = 0; i < result.length; i++){
[output appendFormat:@"%02x", datas[i]];
}
return output;
}
return nil;
}
+(NSString *) aes256_decrypt:(NSString *)key Decrypttext:(NSString *)text
{
//转换为2进制Data
NSMutableData *data = [NSMutableData dataWithCapacity:text.length / 2];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [text length] / 2; i++) {
byte_chars[0] = [text characterAtIndex:i*2];
byte_chars[1] = [text characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[data appendBytes:&whole_byte length:1];
}
//对数据进行解密
NSData* result = [LanAES AES256ParmDecryptWithKey:key Decrypttext:data];
if (result && result.length > 0) {
return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}
return nil;
}