因为对于随机数算法的不信任.所以就自己抄了个随机数算法.以后改起来也能改.说不定还能改成真随机数算法.并且使用tomcrypt里面自带的高级RSA功能加密时我把官方文档里的代码放进去用的时候发现运行有问题.我懒得改他的代码.就自己写了一个.这次是使用官方的方法来进行对称算法的加密解密.
- /*
- * twofish.c
- *
- * Created on: 2012-7-31
- * Author: zzl
- */
- #include <tomcrypt.h>
- /*
- * 支持多种加密函数和加密方式。具体情况请参考tomcrypt_cipher.h
- */
- int main(void)
- {
- 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'};
- symmetric_key skey;
- int err;
- /* ... key is loaded appropriately in key ... */
- /* ... load a block of plaintext in pt ... */
- /* schedule the key */
- if ((err = blowfish_setup(key, /* the key we will use */
- 8, /* key is 8 bytes (64-bits) long */
- 0, /* 0 == use default # of rounds */
- &skey) /* where to put the scheduled key */
- ) != CRYPT_OK) {
- printf("Setup error: %s\n", error_to_string(err));
- return -1;
- }
- printf("Setup key: %s\n", key);
- //printf("Setup skey: %s\n", skey);
- /* encrypt the block */
- blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
- ct, /* store encrypted data here */
- &skey); /* our previously scheduled key */
- int i;
- //如果不清空key则也会打印key的值
- for(i=0;i<8;i++)
- key[i]=0;
- printf("blowfish_ecb_encrypt ct: %s\n", ct);
- /* now ct holds the encrypted version of pt */
- /* decrypt the block */
- blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
- pt, /* store decrypted data here */
- &skey); /* our previously scheduled key */
- /* now we have decrypted ct to the original plaintext in pt */
- /* Terminate the cipher context */
- printf("blowfish_ecb_encrypt pt: %s\n", pt);
- blowfish_done(&skey);
- return 0;
- }
对称算法包括
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库可以完成对称和非对称的加密解密算法了.
阅读(5360) | 评论(0) | 转发(0) |