- /**
- * 加密解密
- * @file encrty.c
- * @brief
- * @author struggleLinux@gmail.com
- * @version 0.1
- * @date 2011-05-10
- */
- #include <stdio.h>
- #include <string.h>
- #define MAX 30
- char *str_key = "TRAILBAZERS";
- char alpha[MAX] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- char key[MAX] = "";
- /**
- * 对key进行处理
- * @brief prepare_key
- *
- * @param key
- *
- * @return
- */
- int prepare_key( char * key );
- /**
- * 加密
- * @brief encrypt
- *
- * @param data
- * @param key
- */
- void encrypt( char *data ,char const *key );
- /**
- * 解密
- * @brief decrypt
- *
- * @param data
- * @param key
- */
- void decrypt( char *data ,char const *key );
- int main()
- {
- char date[] = "ATTACK AT DAWN";
- if(prepare_key(key) != 0 ){
- printf("key = %s \n",key);
- encrypt(date,key);
- printf("加密后 date = %s \n",date);
- decrypt(date,key);
- printf("解密后 date = %s \n",date);
- }else
- printf("编码错误 : %s\n",key);
- return 0;
- }
- int prepare_key( char * key )
- {
- //定义返回值 1 为字符串转换成功, 0为字符串转换失败
- int result = 1;
- char *temp ,*alpha_t;
- temp = key;
- alpha_t = alpha;
- //将密钥中的小写字符转换为大写字符,并将重复的字符去除
- while ( *str_key != '\0'){
- if(islower(*str_key))
- toupper(*str_key);
- if(!isalpha (*str_key)){
- result = 0;
- break;
- }
- if( strrchr(temp,*str_key) == 0)
- *key++ = *str_key;
- str_key++;
- }
- //将alpha中不存在于密钥 str_key 中的字母添加到key中
- while( result != 0 && *alpha_t != '\0'){
- if( strrchr( temp, *alpha_t) == 0 )
- *key++ = *alpha_t;
- alpha_t++;
- }
- //判断key是否为空
- if(key == NULL)
- result = 0;
- return result;
- }
- void encrypt( char *date ,char const *key )
- {
- char * find_char;
- //将date中的字符替换,替换后的字符大小写格式与 date初始值 相同
- while( *date != '\0' ){
- if( isalpha(*date) ){
- find_char = strchr( alpha , toupper(*date));
- if(islower(*date)){
- *date = *( key +strlen(alpha)-strlen(find_char));
- *date = tolower(*date);
- }else{
- *date = *( key +strlen(alpha)-strlen(find_char));
- }
- }
- date++;
- }
- }
- void decrypt( char * date , char const * key )
- {
- char * find_char;
- while( *date != '\0' ){
- if( isalpha(*date ) ){
- find_char = strchr( key , toupper(*date));
- if( islower(*date) ){
- *date = *(alpha + strlen(key)-strlen(find_char));
- *date = tolower(*date);
- }else{
- *date = *(alpha + strlen(key)-strlen(find_char));
- }
- }
- date++;
- }
- }
VIM 7.3
gcc 版本 : 4.5.1 20100924 (Red Hat 4.5.1-4) (GCC)
system : Fedora 14
转载于:https://blog.51cto.com/strugglelinux/562691