這個就是橢圓加密算法,只是選擇了不一樣的參數。所以用其餘一直橢圓曲線的算法實現,經過修改相關方程的參數,也能夠實現SM2。關於橢圓曲線的具體算法,能夠參考zmworm大神的文章,不過我仍是沒看懂。git
http://www.pediy.com/kssd/pediy06/pediy6014.htmgithub
這個是相似MD5,SHA256的摘要算法。經過一系列的位運算來得到一個256bit的大數。算法
對稱加密算法,沒仔細看,直接拿源碼來用了。跟通常的加密算法用起來沒啥區別,一個key既能夠加密,也能夠解密。函數
直接上結果吧,最後的測試經過的狀況是這樣:測試
測試代碼: SM4加密
#include <string.h> #include <stdio.h> #include "sm4.h" int main() { unsigned char key[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}; unsigned char input[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}; unsigned char output[16]; sm4_context ctx; unsigned long i; printf("Key: "); for(i=0;i<16;i++) printf("%02x ", key[i]); printf("\n"); //encrypt standard testing vector sm4_setkey_enc(&ctx,key); sm4_crypt_ecb(&ctx,1,16,input,output); printf("Encrypted: "); for(i=0;i<16;i++) printf("%02x ", output[i]); printf("\n"); //decrypt testing sm4_setkey_dec(&ctx,key); sm4_crypt_ecb(&ctx,0,16,output,output); printf("Decrypted: "); for(i=0;i<16;i++) printf("%02x ", output[i]); printf("\n"); return 0; }
SM3code
#include <string.h> #include <stdio.h> #include "sm3.h" int main( int argc, char *argv[] ) { unsigned char *input = "ab"; int ilen = 2; unsigned char output[32]; int i; sm3_context ctx; printf("Message:\n"); printf("%s\n",input); sm3(input, ilen, output); printf("Hash:\n "); for(i=0; i<32; i++) { printf("%02x",output[i]); if (((i+1) % 4 ) == 0) printf(" "); } printf("\n"); printf("Message:\n"); for(i=0; i < 16; i++) printf("abcd"); printf("\n"); sm3_starts( &ctx ); for(i=0; i < 16; i++) sm3_update( &ctx, "abcd", 4 ); sm3_finish( &ctx, output ); memset( &ctx, 0, sizeof( sm3_context ) ); printf("Hash:\n "); for(i=0; i<32; i++) { printf("%02x",output[i]); if (((i+1) % 4 ) == 0) printf(" "); } printf("\n"); //getch(); //VS2008 }