File: encrypt.py

package info (click to toggle)
python-pykmip 0.10.0-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,796 kB
  • sloc: python: 102,456; makefile: 33; sh: 12
file content (631 lines) | stat: -rw-r--r-- 22,477 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# Copyright (c) 2017 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import six

from kmip.core import attributes
from kmip.core import enums
from kmip.core import primitives
from kmip.core import utils
from kmip.core.messages.payloads import base


class EncryptRequestPayload(base.RequestPayload):
    """
    A request payload for the Encrypt operation.

    Attributes:
        unique_identifier: The unique ID of the managed object to be used for
            encryption.
        cryptographic_parameters: A collection of settings relevant for
            the encryption operation.
        data: The data to be encrypted in the form of a binary string.
        iv_counter_nonce: An IV/counter/nonce to be used with the encryption
            algorithm. Comes in the form of a binary string.
        auth_additional_data: Any additional data to be authenticated via the
            Authenticated Encryption Tag. Added in KMIP 1.4.
    """

    def __init__(self,
                 unique_identifier=None,
                 cryptographic_parameters=None,
                 data=None,
                 iv_counter_nonce=None,
                 auth_additional_data=None):
        """
        Construct an Encrypt request payload struct.

        Args:
            unique_identifier (string): The ID of the managed object (e.g.,
                a symmetric key) to be used for encryption. Optional, defaults
                to None. If not included, the ID placeholder will be used.
            cryptographic_parameters (CryptographicParameters): A
                CryptographicParameters struct containing the settings for
                the encryption algorithm. Optional, defaults to None. If not
                included, the CryptographicParameters associated with the
                managed object will be used instead.
            data (bytes): The data to encrypt in binary form. Required for
                encoding and decoding.
            iv_counter_nonce (bytes): The IV/counter/nonce value to be used
                with the encryption algorithm. Optional, defaults to None.
            auth_additional_data (bytes): Any additional data to be
                authenticated via the Authenticated Encryption Tag.
                Added in KMIP 1.4.
        """
        super(EncryptRequestPayload, self).__init__()

        self._unique_identifier = None
        self._cryptographic_parameters = None
        self._data = None
        self._iv_counter_nonce = None
        self._auth_additional_data = None

        self.unique_identifier = unique_identifier
        self.cryptographic_parameters = cryptographic_parameters
        self.data = data
        self.iv_counter_nonce = iv_counter_nonce
        self.auth_additional_data = auth_additional_data

    @property
    def unique_identifier(self):
        if self._unique_identifier:
            return self._unique_identifier.value
        else:
            return None

    @unique_identifier.setter
    def unique_identifier(self, value):
        if value is None:
            self._unique_identifier = None
        elif isinstance(value, six.string_types):
            self._unique_identifier = primitives.TextString(
                value=value,
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
        else:
            raise TypeError("unique identifier must be a string")

    @property
    def cryptographic_parameters(self):
        return self._cryptographic_parameters

    @cryptographic_parameters.setter
    def cryptographic_parameters(self, value):
        if value is None:
            self._cryptographic_parameters = None
        elif isinstance(value, attributes.CryptographicParameters):
            self._cryptographic_parameters = value
        else:
            raise TypeError(
                "cryptographic parameters must be a CryptographicParameters "
                "struct"
            )

    @property
    def data(self):
        if self._data:
            return self._data.value
        else:
            return None

    @data.setter
    def data(self, value):
        if value is None:
            self._data = None
        elif isinstance(value, six.binary_type):
            self._data = primitives.ByteString(
                value=value,
                tag=enums.Tags.DATA
            )
        else:
            raise TypeError("data must be bytes")

    @property
    def iv_counter_nonce(self):
        if self._iv_counter_nonce:
            return self._iv_counter_nonce.value
        else:
            return None

    @iv_counter_nonce.setter
    def iv_counter_nonce(self, value):
        if value is None:
            self._iv_counter_nonce = None
        elif isinstance(value, six.binary_type):
            self._iv_counter_nonce = primitives.ByteString(
                value=value,
                tag=enums.Tags.IV_COUNTER_NONCE
            )
        else:
            raise TypeError("IV/counter/nonce must be bytes")

    @property
    def auth_additional_data(self):
        if self._auth_additional_data:
            return self._auth_additional_data.value
        else:
            return None

    @auth_additional_data.setter
    def auth_additional_data(self, value):
        if value is None:
            self._auth_additional_data = None
        elif isinstance(value, six.binary_type):
            self._auth_additional_data = primitives.ByteString(
                value=value,
                tag=enums.Tags.AUTHENTICATED_ENCRYPTION_ADDITIONAL_DATA
            )
        else:
            raise TypeError("authenticated additional data must be bytes")

    def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Encrypt request payload and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a read method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is missing from the
                encoded payload.
        """
        super(EncryptRequestPayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(
                enums.Tags.CRYPTOGRAPHIC_PARAMETERS,
                local_stream
        ):
            self._cryptographic_parameters = \
                attributes.CryptographicParameters()
            self._cryptographic_parameters.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(enums.Tags.DATA, local_stream):
            self._data = primitives.ByteString(tag=enums.Tags.DATA)
            self._data.read(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self.is_tag_next(enums.Tags.IV_COUNTER_NONCE, local_stream):
            self._iv_counter_nonce = primitives.ByteString(
                tag=enums.Tags.IV_COUNTER_NONCE
            )
            self._iv_counter_nonce.read(
                local_stream,
                kmip_version=kmip_version
            )

        if kmip_version >= enums.KMIPVersion.KMIP_1_4:
            if self.is_tag_next(
                    enums.Tags.AUTHENTICATED_ENCRYPTION_ADDITIONAL_DATA,
                    local_stream
            ):
                self._auth_additional_data = primitives.ByteString(
                    tag=enums.Tags.AUTHENTICATED_ENCRYPTION_ADDITIONAL_DATA
                )
                self._auth_additional_data.read(
                    local_stream,
                    kmip_version=kmip_version
                )

        self.is_oversized(local_stream)

    def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Encrypt request payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        local_stream = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._cryptographic_parameters:
            self._cryptographic_parameters.write(
                local_stream,
                kmip_version=kmip_version
            )

        if self._data:
            self._data.write(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self._iv_counter_nonce:
            self._iv_counter_nonce.write(
                local_stream,
                kmip_version=kmip_version
            )

        if kmip_version >= enums.KMIPVersion.KMIP_1_4:
            if self._auth_additional_data:
                self._auth_additional_data.write(
                    local_stream,
                    kmip_version=kmip_version
                )

        self.length = local_stream.length()
        super(EncryptRequestPayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

    def __eq__(self, other):
        if isinstance(other, EncryptRequestPayload):
            if self.unique_identifier != other.unique_identifier:
                return False
            elif self.cryptographic_parameters !=\
                    other.cryptographic_parameters:
                return False
            elif self.data != other.data:
                return False
            elif self.iv_counter_nonce != other.iv_counter_nonce:
                return False
            elif self.auth_additional_data != other.auth_additional_data:
                return False
            else:
                return True
        else:
            return NotImplemented

    def __ne__(self, other):
        if isinstance(other, EncryptRequestPayload):
            return not (self == other)
        else:
            return NotImplemented

    def __repr__(self):
        args = ", ".join([
            "unique_identifier='{0}'".format(self.unique_identifier),
            "cryptographic_parameters={0}".format(
                repr(self.cryptographic_parameters)
            ),
            "data={0}".format(self.data),
            "iv_counter_nonce={0}".format(self.iv_counter_nonce),
            "auth_additional_data={0}".format(self.auth_additional_data)
        ])
        return "EncryptRequestPayload({0})".format(args)

    def __str__(self):
        return str({
            'unique_identifier': self.unique_identifier,
            'cryptographic_parameters': self.cryptographic_parameters,
            'data': self.data,
            'iv_counter_nonce': self.iv_counter_nonce,
            'auth_additional_data': self.auth_additional_data
        })


class EncryptResponsePayload(base.ResponsePayload):
    """
    A response payload for the Encrypt operation.

    Attributes:
        unique_identifier: The unique ID of the managed object used for the
            encryption.
        data: The encrypted data in the form of a binary string.
        iv_counter_nonce: The IV/counter/nonce used with the encryption
            algorithm. Comes in the form of a binary string.
        auth_tag: Specifies the tag that will be needed to
            authenticate the decrypted data. Only returned on completion
            of the encryption of the last of the plaintext by an
            authenticated encryption cipher. Optional, defaults to None.
            Added in KMIP 1.4.
    """

    def __init__(self,
                 unique_identifier=None,
                 data=None,
                 iv_counter_nonce=None,
                 auth_tag=None):
        """
        Construct an Encrypt response payload struct.

        Args:
            unique_identifier (string): The ID of the managed object (e.g.,
                a symmetric key) used for encryption. Required for encoding
                and decoding.
            data (bytes): The encrypted data in binary form. Required for
                encoding and decoding.
            iv_counter_nonce (bytes): The IV/counter/nonce value used with
                the encryption algorithm if it was required and if this
                value was not originally specified by the client. Optional,
                defaults to None.
            auth_tag (bytes): Specifies the tag that will be needed to
                authenticate the decrypted data. Only returned on completion
                of the encryption of the last of the plaintext by an
                authenticated encryption cipher. Optional, defaults to None.
                Added in KMIP 1.4.
        """
        super(EncryptResponsePayload, self).__init__()

        self._unique_identifier = None
        self._data = None
        self._iv_counter_nonce = None
        self._auth_tag = None

        self.unique_identifier = unique_identifier
        self.data = data
        self.iv_counter_nonce = iv_counter_nonce
        self.auth_tag = auth_tag

    @property
    def unique_identifier(self):
        if self._unique_identifier:
            return self._unique_identifier.value
        else:
            return None

    @unique_identifier.setter
    def unique_identifier(self, value):
        if value is None:
            self._unique_identifier = None
        elif isinstance(value, six.string_types):
            self._unique_identifier = primitives.TextString(
                value=value,
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
        else:
            raise TypeError("unique identifier must be a string")

    @property
    def data(self):
        if self._data:
            return self._data.value
        else:
            return None

    @data.setter
    def data(self, value):
        if value is None:
            self._data = None
        elif isinstance(value, six.binary_type):
            self._data = primitives.ByteString(
                value=value,
                tag=enums.Tags.DATA
            )
        else:
            raise TypeError("data must be bytes")

    @property
    def iv_counter_nonce(self):
        if self._iv_counter_nonce:
            return self._iv_counter_nonce.value
        else:
            return None

    @iv_counter_nonce.setter
    def iv_counter_nonce(self, value):
        if value is None:
            self._iv_counter_nonce = None
        elif isinstance(value, six.binary_type):
            self._iv_counter_nonce = primitives.ByteString(
                value=value,
                tag=enums.Tags.IV_COUNTER_NONCE
            )
        else:
            raise TypeError("IV/counter/nonce must be bytes")

    @property
    def auth_tag(self):
        if self._auth_tag:
            return self._auth_tag.value
        else:
            return None

    @auth_tag.setter
    def auth_tag(self, value):
        if value is None:
            self._auth_tag = None
        elif isinstance(value, six.binary_type):
            self._auth_tag = primitives.ByteString(
                value=value,
                tag=enums.Tags.AUTHENTICATED_ENCRYPTION_TAG
            )
        else:
            raise TypeError("authenticated encryption tag must be bytes")

    def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Encrypt response payload and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a read method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the unique_identifier or data attributes
                are missing from the encoded payload.
        """
        super(EncryptResponsePayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "invalid payload missing the unique identifier attribute"
            )

        if self.is_tag_next(enums.Tags.DATA, local_stream):
            self._data = primitives.ByteString(tag=enums.Tags.DATA)
            self._data.read(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self.is_tag_next(enums.Tags.IV_COUNTER_NONCE, local_stream):
            self._iv_counter_nonce = primitives.ByteString(
                tag=enums.Tags.IV_COUNTER_NONCE
            )
            self._iv_counter_nonce.read(
                local_stream,
                kmip_version=kmip_version
            )

        if kmip_version >= enums.KMIPVersion.KMIP_1_4:
            if self.is_tag_next(
                    enums.Tags.AUTHENTICATED_ENCRYPTION_TAG, local_stream
            ):
                self._auth_tag = primitives.ByteString(
                    tag=enums.Tags.AUTHENTICATED_ENCRYPTION_TAG
                )
                self._auth_tag.read(
                    local_stream,
                    kmip_version=kmip_version
                )

        self.is_oversized(local_stream)

    def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Encrypt response payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the unique_identifier or data attributes
                are not defined.
        """
        local_stream = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "invalid payload missing the unique identifier attribute"
            )

        if self._data:
            self._data.write(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self._iv_counter_nonce:
            self._iv_counter_nonce.write(
                local_stream,
                kmip_version=kmip_version
            )

        if kmip_version >= enums.KMIPVersion.KMIP_1_4:
            if self._auth_tag:
                self._auth_tag.write(
                    local_stream,
                    kmip_version=kmip_version
                )

        self.length = local_stream.length()
        super(EncryptResponsePayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

    def __eq__(self, other):
        if isinstance(other, EncryptResponsePayload):
            if self.unique_identifier != other.unique_identifier:
                return False
            elif self.data != other.data:
                return False
            elif self.iv_counter_nonce != other.iv_counter_nonce:
                return False
            elif self.auth_tag != other.auth_tag:
                return False
            else:
                return True
        else:
            return NotImplemented

    def __ne__(self, other):
        if isinstance(other, EncryptResponsePayload):
            return not (self == other)
        else:
            return NotImplemented

    def __repr__(self):
        args = ", ".join([
            "unique_identifier='{0}'".format(self.unique_identifier),
            "data={0}".format(self.data),
            "iv_counter_nonce={0}".format(self.iv_counter_nonce),
            "auth_tag={0}".format(self.auth_tag)
        ])
        return "EncryptResponsePayload({0})".format(args)

    def __str__(self):
        return str({
            'unique_identifier': self.unique_identifier,
            'data': self.data,
            'iv_counter_nonce': self.iv_counter_nonce,
            'auth_tag': self.auth_tag
        })