使用tomcrypt库来进行加密

5346阅读 0评论2012-08-01 blacksapper
分类:网络与安全

上一篇文章是使用RSA加密的.
因为对于随机数算法的不信任.所以就自己抄了个随机数算法.以后改起来也能改.说不定还能改成真随机数算法.并且使用tomcrypt里面自带的高级RSA功能加密时我把官方文档里的代码放进去用的时候发现运行有问题.我懒得改他的代码.就自己写了一个.这次是使用官方的方法来进行对称算法的加密解密.

点击(此处)折叠或打开

  1. /*
  2.  * twofish.c
  3.  *
  4.  * Created on: 2012-7-31
  5.  * Author: zzl
  6.  */
  7. #include <tomcrypt.h>
  8. /*
  9.  * 支持多种加密函数和加密方式。具体情况请参考tomcrypt_cipher.h
  10.  */
  11. int main(void)
  12. {
  13. unsigned char pt[8]={'c','h','i','n','a'}, ct[8]={0,0,0,0,0,0,0,0}, key[8]={'c','h','i','n','a'};
  14. symmetric_key skey;
  15. int err;
  16. /* ... key is loaded appropriately in key ... */
  17. /* ... load a block of plaintext in pt ... */
  18. /* schedule the key */
  19. if ((err = blowfish_setup(key, /* the key we will use */
  20. 8, /* key is 8 bytes (64-bits) long */
  21. 0, /* 0 == use default # of rounds */
  22. &skey) /* where to put the scheduled key */
  23. ) != CRYPT_OK) {
  24. printf("Setup error: %s\n", error_to_string(err));
  25. return -1;
  26. }

  27. printf("Setup key: %s\n", key);
  28. //printf("Setup skey: %s\n", skey);
  29. /* encrypt the block */
  30. blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
  31. ct, /* store encrypted data here */
  32. &skey); /* our previously scheduled key */
  33. int i;
  34. //如果不清空key则也会打印key的值
  35. for(i=0;i<8;i++)
  36.     key[i]=0;
  37. printf("blowfish_ecb_encrypt ct: %s\n", ct);
  38. /* now ct holds the encrypted version of pt */
  39. /* decrypt the block */
  40. blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
  41. pt, /* store decrypted data here */
  42. &skey); /* our previously scheduled key */
  43. /* now we have decrypted ct to the original plaintext in pt */
  44. /* Terminate the cipher context */
  45. printf("blowfish_ecb_encrypt pt: %s\n", pt);
  46. blowfish_done(&skey);
  47. return 0;
  48. }

对称算法包括
blowfish_ecb_encrypt
rc5_ecb_encrypt
rc6_ecb_encrypt
rc2_ecb_encrypt
saferp_ecb_encrypt
safer_ecb_encrypt 包括safer_k64 safer_sk64 safer_k128 safer_sk128
rijndael_ecb_encrypt 也就是aes_ecb_encrypt
xtea_ecb_encrypt
twofish_ecb_encrypt
des_ecb_encrypt
des3_ecb_encrypt
cast5_ecb_encrypt
noekeon_ecb_encrypt
skipjack_ecb_encrypt
khazad_ecb_encrypt
anubis_ecb_encrypt
kseed_ecb_encrypt
kasumi_ecb_encrypt
multi2_ecb_encrypt
等方法.
后面还有ecb cfb cbc等加密方式.
使用加密方法的时候把demo里面的XXX_setup XXX_ecb_encrypt XXX_ecb_decrypt XXX_done换成上面的内容就行了.
到目前为止使用tommath库和tomcrypt库可以完成对称和非对称的加密解密算法了.
上一篇:嵌入式系统的基本结构
下一篇:linux下的c语言的随机数算法代码