iOS实现几种会用到的加密方式

这些加密方法都是封装好的,只需要.h实现一下调用即可

1. MD5加密

传入需要加密的字符串
/**
 MD5加密方法
 */
+ (NSString *) md5:(NSString *) input {
const char *cStr = [input UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call

NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    [output appendFormat:@"%02x", digest[i]];

return  output;
}

2.Sha1加密

这个相对来说用的不多,不过还是有的
/**
 sha1加密方式
 */
+ (NSString *) sha1:(NSString *)input{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];

uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (unsigned int)data.length, digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

for(int i=0; i

3.Base64

64相对来说就比较常用了
@interface Base64()

+(int)char2Int:(char)c;

@end

@implementation Base64

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

//加密
+(NSString *)encode:(NSData *)data{
if (data.length == 0)
    return nil;

char *characters = malloc(data.length * 3 / 2);

if (characters == NULL)
    return nil;

NSInteger end = data.length - 3;
int index = 0;
int charCount = 0;
int n = 0;

while (index <= end) {
    int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) << 16)
    | (((int)(((char *)[data bytes])[index + 1]) & 0x0ff) << 8)
    | ((int)(((char *)[data bytes])[index + 2]) & 0x0ff);
    
    characters[charCount++] = encodingTable[(d >> 18) & 63];
    characters[charCount++] = encodingTable[(d >> 12) & 63];
    characters[charCount++] = encodingTable[(d >> 6) & 63];
    characters[charCount++] = encodingTable[d & 63];
    
    index += 3;
    
    if(n++ >= 14)
    {
        n = 0;
        characters[charCount++] = ' ';
    }
}

if(index == data.length - 2)
{
    int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) << 16)
    | (((int)(((char *)[data bytes])[index + 1]) & 255) << 8);
    characters[charCount++] = encodingTable[(d >> 18) & 63];
    characters[charCount++] = encodingTable[(d >> 12) & 63];
    characters[charCount++] = encodingTable[(d >> 6) & 63];
    characters[charCount++] = '=';
}
else if(index == data.length - 1)
{
    int d = ((int)(((char *)[data bytes])[index]) & 0x0ff) << 16;
    characters[charCount++] = encodingTable[(d >> 18) & 63];
    characters[charCount++] = encodingTable[(d >> 12) & 63];
    characters[charCount++] = '=';
    characters[charCount++] = '=';
}
NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
return rtnStr;

}
//解密
+(NSData *)decode:(NSString *)data{
if(data == nil || data.length <= 0) {
    return nil;
}
NSMutableData *rtnData = [[NSMutableData alloc]init];
NSInteger slen = data.length;
int index = 0;
while (true) {
    while (index < slen && [data characterAtIndex:index] <= ' ') {
        index++;
    }
    if (index >= slen || index  + 3 >= slen) {
        break;
    }
    
    int byte = ([self char2Int:[data characterAtIndex:index]] << 18) + ([self char2Int:[data characterAtIndex:index + 1]] << 12) + ([self char2Int:[data characterAtIndex:index + 2]] << 6) + [self char2Int:[data characterAtIndex:index + 3]];
    Byte temp1 = (byte >> 16) & 255;
    [rtnData appendBytes:&temp1 length:1];
    if([data characterAtIndex:index + 2] == '=') {
        break;
    }
    Byte temp2 = (byte >> 8) & 255;
    [rtnData appendBytes:&temp2 length:1];
    if([data characterAtIndex:index + 3] == '=') {
        break;
    }
    Byte temp3 = byte & 255;
    [rtnData appendBytes:&temp3 length:1];
    index += 4;
    
}
return rtnData;
}


+(int)char2Int:(char)c{
if (c >= 'A' && c <= 'Z') {
    return c - 65;
} else if (c >= 'a' && c <= 'z') {
    return c - 97 + 26;
} else if (c >= '0' && c <= '9') {
    return c - 48 + 26 + 26;
} else {
    switch(c) {
        case '+':
            return 62;
        case '/':
            return 63;
        case '=':
            return 0;
        default:
            return -1;
    }
}
}

@end

4.DES加密

