• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * copyright 2012, the android open source project
3  *
4  * licensed under the apache license, version 2.0 (the "license");
5  * you may not use this file except in compliance with the license.
6  * you may obtain a copy of the license at
7  *
8  *     http://www.apache.org/licenses/license-2.0
9  *
10  * unless required by applicable law or agreed to in writing, software
11  * distributed under the license is distributed on an "as is" basis,
12  * without warranties or conditions of any kind, either express or implied.
13  * see the license for the specific language governing permissions and
14  * limitations under the license.
15  */
16 
17 #include "bcc/Support/Sha1Util.h"
18 
19 #include <sha1.h>
20 
21 #include <cstring>
22 
23 #include "bcc/Support/Log.h"
24 #include "bcc/Support/InputFile.h"
25 
26 using namespace bcc;
27 
GetSHA1DigestFromFile(uint8_t pResult[SHA1_DIGEST_LENGTH],const char * pFilename)28 bool Sha1Util::GetSHA1DigestFromFile(uint8_t pResult[SHA1_DIGEST_LENGTH],
29                                      const char *pFilename) {
30   InputFile file(pFilename);
31 
32   if (file.hasError()) {
33     ALOGE("Unable to open the file %s before SHA-1 checksum "
34           "calculation! (%s)", pFilename, file.getErrorMessage().c_str());
35     return false;
36   }
37 
38   SHA1_CTX sha1_context;
39   SHA1Init(&sha1_context);
40 
41   char buf[256];
42   while (true) {
43     ssize_t nread = file.read(buf, sizeof(buf));
44 
45     if (nread < 0) {
46       // Some errors occurred during file reading.
47       return false;
48     }
49 
50     SHA1Update(&sha1_context,
51                reinterpret_cast<unsigned char *>(buf),
52                static_cast<unsigned long>(nread));
53 
54     if (static_cast<size_t>(nread) < sizeof(buf)) {
55       break;
56     }
57   }
58 
59   SHA1Final(pResult, &sha1_context);
60 
61   return true;
62 }
63 
GetSHA1DigestFromBuffer(uint8_t pResult[SHA1_DIGEST_LENGTH],const uint8_t * pData,size_t pSize)64 bool Sha1Util::GetSHA1DigestFromBuffer(uint8_t pResult[SHA1_DIGEST_LENGTH],
65                                        const uint8_t *pData, size_t pSize) {
66   SHA1_CTX sha1_context;
67 
68   SHA1Init(&sha1_context);
69 
70   SHA1Update(&sha1_context,
71              reinterpret_cast<const unsigned char *>(pData),
72              static_cast<unsigned long>(pSize));
73 
74   SHA1Final(pResult, &sha1_context);
75 
76   return true;
77 }
78