How to use wrapping method in localstack

Best Python code snippet using localstack_python

wrapping_keys.py

Source:wrapping_keys.py Github

copy

Full Screen

1# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You4# may not use this file except in compliance with the License. A copy of5# the License is located at6#7# http://aws.amazon.com/apache2.0/8#9# or in the "license" file accompanying this file. This file is10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF11# ANY KIND, either express or implied. See the License for the specific12# language governing permissions and limitations under the License.13"""Contains wrapping key primitives."""14import logging15import os16from cryptography.hazmat.backends import default_backend17from cryptography.hazmat.primitives import serialization18from ...exceptions import IncorrectMasterKeyError, InvalidDataKeyError19from ...identifiers import EncryptionKeyType, EncryptionType20from ..formatting.encryption_context import serialize_encryption_context21from ..structures import EncryptedData22from .data_keys import derive_data_encryption_key23from .encryption import decrypt, encrypt24_LOGGER = logging.getLogger(__name__)25class WrappingKey(object):26 """Creates a wrapping encryption key object to encrypt and decrypt data keys.27 For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects.28 :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key29 :type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm30 :param bytes wrapping_key: Encryption key with which to wrap plaintext_data_key31 :param wrapping_key_type: Type of encryption key with which to wrap plaintext_data_key32 :type wrapping_key_type: aws_encryption_sdk.identifiers.EncryptionKeyType33 :param bytes password: Password to decrypt wrapping_key (optional, currently only relevant for RSA)34 """35 def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None):36 """Prepares initial values."""37 self.wrapping_algorithm = wrapping_algorithm38 self.wrapping_key_type = wrapping_key_type39 if wrapping_key_type is EncryptionKeyType.PRIVATE:40 self._wrapping_key = serialization.load_pem_private_key(41 data=wrapping_key, password=password, backend=default_backend()42 )43 elif wrapping_key_type is EncryptionKeyType.PUBLIC:44 self._wrapping_key = serialization.load_pem_public_key(data=wrapping_key, backend=default_backend())45 elif wrapping_key_type is EncryptionKeyType.SYMMETRIC:46 self._wrapping_key = wrapping_key47 self._derived_wrapping_key = derive_data_encryption_key(48 source_key=self._wrapping_key, algorithm=self.wrapping_algorithm.algorithm, message_id=None49 )50 else:51 raise InvalidDataKeyError("Invalid wrapping_key_type: {}".format(wrapping_key_type))52 def encrypt(self, plaintext_data_key, encryption_context):53 """Encrypts a data key using a direct wrapping key.54 :param bytes plaintext_data_key: Data key to encrypt55 :param dict encryption_context: Encryption context to use in encryption56 :returns: Deserialized object containing encrypted key57 :rtype: aws_encryption_sdk.internal.structures.EncryptedData58 """59 if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:60 if self.wrapping_key_type is EncryptionKeyType.PRIVATE:61 encrypted_key = self._wrapping_key.public_key().encrypt(62 plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding63 )64 else:65 encrypted_key = self._wrapping_key.encrypt(66 plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding67 )68 return EncryptedData(iv=None, ciphertext=encrypted_key, tag=None)69 serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)70 iv = os.urandom(self.wrapping_algorithm.algorithm.iv_len)71 return encrypt(72 algorithm=self.wrapping_algorithm.algorithm,73 key=self._derived_wrapping_key,74 plaintext=plaintext_data_key,75 associated_data=serialized_encryption_context,76 iv=iv,77 )78 def decrypt(self, encrypted_wrapped_data_key, encryption_context):79 """Decrypts a wrapped, encrypted, data key.80 :param encrypted_wrapped_data_key: Encrypted, wrapped, data key81 :type encrypted_wrapped_data_key: aws_encryption_sdk.internal.structures.EncryptedData82 :param dict encryption_context: Encryption context to use in decryption83 :returns: Plaintext of data key84 :rtype: bytes85 """86 if self.wrapping_key_type is EncryptionKeyType.PUBLIC:87 raise IncorrectMasterKeyError("Public key cannot decrypt")88 if self.wrapping_key_type is EncryptionKeyType.PRIVATE:89 return self._wrapping_key.decrypt(90 ciphertext=encrypted_wrapped_data_key.ciphertext, padding=self.wrapping_algorithm.padding91 )92 serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)93 return decrypt(94 algorithm=self.wrapping_algorithm.algorithm,95 key=self._derived_wrapping_key,96 encrypted_data=encrypted_wrapped_data_key,97 associated_data=serialized_encryption_context,...

Full Screen

Full Screen

keywrap.py

Source:keywrap.py Github

copy

Full Screen

