信息安全:OpenSSL之RC4加密简单示例

RC4

     RC4是流密码算法,流算法以密钥作为种子产生密钥流,然后明文比特流和密钥流进行异或以实现加密.

     RC4加密算法密钥长度可变,没有填充的麻烦.

函数

     OpenSSL中RC4加密算法主要有两个函数,在openssl/rc4.h中找到.如下:

     void RC4_set_key(RC4_KEY *key,int len,const unsigned char *data);

     void RC4(RC4_KEY *key,size_t len,const unsigned char *indata,unsigned char *outdata);

示例

#include 
#include 
#include 
#include 
int main(int argc,char* argv[])
{
  RC4_KEY key;
  unsigned char *data="Hello,World!!";
  int length=strlen(data);
  RC4_set_key(&key,length,data);//设置密钥
  unsigned char *indata="This is plain text !!!!";
  int len=strlen(indata);
//  printf("len=%d\n",len);
  unsigned char *outdata;//分配密文空间
  outdata=(unsigned char *)malloc(sizeof(unsigned char)*(len+1));
  memset(outdata,0,len+1);//初始为0
  printf("\tindata=%s\n",indata);
  RC4(&key,strlen(indata),indata,outdata);//加密明文
  printf("\toutdata=%s\n",outdata);
  //printf("strlen(outdata)=%d\n",strlen(outdata));
  unsigned char *plain;//分配明文空间
  plain=(unsigned char *)malloc(sizeof(unsigned char)*(len+1));
  memset(plain,0,len+1);//初始化为0
  RC4_set_key(&key,length,data);//重新设置密钥
  RC4(&key,strlen(outdata),outdata,plain);//解密密文
  printf("\tplain=%s\n",plain);
//  printf("strlen(plain)=%d\n",strlen(plain)); return 0;}

运行结果

信息安全:OpenSSL之RC4加密简单示例_第1张图片




你可能感兴趣的:(信息安全)