一个常见的加密算法 加解密是一个东西 魔改点一般都在打乱S盒 自定义S盒 还有一些乱七八糟的异或左移右移

加密原理

RC4 是一种流加密(Stream Cipher)算法。它的特点是简单、高效,通过一个密钥生成一个伪随机流,然后将这个随机流与明文进行异或(XOR)运算

RC4分为两个地方加密

  • KSA (Key-Scheduling Algorithm) 密钥调度算法: 利用你提供的密钥(Key)来打乱一个 256 字节的数组(称为 S 盒或状态向量)。最初这个数组是 $0, 1, 2, ..., 255$。
  • PRGA (Pseudo-Random Generation Algorithm) 伪随机子密码生成算法: 根据打乱后的 S 盒,生成一个不断的随机字节流。这个字节流会和明文逐字节进行 XOR 运算。

然后就没有了 看到下方加密实现就知道为什么是流加密了

代码实现

由于RC4的加密就只是一个异或加密 所以我们只需要异或回去就可以 也就是调用他自己给他自己解密
def rc4_init(key):
    """KSA 阶段:初始化 S 盒"""
    s = list(range(256))
    j = 0
    key_len = len(key)
    for i in range(256):
        # 根据密钥打乱 S 盒
        j = (j + s[i] + key[i % key_len]) % 256
        s[i], s[j] = s[j], s[i]  # 交换
    return s

def rc4_crypt(data, key):
    """PRGA 阶段:生成随机流并加解密"""
    # 转换为字节处理
    data = data.encode('utf-8') if isinstance(data, str) else data
    key = key.encode('utf-8') if isinstance(key, str) else key
    
    s = rc4_init(key)
    res = []
    i = j = 0
    
    for byte in data:
        i = (i + 1) % 256
        j = (j + s[i]) % 256
        s[i], s[j] = s[j], s[i]  # 再次交换
        
        # 生成伪随机字节 k
        t = (s[i] + s[j]) % 256
        k = s[t]
        
        # 异或运算:明文 ^ k = 密文;密文 ^ k = 明文
        res.append(byte ^ k)
        
    return bytes(res)

# 测试
key = "my-secret-key"
plain_text = "Hello Gemini!"

cipher_data = rc4_crypt(plain_text, key)
print(f"加密后 (十六进制): {cipher_data.hex()}")

decrypted_data = rc4_crypt(cipher_data, key)
print(f"解密后: {decrypted_data.decode('utf-8')}")

C语言实现

#include <stdio.h>
#include <string.h>

// 初始化 S 盒 (KSA)
void rc4_init(unsigned char *s, unsigned char *key, int key_len) {
    for (int i = 0; i < 256; i++)
        s[i] = i;
    
    int j = 0;
    for (int i = 0; i < 256; i++) {
        j = (j + s[i] + key[i % key_len]) % 256;
        unsigned char temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }
}

// 加解密逻辑 (PRGA + XOR)
void rc4_crypt(unsigned char *s, unsigned char *data, int data_len) {
    int i = 0, j = 0;
    for (int n = 0; n < data_len; n++) {
        i = (i + 1) % 256;
        j = (j + s[i]) % 256;
        
        unsigned char temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        
        unsigned char k = s[(s[i] + s[j]) % 256];
        data[n] ^= k; // 异或运算
    }
}

int main() {
    unsigned char s[256];
    unsigned char key[] = "password123";
    unsigned char data[] = "Secret Message";
    int data_len = strlen((char*)data);

    // 1. 加密
    rc4_init(s, key, strlen((char*)key));
    rc4_crypt(s, data, data_len);
    
    printf("加密后的数据: ");
    for(int i=0; i<data_len; i++) printf("%02X ", data[i]);
    printf("\n");

    // 2. 解密(RC4 对称性:再执行一次同样的逻辑即为解密)
    rc4_init(s, key, strlen((char*)key)); // 重新初始化 S 盒
    rc4_crypt(s, data, data_len);
    printf("解密后的数据: %s\n", data);

    return 0;
}