码迷,mamicode.com
首页 > 移动开发 > 详细

iOS RC4加解密算法

时间:2016-01-12 18:09:06      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

-(NSString *)encrypt:(NSString *)string withKey:(NSString *)key{

    self.sBox = [[self 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 + [[self.sBox objectAtIndex:i]integerValue]) % SBOX_LENGTH;

        [self.sBox exchangeObjectAtIndex:i withObjectAtIndex:j];

        NSInteger index=([self.sBox[i] integerValue]+[self.sBox[j] integerValue]);

        NSInteger rand=([self.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:(NSString*)string withKey:(NSString*)key

{

    return [self encrypt: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 RC4加解密算法

标签:

原文地址:http://www.cnblogs.com/vfeng/p/5125146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!