Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92331055
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-16 22:48:25

// DES encrypt with OpenSSL support 
// g++ crypt.cc -lssl -o crypt 

#include  
#include  

int main(int argc, char** argv) 

  try 
  { 
     std::string keystring("this is my key");// 初始化key(密钥) 
     DES_cblock key[1];   //具体是什么?不知道也一样可以用 
     DES_key_schedule key_schedule;   //字面意思是密码表 

     if (NULL != argv[1]) 
        keystring.assign(argv[1]);//如果命令行指定了key,那么就用指定的 

     // 生成一个 key 
     DES_string_to_key(keystring.c_str(), key); 
     if (DES_set_key_checked(key, &key_schedule) != 0) 
        throw "DES_set_key_schedule"

     unsigned char input[] = "this is a text being encrypted by openssl";//需要加密的字符串 
     size_t len = (sizeof(input)+7)/8 * 8;   
     unsigned char *output = new unsigned char[len+1]; 
      //加密以后的内容怎么分配内存,照上面这两步走就是了 
      //错了就干掉贴代码的人:mrgreen: 
     DES_cblock ivec;   
      //照这个搞就是了,用别人的代码不一定要知道所由的细节是为什么 

     // 加密 
     memset((char*)&ivec, 0, sizeof(ivec));//ivec清0 
     DES_ncbc_encrypt(input, output, sizeof(input), &key_schedule, &ivec, 1);//这里就进行加密了 
     std::cout << input << std::endl; 

     //输出加密以后的内容 
     for (int i = 0; i < len; ++i) 
        printf("%02x", output); 
     std::cout << std::endl; 

     // 解密 
     memset((char*)&ivec, 0, sizeof(ivec)); 
     DES_ncbc_encrypt(output, input, len, &key_schedule, &ivec, 0); 
     std::cout << input << std::endl; 
      
     delete[] output; 
  } 
  catch(const char* errstr)   //对抛出异常的处理 
  { 
     std::cerr << errstr << std::endl; 
     return EXIT_FAILURE; 
  } 

  return EXIT_SUCCESS; 
}
阅读(381) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~