Merge master.
[libdcp.git] / src / key.cc
1 /*
2     Copyright (C) 2013-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/key.cc
21  *  @brief Key class.
22  */
23
24 #include "key.h"
25 #include "AS_DCP.h"
26 #include "KM_prng.h"
27 #include "KM_util.h"
28 #include <sstream>
29 #include <string>
30 #include <iomanip>
31
32 using std::string;
33 using std::stringstream;
34 using std::setw;
35 using std::setfill;
36 using namespace dcp;
37
38 Key::Key ()
39         : _value (new uint8_t[ASDCP::KeyLen])
40 {
41         Kumu::FortunaRNG rng;
42         rng.FillRandom (_value, ASDCP::KeyLen);
43 }
44
45 Key::Key (uint8_t const * value)
46         : _value (new uint8_t[ASDCP::KeyLen])
47 {
48         memcpy (_value, value, ASDCP::KeyLen);
49 }
50
51 Key::Key (string value)
52         : _value (new uint8_t[ASDCP::KeyLen])
53 {
54         unsigned int length;
55         Kumu::hex2bin (value.c_str(), _value, ASDCP::KeyLen, &length);
56 }
57
58 Key::Key (Key const & other)
59         : _value (new uint8_t[ASDCP::KeyLen])
60 {
61         memcpy (_value, other._value, ASDCP::KeyLen);
62 }
63
64 Key::~Key ()
65 {
66         delete[] _value;
67 }
68
69 Key &
70 Key::operator= (Key const & other)
71 {
72         if (this == &other) {
73                 return *this;
74         }
75         
76         memcpy (_value, other._value, ASDCP::KeyLen);
77         return *this;
78 }
79
80 string
81 Key::hex () const
82 {
83         stringstream g;
84         
85         for (unsigned int i = 0; i < ASDCP::KeyLen; ++i) {
86                 g << setw(2) << setfill('0') << std::hex << static_cast<int> (_value[i]);
87         }
88
89         return g.str ();
90 }
91
92 bool
93 dcp::operator== (Key const & a, Key const & b)
94 {
95         return memcmp (a.value(), b.value(), ASDCP::KeyLen) == 0;
96 }
97
98 bool
99 dcp::operator!= (Key const & a, Key const & b)
100 {
101         return !(a == b);
102 }
103