RC4 加密算法 OC版

2017-12-12  本文已影响200人  文刂阿毛

对c RC4算法的封装

 *1.pSecret指向加密密钥
 2.SecretLen加密密钥长度(单位字节)
 3.pMessage指向需要加密的消息
 4.MessageLen需要加密的消息的长度(单位字节)
 5.pOut指向加密后的消息
 **/
void RC4(char *pSecret,int SecretLen,char *pMessage,int MessageLen,char *pOut )
{
    int i = 0;
    int j = 1;
    int temp = 0;
    int x = 0;
    int t = 0;
    int iY = 0;
    char iCY;
    int iS[256] = {0};
    char iK[256] = {0};
    for (i = 0; i < 256; i++)
                {
                    iS[i] = i;
                }
    
    for (i = 0; i < 256; i++)
                {
                    iK[i] = pSecret[(i % SecretLen)];
                }
    j = 0;
    for (i = 0; i < 256; i++)
                {
                    j = (j + iS[i]&0xff + iK[i]&0xff) % 256;
                    temp = iS[i];
                    iS[i] = iS[j];
                    iS[j] = temp;
                    
                }
    i = 0;
    j = 0;
    
    for (x = 0; x < MessageLen; x++)
                {
                    i = (i + 1) % 256;
                    j = (j + iS[i]&0xff) % 256;
                    temp = iS[i]&0xff;
                    iS[i] = iS[j];
                    iS[j] = temp;
                    t = (iS[i] + (iS[j]&0xff % 256)) % 256;
                    iY = iS[t]&0xff;
                    iCY = (char) iY;
                    pOut[x] = (char) (pMessage[x] ^ iCY);
                }
}

调用c的算法

/****RCE4加密  注: 所有data均属于16进制的字符串***/
+ (NSData *)RC4EncodeWithContentData:(NSData *)contentData keyData:(NSData *)keyData{
    char *a = (char *)[keyData bytes];
    int bytes = (int)[keyData length];
    char *b = (char *)[contentData bytes];
    int contentBytes = (int)[contentData length];
    char *resutl = (char *)malloc(1024 * sizeof(char));
    XDLog(@"加密之前 === %@", contentData);
    RC4(a, bytes, b, contentBytes, resutl);
    return [NSData dataWithBytes:resutl length: contentBytes];
}
上一篇下一篇

猜你喜欢

热点阅读