前言
你有没有想过:你输入的密码、发送的消息、存储的文件------是怎么变成一堆乱码,让黑客看不懂的?
加密是信息安全的基石。今天我们从零实现两种经典加密算法:
· AES(对称加密):同一个密钥加密和解密,速度快
· RSA(非对称加密):公钥加密、私钥解密,安全分发密钥
一、AES加密原理
- AES核心操作
AES是分组加密算法,每次处理16字节(128位):
```
┌─────────────────────────────────────────────────────────────┐
│ AES加密流程 │
│ 明文(16B) → AddRoundKey → SubBytes → ShiftRows → MixCols │
│ ↓ │
│ 重复9/11/13轮(取决于密钥长度) │
│ ↓ │
│ 密文(16B) │
└─────────────────────────────────────────────────────────────┘
```
操作 说明
SubBytes 字节替换(S盒查表)
ShiftRows 行移位
MixColumns 列混合(GF(2⁸)乘法)
AddRoundKey 与轮密钥异或
二、完整代码实现
- AES核心操作
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <math.h>
// AES S盒
static const uint8_t sbox256 = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
// 逆S盒
static const uint8_t inv_sbox256 = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0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 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
// 轮常数
static const uint8_t rcon10 = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};
// SubBytes
void sub_bytes(uint8_t *state) {
for (int i = 0; i < 16; i++) {
statei = sboxstate\[i];
}
}
void inv_sub_bytes(uint8_t *state) {
for (int i = 0; i < 16; i++) {
statei = inv_sboxstate\[i];
}
}
// ShiftRows
void shift_rows(uint8_t *state) {
uint8_t tmp16;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
tmpi \* 4 + j = statei \* 4 + ((j + i) % 4);
}
}
memcpy(state, tmp, 16);
}
void inv_shift_rows(uint8_t *state) {
uint8_t tmp16;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
tmpi \* 4 + j = statei \* 4 + ((j - i + 4) % 4);
}
}
memcpy(state, tmp, 16);
}
// GF(2^8)乘法
uint8_t gf_mul(uint8_t a, uint8_t b) {
uint8_t result = 0;
for (int i = 0; i < 8; i++) {
if (b & 1) result ^= a;
b >>= 1;
a <<= 1;
if (a & 0x100) a ^= 0x1b;
}
return result;
}
// MixColumns
void mix_columns(uint8_t *state) {
uint8_t tmp16;
for (int i = 0; i < 4; i++) {
int idx = i * 4;
tmpidx = gf_mul(stateidx, 2) ^ gf_mul(stateidx+1, 3) ^ stateidx+2 ^ stateidx+3;
tmpidx+1 = stateidx ^ gf_mul(stateidx+1, 2) ^ gf_mul(stateidx+2, 3) ^ stateidx+3;
tmpidx+2 = stateidx ^ stateidx+1 ^ gf_mul(stateidx+2, 2) ^ gf_mul(stateidx+3, 3);
tmpidx+3 = gf_mul(stateidx, 3) ^ stateidx+1 ^ stateidx+2 ^ gf_mul(stateidx+3, 2);
}
memcpy(state, tmp, 16);
}
void inv_mix_columns(uint8_t *state) {
uint8_t tmp16;
for (int i = 0; i < 4; i++) {
int idx = i * 4;
tmpidx = gf_mul(stateidx, 0x0e) ^ gf_mul(stateidx+1, 0x0b) ^ gf_mul(stateidx+2, 0x0d) ^ gf_mul(stateidx+3, 0x09);
tmpidx+1 = gf_mul(stateidx, 0x09) ^ gf_mul(stateidx+1, 0x0e) ^ gf_mul(stateidx+2, 0x0b) ^ gf_mul(stateidx+3, 0x0d);
tmpidx+2 = gf_mul(stateidx, 0x0d) ^ gf_mul(stateidx+1, 0x09) ^ gf_mul(stateidx+2, 0x0e) ^ gf_mul(stateidx+3, 0x0b);
tmpidx+3 = gf_mul(stateidx, 0x0b) ^ gf_mul(stateidx+1, 0x0d) ^ gf_mul(stateidx+2, 0x09) ^ gf_mul(stateidx+3, 0x0e);
}
memcpy(state, tmp, 16);
}
// AddRoundKey
void add_round_key(uint8_t *state, uint8_t *key) {
for (int i = 0; i < 16; i++) {
statei ^= keyi;
}
}
```
- AES密钥扩展
```c
// 密钥扩展
void key_expansion(uint8_t *key, uint8_t *round_keys, int rounds) {
int key_len = 16; // AES-128
int total_words = (rounds + 1) * 4;
uint32_t *w = (uint32_t*)round_keys;
// 前4个字是原始密钥
for (int i = 0; i < 4; i++) {
wi = (keyi\*4 << 24) | (keyi\*4+1 << 16) |
(keyi\*4+2 << 8) | keyi\*4+3;
}
for (int i = 4; i < total_words; i++) {
uint32_t temp = wi-1;
if (i % 4 == 0) {
// RotWord + SubWord + Rcon
temp = (temp << 8) | (temp >> 24);
temp = (sboxtemp \>\> 24 << 24) | (sbox(temp \>\> 16) \& 0xff << 16) |
(sbox(temp \>\> 8) \& 0xff << 8) | sboxtemp \& 0xff;
temp ^= (rconi/4 - 1 << 24);
}
wi = wi-4 ^ temp;
}
}
```
- AES加密/解密
```c
// AES加密(AES-128)
void aes_encrypt(uint8_t *input, uint8_t *output, uint8_t *key) {
uint8_t state16;
memcpy(state, input, 16);
int rounds = 10;
uint8_t round_keys176;
key_expansion(key, round_keys, rounds);
// 初始轮
add_round_key(state, round_keys);
// 9轮
for (int r = 1; r < rounds; r++) {
sub_bytes(state);
shift_rows(state);
mix_columns(state);
add_round_key(state, round_keys + r * 16);
}
// 最后一轮
sub_bytes(state);
shift_rows(state);
add_round_key(state, round_keys + rounds * 16);
memcpy(output, state, 16);
}
void aes_decrypt(uint8_t *input, uint8_t *output, uint8_t *key) {
uint8_t state16;
memcpy(state, input, 16);
int rounds = 10;
uint8_t round_keys176;
key_expansion(key, round_keys, rounds);
// 初始轮(逆)
add_round_key(state, round_keys + rounds * 16);
// 9轮(逆)
for (int r = rounds - 1; r > 0; r--) {
inv_shift_rows(state);
inv_sub_bytes(state);
add_round_key(state, round_keys + r * 16);
inv_mix_columns(state);
}
// 最后一轮(逆)
inv_shift_rows(state);
inv_sub_bytes(state);
add_round_key(state, round_keys);
memcpy(output, state, 16);
}
```
- RSA加密
```c
// 大整数运算(简化版,仅演示原理)
typedef struct big_int {
uint32_t parts32;
int size;
} big_int_t;
// 快速幂模运算
uint64_t mod_pow(uint64_t base, uint64_t exp, uint64_t mod) {
uint64_t result = 1;
base %= mod;
while (exp > 0) {
if (exp & 1) result = (result * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
return result;
}
// 判断素数(简单试除)
int is_prime(uint64_t n) {
if (n < 2) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
for (uint64_t i = 3; i * i <= n; i += 2) {
if (n % i == 0) return 0;
}
return 1;
}
// 生成随机素数
uint64_t random_prime(int bits) {
uint64_t start = 1ULL << (bits - 1);
uint64_t end = (1ULL << bits) - 1;
uint64_t n;
do {
n = start + rand() % (end - start);
if (n % 2 == 0) n++;
} while (!is_prime(n));
return n;
}
// 扩展欧几里得
uint64_t mod_inverse(uint64_t a, uint64_t m) {
uint64_t m0 = m, a0 = a;
uint64_t y = 0, x = 1;
if (m == 1) return 0;
while (a > 1) {
uint64_t q = a / m;
uint64_t t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0) x += m0;
return x;
}
// RSA密钥对
typedef struct rsa_key {
uint64_t n; // 模数
uint64_t e; // 公钥指数
uint64_t d; // 私钥指数
} rsa_key_t;
// 生成RSA密钥对
rsa_key_t rsa_generate_keys(int bits) {
uint64_t p = random_prime(bits);
uint64_t q = random_prime(bits);
uint64_t n = p * q;
uint64_t phi = (p - 1) * (q - 1);
uint64_t e = 65537;
uint64_t d = mod_inverse(e, phi);
rsa_key_t keys;
keys.n = n;
keys.e = e;
keys.d = d;
return keys;
}
// RSA加密(公钥)
uint64_t rsa_encrypt(uint64_t msg, uint64_t e, uint64_t n) {
if (msg >= n) {
fprintf(stderr, "消息过大,需要分段加密\n");
return 0;
}
return mod_pow(msg, e, n);
}
// RSA解密(私钥)
uint64_t rsa_decrypt(uint64_t cipher, uint64_t d, uint64_t n) {
return mod_pow(cipher, d, n);
}
```
- 测试代码
```c
void test_aes() {
printf("=== AES加密测试 ===\n\n");
uint8_t key16 = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
uint8_t plaintext16 = {0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d,
0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34};
printf("明文: ");
for (int i = 0; i < 16; i++) printf("%02x ", plaintexti);
printf("\n");
uint8_t ciphertext16;
aes_encrypt(plaintext, ciphertext, key);
printf("密文: ");
for (int i = 0; i < 16; i++) printf("%02x ", ciphertexti);
printf("\n");
uint8_t decrypted16;
aes_decrypt(ciphertext, decrypted, key);
printf("解密: ");
for (int i = 0; i < 16; i++) printf("%02x ", decryptedi);
printf("\n");
printf("原始==解密: %s\n",
memcmp(plaintext, decrypted, 16) == 0 ? "✅ 成功" : "❌ 失败");
}
void test_rsa() {
printf("\n=== RSA加密测试 ===\n\n");
rsa_key_t keys = rsa_generate_keys(8);
printf("公钥: (n=%llu, e=%llu)\n", keys.n, keys.e);
printf("私钥: (n=%llu, d=%llu)\n", keys.n, keys.d);
uint64_t msg = 42;
printf("\n原文: %llu\n", msg);
uint64_t cipher = rsa_encrypt(msg, keys.e, keys.n);
printf("加密: %llu\n", cipher);
uint64_t decrypted = rsa_decrypt(cipher, keys.d, keys.n);
printf("解密: %llu\n", decrypted);
printf("原始==解密: %s\n", msg == decrypted ? "✅ 成功" : "❌ 失败");
}
int main() {
srand(time(NULL));
test_aes();
test_rsa();
return 0;
}
```
三、编译和运行
```bash
gcc -o encryption encryption.c -lm
./encryption
```
四、AES vs RSA
特性 AES RSA
类型 对称加密 非对称加密
密钥 同一密钥 公钥+私钥
速度 快 慢(慢1000倍)
密钥长度 128/192/256位 1024/2048/4096位
适用场景 数据加密 密钥分发、数字签名
五、总结
通过这篇文章,你学会了:
· AES加密核心操作(S盒、行移位、列混合、密钥扩展)
· RSA密钥生成和加解密
· 两种加密算法的完整实现
· 对称加密 vs 非对称加密的区别
加密是信息安全的基石。掌握它,你就理解了HTTPS、SSH、数字签名的底层原理。
下一篇预告:《从零实现一个网络防火墙:包过滤与状态检测》
评论区分享一下你对加密技术的理解~