sm3算法c++详细代码
时间: 2024-12-22 13:18:59 浏览: 11
SM3是中国国家密码管理局发布的一种哈希算法,它的安全性、效率等方面都得到了广泛认可。以下是SM3算法的C++实现代码:
```
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
typedef unsigned int uint32;
typedef unsigned char byte;
const uint32 T[] = {
0x79cc4519, 0xf3988a32, 0xe7311465, 0xce6228cb,
0x9cc45197, 0x3988a32f, 0x7311465e, 0xe6228cbc,
0xcc451979, 0x988a32f3, 0x311465e7, 0x6228cbce,
0xc451979c, 0x88a32f39, 0x11465e73, 0x228cbce6,
0x9d8a7b6f, 0x3b14f6de, 0x7629edbc, 0xec53d978,
0xd8a7b6f1, 0xb14f6de3, 0x629edbc7, 0xc53d978e,
0x8a7b6f1d, 0x14f6de3b, 0x29edbc76, 0x53d978ec,
0xa7b6f1d8, 0x4f6de3b1, 0x9edbc762, 0x3d978ec5,
0x7b6f1d8a, 0xf6de3b14, 0xedbc7629, 0xd978ec53,
0xb6f1d8a7, 0x6de3b14f, 0xdbc7629e, 0x978ec53d,
0x6f1d8a7b, 0xde3b14f6, 0xbc7629ed, 0x78ec53d9,
0x5d8ce909, 0xbb19d212, 0x7627a424, 0xec4f4849,
0xd8ce9093, 0xb19d2127, 0x627a424e, 0xc4f4849c,
0x8ce90935, 0x19d2127b, 0x27a424ef, 0x4f4849de,
0xce90935d, 0x9d2127bb, 0x7a424ef6, 0xf4849dec,
0xe90935d8, 0xd2127bb1, 0xa424ef67, 0x4849decf,
0x90935d8c, 0x2127bb19, 0x424ef762, 0x849dec53
};
uint32 ROT(uint32 x,int n)
{
return (x << n) | (x >> (32-n));
}
void CF(byte* V,uint32* W,uint32* W1)
{
uint32 A = V <<24 | V <<16 | V <<8 | V;
uint32 B = V <<24 | V <<16 | V <<8 | V;
uint32 C = V <<24 | V <<16 | V[10]<<8 | V[11];
uint32 D = V[12]<<24 | V[13]<<16 | V[14]<<8 | V[15];
uint32 E = V[16]<<24 | V[17]<<16 | V[18]<<8 | V[19];
uint32 F = V[20]<<24 | V[21]<<16 | V[22]<<8 | V[23];
uint32 G = V[24]<<24 | V[25]<<16 | V[26]<<8 | V[27];
uint32 H = V[28]<<24 | V[29]<<16 | V[30]<<8 | V[31];
for(int i=0; i<64; ++i) {
uint32 SS1 = ROT(ROT(A,12)+E+ROT(T[i],i),7);
uint32 SS2 = SS1 ^ ROT(A,12);
uint32 TT1 = (i<16) ? (FF(A,B,C)+D+W[i]) : (GG(A,B,C)+D+W1[i-16]);
uint32 TT2 = (i<16) ? (HH(E,F,G)+H+W[i]) : (HHH(E,F,G)+H+W1[i-16]);
D = C;
C = ROT(B,9);
B = A;
A = SS2 + TT1;
H = G;
G = ROT(F,19);
F = E;
E = P(SS1) + TT2;
}
V[31] += H;
V[30] += G;
V[29] += F;
V[28] += E;
V[27] += D;
V[26] += C;
V[25] += B;
V[24] += A;
}
void Hash(byte* message,uint32 len,uint32* digest)
{
byte M[64];
byte N = ((len+8)%64);
byte K = (N<56) ? (56-N) : (120-N);
len <<=3;
memset(M ,00,sizeof(M));
memcpy(M ,message,len>>3);
M[len>>3] |= (byte)128;
memcpy(M+K+8,&len,sizeof(len));
for(int i=0; i<len+K+8; i+=64)
CF(digest,(uint32*)(M+i),(uint32*)(M+i+64));
}
int main()
{
byte message[] = "Hello world!";
uint32 digest[] = { //初始值
0x7380166F,0x4914B2B9,
0x172442D7,0xDA8A0600,
0xA96F30BC,0x163138AA,
0xE38DEE4D,0xB0FB0E4E
};
Hash(message,sizeof(message),digest);
cout<<"Digest: ";
for(int i=0; i<8; ++i) {
cout<<hex<<setfill('0')<<setw(8)<<digest[i];
}
}
```
阅读全文