本文介绍RC4加解密源码。
RC4(来自Rivest Cipher 4的缩写)是一种流加密算法,密钥长度可变。它加解密使用相同的密钥,因此也属于对称加密算法。RC4具有加解密速度快,算法简单等优点,在算力不高场合(MCU)也可以使用。
1.源码
1)头文件
头文件(rc4.h)主要包括RC4相关数据结构定义及外部函数声明。头文件定义如下。
#ifndef __RC4_H
#define __RC4_H#ifdef __cplusplusextern "C" {
#endif typedef struct _RC4_INFO
{uint8_t s[256];uint8_t t[256];
}RC4_INFO; extern void rc4_init(RC4_INFO *RC4Info, const uint8_t *key, uint32_t len);
extern void rc4_crypt(RC4_INFO *RC4Info, const uint8_t *input, uint8_t *output, uint32_t len); #ifdef __cplusplus
}
#endif#endif
注意:
a)加密过程,需要先调用rc4_init()函数,再调用rc4_crypt()函数,同样,解密过程,也需要先调用rc4_init()函数,再调用rc4_crypt()函数。加解密使用的是同一个密钥。
b)密钥长度可变,一般为8-256 bits。
2)源文件
源文件(rc4. c)主要包括RC4相关外部函数定义。源文件定义如下。
#include "rc4.h"static void swap(uint8_t *p1, uint8_t *p2);void rc4_init(RC4_INFO *RC4Info, const uint8_t *key, uint32_t len)
{uint32_t i = 0;uint32_t j = 0;if ((RC4Info == NULL) || (key == NULL) || (len == 0)){return ;}//Initial values of both vectorsfor (i = 0; i < 256; i++){RC4Info->s[i] = (uint8_t)i;RC4Info->t[i] = key[i % len];}//Initial permutationfor (i = 0; i < 256; i++){j = (j + RC4Info->s[i] + RC4Info->t[i]) % 256;swap(&RC4Info->s[i], &RC4Info->s[j]);}
}void rc4_crypt(RC4_INFO *RC4Info, const uint8_t *input, uint8_t *output, uint32_t len)
{uint32_t i = 0;uint8_t t1 = 0;uint8_t t2 = 0;uint8_t val = 0;uint8_t out = 0;if ((RC4Info == NULL) || (input == NULL) || (output == NULL) || (len == 0)){return ;}//process one byte at a timefor (i = 0; i < len; i++){t1 = (t1 + 1) % 256;t2 = (t2 + RC4Info->s[t1]) % 256;swap(&RC4Info->s[t1], &RC4Info->s[t2]);val = (RC4Info->s[t1] + RC4Info->s[t2]) % 256;out = *input++ ^ RC4Info->s[val];*output++ = out;}
}static void swap(uint8_t *p1, uint8_t *p2)
{uint8_t t = 0;if ((p1 == NULL) || (p2 == NULL)){return ;}t = *p1;*p1 = *p2;*p2 = t;
}
2.测试
这里主要测试加解密过程。
int main()
{RC4_INFO RC4Info;uint8_t key[] = {0x03, 0x01, 0x02, 0x03, 0x04, 0x08, 0x09, 0x1a};uint8_t data[] = {0x03, 0x04, 0x08, 0x09, 0xa5, 0x5a, 0x33, 0x22, 0x88};uint8_t encrypt[256] = {0};uint8_t decrypt[256] = {0};uint32_t i = 0;printf("raw data:\r\n");for (i = 0; i < sizeof(data) / sizeof(data[0]); i++){printf("0x%x ", data[i]);}printf("\r\n");//encryptrc4_init(&RC4Info, key, sizeof(key) / sizeof(key[0]));rc4_crypt(&RC4Info, data, encrypt, sizeof(data) / sizeof(data[0]));printf("encrypt data:\r\n");for (i = 0; i < sizeof(data) / sizeof(data[0]); i++){printf("0x%x ", encrypt[i]);}printf("\r\n");//decryptrc4_init(&RC4Info, key, sizeof(key) / sizeof(key[0]));rc4_crypt(&RC4Info, encrypt, decrypt, sizeof(data) / sizeof(data[0]));printf("decrypt data:\r\n");for (i = 0; i < sizeof(data) / sizeof(data[0]); i++){printf("0x%x ", decrypt[i]);}printf("\r\n");return 0;
}
输出结果:
总结,本文介绍了RC4加解密源码。