Linux下openssl的第1个程序

openssl是开源的,可以在上面编写测试代码,怎样编写呢?在此举一个例子。

第一步:编写1个测试程序MD5test1.c,代码如下
  1. #include<stdio.h>
  2. #include<openssl/md5.h>
  3. #include<string.h>
  4. int main(int argc,char**argv )
  5. {
  6. MD5_CTX ctx;
  7. unsignedchar*data="123";
  8. unsignedchar md[16];
  9. char buf[33]={'\0'};
  10. char tmp[3]={'\0'};
  11. int i;
  12. MD5_Init(&ctx);
  13. MD5_Update(&ctx,data, strlen (data));
  14. MD5_Final(md,&ctx);
  15. for( i=0; i<16; i++)
  16. {
  17. sprintf (tmp,"%02X",md[i]);
  18. strcat (buf,tmp);
  19. }
  20. printf ("%s\n",buf);
  21. return0;
  22. }
第二步:将该代码放在如下目录:
/openssl-1.1.0c/test
第三步:编译 MD5test1.c。
[root@localhost test]# gcc -o MD5test1 MD5test1.c
/tmp/cczP8S6Z.o: In function `main':
MD5test1.c:(.text+0x6b): undefined reference to `MD5_Init'
MD5test1.c:(.text+0x8d): undefined reference to `MD5_Update'
MD5test1.c:(.text+0xa0): undefined reference to `MD5_Final'
collect2: error: ld returned 1 exit status
出现了三个错误。
错误原因是
包含md5函数的库为/usr/lib/libcrypto.a(.so),编译时要使用-lcrypto。
第四步:重新编译 MD5test1.c。
[root@localhost test]# gcc -o MD5test1 MD5test1.c  -lcrypto
编译成功。
第五步:运行 MD5test1
[root@localhost test]# ./MD5test1 
202CB962AC59075B964B07152D234B70

猜你喜欢

转载自cakin24.iteye.com/blog/2344219