namespace libdcp -> dcp.
[libdcp.git] / src / key.cc
1 /*
2     Copyright (C) 2013 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 #include <sstream>
21 #include <string>
22 #include <iomanip>
23 #include "AS_DCP.h"
24 #include "KM_prng.h"
25 #include "KM_util.h"
26 #include "key.h"
27
28 using std::string;
29 using std::stringstream;
30 using std::setw;
31 using std::setfill;
32 using namespace dcp;
33
34 Key::Key ()
35         : _value (new uint8_t[ASDCP::KeyLen])
36 {
37         Kumu::FortunaRNG rng;
38         rng.FillRandom (_value, ASDCP::KeyLen);
39 }
40
41 Key::Key (uint8_t const * value)
42         : _value (new uint8_t[ASDCP::KeyLen])
43 {
44         memcpy (_value, value, ASDCP::KeyLen);
45 }
46
47 Key::Key (string value)
48         : _value (new uint8_t[ASDCP::KeyLen])
49 {
50         unsigned int length;
51         Kumu::hex2bin (value.c_str(), _value, ASDCP::KeyLen, &length);
52 }
53
54 Key::Key (Key const & other)
55         : _value (new uint8_t[ASDCP::KeyLen])
56 {
57         memcpy (_value, other._value, ASDCP::KeyLen);
58 }
59
60 Key::~Key ()
61 {
62         delete[] _value;
63 }
64
65 Key &
66 Key::operator= (Key const & other)
67 {
68         if (this == &other) {
69                 return *this;
70         }
71         
72         memcpy (_value, other._value, ASDCP::KeyLen);
73         return *this;
74 }
75
76 string
77 Key::hex () const
78 {
79         stringstream g;
80         
81         for (unsigned int i = 0; i < ASDCP::KeyLen; ++i) {
82                 g << setw(2) << setfill('0') << std::hex << static_cast<int> (_value[i]);
83         }
84
85         return g.str ();
86 }
87
88 bool
89 dcp::operator== (Key const & a, Key const & b)
90 {
91         return memcmp (a.value(), b.value(), ASDCP::KeyLen) == 0;
92 }
93
94 bool
95 dcp::operator!= (Key const & a, Key const & b)
96 {
97         return !(a == b);
98 }
99