1 /*
2 * This code is derived from (original license follows):
3 *
4 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
5 * MD5 Message-Digest Algorithm (RFC 1321).
6 *
7 * Homepage:
8 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
9 *
10 * Author:
11 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
12 *
13 * This software was written by Alexander Peslyak in 2001. No copyright is
14 * claimed, and the software is hereby placed in the public domain.
15 * In case this attempt to disclaim copyright and place the software in the
16 * public domain is deemed null and void, then the software is
17 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
18 * general public under the following terms:
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted.
22 *
23 * There's ABSOLUTELY NO WARRANTY, express or implied.
24 *
25 * See md5.c for more information.
26 */
27
28 #ifndef LLVM_SUPPORT_MD5_H
29 #define LLVM_SUPPORT_MD5_H
30
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/Support/DataTypes.h"
33 #include "llvm/Support/Endian.h"
34
35 namespace llvm {
36 template <typename T> class ArrayRef;
37
38 class MD5 {
39 // Any 32-bit or wider unsigned integer data type will do.
40 typedef uint32_t MD5_u32plus;
41
42 MD5_u32plus a, b, c, d;
43 MD5_u32plus hi, lo;
44 uint8_t buffer[64];
45 MD5_u32plus block[16];
46
47 public:
48 typedef uint8_t MD5Result[16];
49
50 MD5();
51
52 /// \brief Updates the hash for the byte stream provided.
53 void update(ArrayRef<uint8_t> Data);
54
55 /// \brief Updates the hash for the StringRef provided.
56 void update(StringRef Str);
57
58 /// \brief Finishes off the hash and puts the result in result.
59 void final(MD5Result &Result);
60
61 /// \brief Translates the bytes in \p Res to a hex string that is
62 /// deposited into \p Str. The result will be of length 32.
63 static void stringifyResult(MD5Result &Result, SmallString<32> &Str);
64
65 private:
66 const uint8_t *body(ArrayRef<uint8_t> Data);
67 };
68
69 /// Helper to compute and return lower 64 bits of the given string's MD5 hash.
MD5Hash(StringRef Str)70 inline uint64_t MD5Hash(StringRef Str) {
71 MD5 Hash;
72 Hash.update(Str);
73 llvm::MD5::MD5Result Result;
74 Hash.final(Result);
75 // Return the least significant 8 bytes. Our MD5 implementation returns the
76 // result in little endian, so we may need to swap bytes.
77 using namespace llvm::support;
78 return endian::read<uint64_t, little, unaligned>(Result);
79 }
80
81 }
82
83 #endif
84