这是一个高内聚低耦合可复用的DES加密系统的实现。
Github 链接:https://github.com/cyendra/CyDES
要实现加密系统,先考虑数据的基本单位。
在DES加密中,数据是以64位为一组的(unsigned long long),我们称它为Bit。
加密过程中会对Bit做位移操作(左移、右移、循环左移、循环右移),也会做位运算(And、Or、Xor),还会做分割以及合并等操作。
我们设计一个类Bit来封装这些操作,作为数据的基本单位。
1 /* 2 表示64位以下的数据 3 可以做常见的位运算 4 */ 5 class Bit { 6 private: 7 unsigned long long bit;// 表示数据,最多64位 8 int size;// 表示数据的位数,不超过64位 9 public: 10 // 值为0的64位数据 11 Bit(); 12 13 // 值为_bit的64位数据 14 Bit(unsigned long long _bit); 15 16 // 值为_bit的n位数据,当n>64位时截断 17 Bit(unsigned long long _bit, int n); 18 19 Bit(const Bit& b); 20 Bit& operator=(Bit& b); 21 //Bit& operator=(unsigned char num); 22 23 // 由byte构造8位Bit对象 24 void Byte(unsigned char num); 25 26 // 直接左移d位 27 void LeftShift(int d); 28 29 // 循环左移d位 30 void LeftRotate(int d); 31 32 // 直接右移d位 33 void RightShift(int d); 34 35 // 循环右移d位 36 void RightRotate(int d); 37 38 // 将第pos位设置为1 39 // pos从左向右从0开始计数,超过size位时无效 40 void Set(int pos); 41 42 // 将所有位都设置为1 43 void Set(); 44 45 // 将第pos位设置为0 46 // pos从左向右从0开始计数,超过size位时无效 47 void Reset(int pos); 48 49 // 将所有位都设置为0 50 void Reset(); 51 52 // 将第pos位取反 53 // pos从左向右从0开始计数,超过size位时无效 54 void Flip(int pos); 55 56 // 将所有位都取反 57 void Flip(); 58 59 // 当所有位都为0时返回true 60 bool None(); 61 62 // 当任意位为1时返回true 63 bool Any(); 64 65 // 统计所有位中1的个数 66 int Count(); 67 68 // 数据的有效位数 69 int Size(); 70 71 // 当第pos位的值为1时返回true 72 // pos从左向右从0开始计数,超过size位时无效 73 bool operator[](int pos); 74 75 // 将数据以unsigned long long的形式返回 76 unsigned long long ToULL(); 77 78 // 将所有二进制位以二进制串形式返回 79 std::string ToString(); 80 81 // 静态方法,将数据bit从中间分割为两份数据 82 static std::pair<Bit, Bit> Split(Bit bit); 83 84 // 静态方法,把数据bit平分为n份,n为偶数,bit的size能被n整除 85 static std::vector<Bit> Split(Bit bit, int n); 86 87 // 静态方法,将两份数据合并为一份数据 88 static Bit Merge(Bit L, Bit R); 89 90 // 静态方法,将Bit数组中从L到R之间的数据合并为一份数据 91 static Bit Merge(Bit b[], int L, int R); 92 93 // 静态方法,求两份数据的异或值 94 static Bit Xor(Bit x, Bit y); 95 96 // 静态方法,求两份数据的OR 97 static Bit Or(Bit x, Bit y); 98 99 // 静态方法,求两份数据的AND 100 static Bit And(Bit x, Bit y); 101 };