#include <iostream> #include <cstring> typedef unsigned int uint32_t; //定义32位无符号整数 const uint32_t P = 0xb7e15163; //定义P值 const uint32_t Q = 0x9e3779b9; //定义Q值 // 左移函数 uint32_t rotate_left(uint32_t x, uint32_t y) { return (x << y) | (x >> (32 - y)); } // 右移函数 uint32_t rotate_right(uint32_t x, uint32_t y) { return (x >> y) | (x << (32 - y)); } // 加密函数 void rc5_encrypt(uint32_t *pt, uint32_t *ct, uint32_t *key, int rounds) { uint32_t i, j, a, b, *s, t, u; s = new uint32_t[2*rounds + 2]; s[0] = P; for (i = 1; i < 2*rounds + 2; i++) s[i] = s[i-1] + Q; i = j = 0; a = b = 0; for (int k = 0; k < 4; k++) { a |= key[k] << (k*8); b |= key[k+4] << (k*8); } a = a + s[0]; b = b + s[1]; for (i = 2; i <= 2*rounds; i++) { t = rotate_left(a + b, 3); a = t; u = t + b; t = rotate_left(b, u); b = t; u = t + a; a = rotate_left(a + s[i], u); t = rotate_left(b + s[i+1], u); b = t; i += 1; } ct[0] = a; ct[1] = b; } // 解密函数 void rc5_decrypt(uint32_t *ct, uint32_t *pt, uint32_t *key, int rounds) { uint32_t i, j, a, b, *s, t, u; s = new uint32_t[2*rounds + 2]; s[0] = P; for (i = 1; i < 2*rounds + 2; i++) s[i] = s[i-1] + Q; i = j = 0; a = b = 0; for (int k = 0; k < 4; k++) { a |= key[k] << (k*8); b |= key[k+4] << (k*8); } ct[0] = ct[0] - s[2*rounds + 1]; ct[1] = ct[1] - s[2*rounds]; for (i = 2*rounds; i >= 2; i--) { t = rotate_left(b, u); b = ct[1] - s[i-1]; u = t + b; t = rotate_left(a, u); a = ct[0] - s[i-2]; b = t + a; a = t - rotate_left(a + s[i-1], u); i -= 1; } pt[0] = a; pt[1] = b; } // 测试函数 int main() { uint32_t pt[2] = {0x01234567, 0x89abcdef}; uint32_t key[8] = {0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f}; uint32_t ct[2]; int rounds = 12; rc5_encrypt(pt, ct, key, rounds); std::cout << "Encrypted message: " << std::hex << ct[0] << " " << ct[1] << std::endl; rc5_decrypt(ct, pt, key, rounds); std::cout << "Decrypted message: " << std::hex << pt[0] << " " << pt[1] << std::endl; return 0; }