BoringSSL-简单应用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <string>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
#include <fstream>

//获取SSL版本
const char * getSslVersion() {
   return SSLeay_version(SSLEAY_VERSION);
}

//文件SHA1
std::string fileSha1(const char *filePath) {
 SHA_CTX ctx;
 unsigned char out_value[20] = {0};
 char tmp[3] = {0};
 std::string result;
 int i;

 SHA1_Init(&ctx);

 int bufferLen = 1024;
 char *buffer = new char[bufferLen];

 std::ifstream is(filePath, std::ifstream::binary);
 if (is.is_open()) {
   while (!is.eof()) {
     is.read(buffer, bufferLen);
     size_t count = is.gcount();
     SHA1_Update(&ctx, buffer, count);
   }
 }
 is.close();
 delete[] buffer;

 SHA1_Final(out_value, &ctx);

 //格式化结果
 for (i = 0; i < 20; i++) {
   sprintf(tmp, "%02x", out_value[i]);
   result.append(tmp);
 }

 return result;
}

//字符串的SHA1
std::string strSha1(const char *input, size_t len) {
 SHA_CTX ctx;
 unsigned char out_value[20] = {0};
 char tmp[3] = {0};
 std::string result;
 int i;

 SHA1_Init(&ctx);
 SHA1_Update(&ctx, input, len);
 SHA1_Final(out_value, &ctx);

 for (i = 0; i < 20; i++) {
   sprintf(tmp, "%02x", out_value[i]);
   result.append(tmp);
 }

 return result;
}

MD5计算方法类似,SHA_CTX变成MD5_CTX,其他函数也变成MD5开头即可。

Built with Hugo
主题 StackJimmy 设计