这个需要传入一个加密的key
//加密
+(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key{
NSString *plaintext = nil;

NSInteger textLenght = cipherText.length;

//    NSData *cipherdata = [Base64 decode:cipherText];
 NSData *cipherdata = [GTMBase64 decodeString:cipherText];

//    const Byte iv[] = {1,2,3,4,5,6,7,8};

unsigned char buffer[textLenght];//原来为1024后来改为3072,由于有时数据量太大
memset(buffer, 0, sizeof(char));
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding,//| kCCOptionECBMode
                                      [key UTF8String], kCCKeySizeDES,
                                      (Byte *)[[key dataUsingEncoding:NSUTF8StringEncoding] bytes],
                                      [cipherdata bytes], [cipherdata length],
                                      buffer, textLenght,//原来为1024后来改为3072,由于有时数据量太大
                                      &numBytesDecrypted);
if(cryptStatus == kCCSuccess) {
    NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
    plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
}
return plaintext;
}

//解密
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key{

//    const Byte iv[] = {1,2,3,4,5,6,7,8};
NSString *ciphertext = nil;
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [textData length];
unsigned char buffer[3072];//原来为1024后来改为3072,由于有时数据量太大
memset(buffer, 0, sizeof(char));
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding, //| kCCOptionECBMode
                                      [key UTF8String], kCCKeySizeDES,
                                      (Byte *)[[key dataUsingEncoding:NSUTF8StringEncoding] bytes],
                                      [textData bytes], dataLength,
                                      buffer, 3072,//原来为1024后来改为3072,由于有时数据量太大
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
    ciphertext = [GTMBase64 encodeBase64Data:data];
}
//
NSMutableString *resultStr = [NSMutableString stringWithString:ciphertext];
if (resultStr.length > 77) {
    [resultStr insertString:@"\n" atIndex:76];
}
NSString *returnStr = [NSString stringWithFormat:@"%@\n", resultStr];
return returnStr;
}
DES加密需要导入GTMBase64支持,自行搜索下载即可

5.RC4加密

传入key进行加密解密
//加密
+(NSString *)encrypt_Rc4:(NSString *)string withKey:(NSString *)key{

//    NSArray *r_key = [NSArray array];
NSMutableArray *r_sBox = [NSMutableArray array];

r_sBox = [[CiphertextManage frameSBox:key] mutableCopy];
unichar code[string.length];

int i = 0;
int j = 0;
for (int n = 0; n < string.length; n++) {
    i = (i + 1) % SBOX_LENGTH;
    j = (j + [[r_sBox objectAtIndex:i]integerValue]) % SBOX_LENGTH;
    [r_sBox exchangeObjectAtIndex:i withObjectAtIndex:j];
    
    NSInteger index=([r_sBox[i] integerValue]+[r_sBox[j] integerValue]);
    
    NSInteger rand=([r_sBox[(index%SBOX_LENGTH)] integerValue]);
    
    code[n]=(rand  ^  (int)[string characterAtIndex:n]);
}
const unichar* buffer;
buffer = code;

return  [NSString stringWithCharacters:buffer length:string.length];
}

//解密
+ (NSString*)decrypt_Rc4:(NSString*)string withKey:(NSString*)key{
   return [CiphertextManage encrypt_Rc4:string withKey:key];
}


+(NSArray *)frameSBox:(NSString *)keyValue{

NSMutableArray *sBox = [[NSMutableArray alloc] initWithCapacity:SBOX_LENGTH];

int j = 0;

for (int i = 0; i < SBOX_LENGTH; i++) {
    [sBox addObject:[NSNumber numberWithInteger:i]];
}

for (int i = 0; i < SBOX_LENGTH; i++) {
    j = (j + [sBox[i] integerValue] + [keyValue characterAtIndex:(i % keyValue.length)]) % SBOX_LENGTH;
    [sBox exchangeObjectAtIndex:i withObjectAtIndex:j];
}

return [NSArray arrayWithArray:sBox];
}

以上就是可能会遇到的几种加密方式,如有问题欢迎咨询。

你可能感兴趣的:(iOS实现几种会用到的加密方式)