美文网首页
OPENSSL:RC4用法举例

OPENSSL:RC4用法举例

作者: 客昂康 | 来源:发表于2021-07-15 20:48 被阅读0次

RC4是密钥流加密算法,明文长度和密文长度相同,加密过程和解密过程也相同。RC4加解密 是另一个RC4的实现,里面有RC4加密算法更详细的内容。

// 所需头文件
#include <openssl/rc4.h>

// 用密钥对 RC4_KEY 结构体初始化
void RC4_set_key(RC4_KEY *rc4Key, int keySize, const unsigned char *keyData);

// 加密或解密
void RC4(RC4_KEY *rc4Key, size_t dataSize, const unsigned char *indata, unsigned char *outdata);

代码举例

/*
    openssl-devel 的 RC4 用法举例
    gcc RC4.c -lcrypto -Wall
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rc4.h>

static void hex(unsigned char *buffer, int len){
    int i;
    for(i=0; i<len; i++){
        printf("%02x", buffer[i]);
    }
    putchar('\n');
}

int main(int argc, char* argv[]){
    if(argc < 3){
        printf("%s key str\n", argv[0]);
        return -1;
    }
    
    char *key = argv[1];
    char *str = argv[2];
    int length = strlen(str);
    unsigned char *buffer1 = malloc(length+8);
    unsigned char *buffer2 = malloc(length+8);
    if((buffer1 == NULL) || (buffer2 == NULL)){
        if(buffer1) free(buffer1);
        if(buffer2) free(buffer2);
        return -2;
    }
    
    printf("RC4Key : %s\n", key);
    printf("SrcData: %s\n", str);
    
    // RC4 加密
    RC4_KEY rc4Key1;
    RC4_set_key(&rc4Key1, strlen(key), (unsigned char*)key);
    RC4(&rc4Key1, length, (unsigned char*)str, buffer1);
    printf("Encrypt: ");
    hex(buffer1, length);
    
    // RC4 解密
    RC4_KEY rc4Key2;
    RC4_set_key(&rc4Key2, strlen(key), (unsigned char*)key);
    RC4(&rc4Key2, length, buffer1, buffer2);
    buffer2[length] = 0;
    printf("Decrypt: %s\n", (char*)buffer2);
    
    free(buffer1);
    free(buffer2);
    return 0;
}

运行效果

wxk@ThinkPad:~/work/tmp$ 
wxk@ThinkPad:~/work/tmp$ gcc RC4.c -lcrypto
wxk@ThinkPad:~/work/tmp$ 
wxk@ThinkPad:~/work/tmp$ ./a.out 123456 helloEveryone
RC4Key : 123456
SrcData: helloEveryone
Encrypt: 689d120b4b7663f90d4e4dd89c
Decrypt: helloEveryone
wxk@ThinkPad:~/work/tmp$ 
wxk@ThinkPad:~/work/tmp$

相关文章

网友评论

      本文标题:OPENSSL:RC4用法举例

      本文链接:https://www.haomeiwen.com/subject/zvkmpltx.html