1# This file is dual licensed under the terms of the Apache License, Version2# 2.0, and the BSD License. See the LICENSE file in the root of this repository3# for complete details.4from __future__ import absolute_import, division, print_function5import struct6from cryptography.hazmat.primitives.ciphers import Cipher7from cryptography.hazmat.primitives.ciphers.algorithms import AES8from cryptography.hazmat.primitives.ciphers.modes import ECB9from cryptography.hazmat.primitives.constant_time import bytes_eq10def _wrap_core(wrapping_key, a, r, backend):11 # RFC 3394 Key Wrap - 2.2.1 (index method)12 encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()13 n = len(r)14 for j in range(6):15 for i in range(n):16 # every encryption operation is a discrete 16 byte chunk (because17 # AES has a 128-bit block size) and since we're using ECB it is18 # safe to reuse the encryptor for the entire operation19 b = encryptor.update(a + r[i])20 # pack/unpack are safe as these are always 64-bit chunks21 a = struct.pack(22 ">Q", struct.unpack(">Q", b[:8])[0] ^ ((n * j) + i + 1)23 )24 r[i] = b[-8:]25 assert encryptor.finalize() == b""26 return a + b"".join(r)27def aes_key_wrap(wrapping_key, key_to_wrap, backend):28 if len(wrapping_key) not in [16, 24, 32]:29 raise ValueError("The wrapping key must be a valid AES key length")30 if len(key_to_wrap) < 16:31 raise ValueError("The key to wrap must be at least 16 bytes")32 if len(key_to_wrap) % 8 != 0:33 raise ValueError("The key to wrap must be a multiple of 8 bytes")34 a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"35 r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)]36 return _wrap_core(wrapping_key, a, r, backend)37def _unwrap_core(wrapping_key, a, r, backend):38 # Implement RFC 3394 Key Unwrap - 2.2.2 (index method)39 decryptor = Cipher(AES(wrapping_key), ECB(), backend).decryptor()40 n = len(r)41 for j in reversed(range(6)):42 for i in reversed(range(n)):43 # pack/unpack are safe as these are always 64-bit chunks44 atr = struct.pack(45 ">Q", struct.unpack(">Q", a)[0] ^ ((n * j) + i + 1)46 ) + r[i]47 # every decryption operation is a discrete 16 byte chunk so48 # it is safe to reuse the decryptor for the entire operation49 b = decryptor.update(atr)50 a = b[:8]51 r[i] = b[-8:]52 assert decryptor.finalize() == b""53 return a, r54def aes_key_wrap_with_padding(wrapping_key, key_to_wrap, backend):55 if len(wrapping_key) not in [16, 24, 32]:56 raise ValueError("The wrapping key must be a valid AES key length")57 aiv = b"\xA6\x59\x59\xA6" + struct.pack(">i", len(key_to_wrap))58 # pad the key to wrap if necessary59 pad = (8 - (len(key_to_wrap) % 8)) % 860 key_to_wrap = key_to_wrap + b"\x00" * pad61 if len(key_to_wrap) == 8:62 # RFC 5649 - 4.1 - exactly 8 octets after padding63 encryptor = Cipher(AES(wrapping_key), ECB(), backend).encryptor()64 b = encryptor.update(aiv + key_to_wrap)65 assert encryptor.finalize() == b""66 return b67 else:68 r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)]69 return _wrap_core(wrapping_key, aiv, r, backend)70def aes_key_unwrap_with_padding(wrapping_key, wrapped_key, backend):71 if len(wrapped_key) < 16:72 raise InvalidUnwrap("Must be at least 16 bytes")73 if len(wrapping_key) not in [16, 24, 32]:74 raise ValueError("The wrapping key must be a valid AES key length")75 if len(wrapped_key) == 16:76 # RFC 5649 - 4.2 - exactly two 64-bit blocks77 decryptor = Cipher(AES(wrapping_key), ECB(), backend).decryptor()78 b = decryptor.update(wrapped_key)79 assert decryptor.finalize() == b""80 a = b[:8]81 data = b[8:]82 n = 183 else:84 r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)]85 encrypted_aiv = r.pop(0)86 n = len(r)87 a, r = _unwrap_core(wrapping_key, encrypted_aiv, r, backend)88 data = b"".join(r)89 # 1) Check that MSB(32,A) = A65959A6.90 # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let91 # MLI = LSB(32,A).92 # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of93 # the output data are zero.94 (mli,) = struct.unpack(">I", a[4:])95 b = (8 * n) - mli96 if (97 not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") or not98 8 * (n - 1) < mli <= 8 * n or (99 b != 0 and not bytes_eq(data[-b:], b"\x00" * b)100 )101 ):102 raise InvalidUnwrap()103 if b == 0:104 return data105 else:106 return data[:-b]107def aes_key_unwrap(wrapping_key, wrapped_key, backend):108 if len(wrapped_key) < 24:109 raise InvalidUnwrap("Must be at least 24 bytes")110 if len(wrapped_key) % 8 != 0:111 raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes")112 if len(wrapping_key) not in [16, 24, 32]:113 raise ValueError("The wrapping key must be a valid AES key length")114 aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"115 r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)]116 a = r.pop(0)117 a, r = _unwrap_core(wrapping_key, a, r, backend)118 if not bytes_eq(a, aiv):119 raise InvalidUnwrap()120 return b"".join(r)121class InvalidUnwrap(Exception):...

Full Screen

Full Screen

example.py

Source:example.py Github

copy

Full Screen

1import time2def sample(a, b):3 """4 Test case 15 """6 for _ in range(2):7 print("yes \n ")8 x = 89 y = 1410 muted_variable_name = "This variable should be muted in the video output"11 x = a + b12 y = x * 213 print('Math test: ' + str(y))14 friends = ['john', 'pat', 'gary', 'michael']15 for i in range(len(friends)):16 print("iteration {iteration} is {name}".format(iteration=i, name=friends[i]))17 muted_variable_name = "I, the muted variable, have changed"18 fl = 1.23419 a_string = "this is a string"20 print(a_string)21 numbers = [45, 67, 90, 2, 78]22 for j in range(len(numbers)):23 print("number: {}".format(numbers[j]))24 num_list = [100, 200, 700, 800]25 num_list.remove(200)26 dict_test = dict()27 dict_test["one"] = 2 # text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test text wrapping test28 dict_test = {"one": 1, "two": 2}29 print("Test 2, test 3, Test the test?")30 dict_test = {"one": {"yes": "yes"}, "two": 2}31 dict_test["one"]["yes"] = 032def nested_loop(a):33 """34 Test case 235 """36 test_a = a37 num_list = [500, 600, 700]38 alpha_list = ['x', 'y', 'z']39 for number in num_list:40 print(number)41 time.sleep(1)42 for letter in alpha_list:43 print(letter)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful