blob: 65e3b4475798ebdd469abf72601544eeb3037b30 [file] [log] [blame]
Alexander Afanasyev8f25cbb2012-03-01 23:53:40 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
19 * 卞超轶 Chaoyi Bian <bcy@pku.edu.cn>
20 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
21 */
22
23#include "sync-digest.h"
24#include <string.h>
25
26#include "ns3/assert.h"
27
28namespace ns3 {
29namespace Sync {
30
31Digest::Digest ()
32 : m_buffer (0)
33 , m_hashLength (0)
34{
35 m_context = EVP_MD_CTX_create ();
36
37 int ok = EVP_DigestInit_ex (m_context, EVP_sha1 (), 0);
38 if (!ok)
39 throw DigestCalculationError ();
40}
41
42Digest::~Digest ()
43{
44 if (m_buffer != 0)
45 delete [] m_buffer;
46
47 EVP_MD_CTX_destroy (m_context);
48}
49
50void
51Digest::Finalize ()
52{
53 if (m_buffer != 0) return;
54
55 m_buffer = new uint8_t [HASH_SIZE];
56
57 int ok = EVP_DigestFinal_ex (m_context,
58 m_buffer, &m_hashLength);
59 if (!ok)
60 throw DigestCalculationError ();
61}
62
63std::size_t
64Digest::getHash ()
65{
66 if (m_buffer == 0)
67 Finalize ();
68
69 NS_ASSERT (sizeof (std::size_t) <= m_hashLength);
70
71 // just getting first sizeof(std::size_t) bytes
72 // not ideal, but should work pretty well
73 return reinterpret_cast<std::size_t> (m_buffer);
74}
75
76bool
77Digest::operator == (Digest &digest)
78{
79 if (m_buffer == 0)
80 Finalize ();
81
82 if (digest.m_buffer == 0)
83 digest.Finalize ();
84
85 NS_ASSERT (m_hashLength == digest.m_hashLength);
86
87 return memcmp (m_buffer, digest.m_buffer, m_hashLength) == 0;
88}
89
90
91} // Sync
92} // ns3
93