Best Python code snippet using autotest_python
sms_encrypt.py
Source:sms_encrypt.py
...242 for entry storage into the database.243"""244def encrypt_msg(entry, user, to):245 server_publickey = get_server_keys("public")246 pk = get_user_keys("private", user, 0)247 msg = entry248 hash = SHA256.new(msg)249 signer = PKCS1_PSS.new(pk)250 signature = signer.sign(hash)251 signature = base64.b64encode(signature)252 shared_key = get_user_keys("private", user, BS)253 raw = pad(msg)254 iv = Random.new().read(AES.block_size)255 aes = AES.new(shared_key, AES.MODE_CBC, iv)256 cipher = base64.b64encode(iv + aes.encrypt(raw))257 cipher = server_publickey.encrypt(cipher, BS)258 ##decrypt_msg(cipher, user, signature, user)259 return (signature, cipher)260 261"""262 Function is used when the view page is requested. 263 This encrypts takes the decrypted database message 264 and encrypts with the requester's public key and a 265 digital signature with the server's private key.266"""267def encrypt_msg_for_requester(entry, user):268 server_privatekey = get_server_keys("private")269 user_publickey = get_user_keys("public", user, 0)270 msg = entry271 hash = SHA256.new(msg)272 signer = PKCS1_PSS.new(server_privatekey)273 signature = signer.sign(hash)274 signature = base64.b64encode(signature)275 276 msg = base64.b64encode(msg)277 cipher = user_publickey.encrypt(msg, BS)278 return (signature, cipher)279"""280 This is used for the test decryption page for testing281 validation. This reverses the requester encryption.282"""283def decrypt_encrypt_msg_for_requester(msg, ds, user):284 try:285 server_publickey = get_server_keys("public")286 user_privatekey = get_user_keys("private", user, 0)287 288 # decrypt the msg289 decrypt_msg = user_privatekey.decrypt(msg)290 decrypt_msg = base64.b64decode(decrypt_msg)291 # compare to the digital signature 292 hash = SHA256.new(decrypt_msg)293 verifier = PKCS1_PSS.new(server_publickey)294 ds = base64.b64decode(ds)295 if verifier.verify(hash, ds):296 ds = base64.b64encode(ds)297 else:298 ds = decrypt_msg = "ERROR: Invalid Signature, msg cannot be verified!"299 except: 300 ds = decrypt_msg = "ERROR: Cannot decode message."301 #traceback.print_exc()302 return (ds, decrypt_msg)303"""304 decrypt_msg(): Allows users to decrypt and 305 verify the validity of message. 306"""307def decrypt_msg(cipher, user, signature, req_user):308 server_privatekey = get_server_keys("private")309 rsa_decrypt = server_privatekey.decrypt(cipher)310 try:311 rsa_decrypt = base64.b64decode(rsa_decrypt)312 shared_key = get_user_keys("private", user, BS)313 iv = rsa_decrypt[:AES.block_size]314 aes = AES.new(shared_key, AES.MODE_CBC, iv)315 msg = unpad(aes.decrypt(rsa_decrypt[AES.block_size:])).decode()316 except:317 # Occurs when shared_key corrupted. 318 ds = "ERROR: Cannot decode message."319 return (ds, ds)320 if verify_signature(user, msg, signature):321 (ds, msg) = encrypt_msg_for_requester(msg, req_user)322 return (ds, msg)323 else: 324 ds = "ERROR: Invalid signature, msg will not be returned."325 return (ds, ds)326"""327 verify_signature(): This function allows verification of 328 a msg of a hash stored in the database for msg 329 authentication.330"""331def verify_signature(user, msg, db_signature):332 pk = get_user_keys("public", user, 0)333 hash = SHA256.new(msg)334 verifier = PKCS1_PSS.new(pk)335 db_signature = base64.b64decode(db_signature)336 if verifier.verify(hash, db_signature):337 return True338 return False339"""340 get_server_keys(): Gets either the public/private key341 for this crypto.com system. 342 User passes in "private" or "public" for keytype value343 to retrive.344"""345def get_server_keys(keytype):346 if keytype == "private":347 server_pk = os.path.join(KEYDIR_CRYPTO, CRYPTO_PRIVATE_KEY)348 else:349 server_pk = os.path.join(KEYDIR_CRYPTO, CRYPTO_PUBLIC_KEY)350 key = open(server_pk, "r").read()351 server_publickey = RSA.importKey(key)352 return server_publickey353 354"""355 get_user_keys(): Get the specific user's asymmetric 356 key.357"""358def get_user_keys(keytype, user, bytelim):359 if keytype == "private":360 keyname = os.path.join(KEYDIR_PRIVATE, user + "_privatekey")361 else:362 keyname = os.path.join(KEYDIR_PUBLIC, user + "_publickey")363 # Return if only want a portion of key364 if bytelim:365 key = open(keyname, "r").read(bytelim)366 return key367 keypair = open(keyname, "r").read()368 pk = RSA.importKey(keypair)369 return pk370"""371 writefile(): Helper function to write text to a file.372"""...
github_tests.py
Source:github_tests.py
...125 # test invalid string126 self.assertRaises(github.InvalidKey,127 github.get_key_fingerprint,128 self.public_keys['not_a_key'])129 def test_get_user_keys(self):130 """131 Test getting user keys132 """133 # existing user with key134 self.assertEquals(github.get_user_keys('good-user'),135 [self.public_keys['rsa']])136 # non existing user137 self.assertRaises(github.GithubRequestException, github.get_user_keys,138 'bad-user')139 # existing user with no keys140 self.assertEquals([], github.get_user_keys('good-no-keys'))141 # existing user with multiple keys filtered by fingerprint142 self.assertEquals(143 [self.public_keys['rsa']],144 github.get_user_keys(145 'good-all-keys',146 fingerprints=[self.public_keys['rsa']['fingerprint']]))147 # existing user with single key and multiple fingerprints148 # in the fingerprint list149 self.assertEquals(150 [self.public_keys['rsa']],151 github.get_user_keys(152 'good-user',153 fingerprints=[self.public_keys['rsa']['fingerprint'],154 self.public_keys['rsa']['fingerprint']]))155 def test_get_user_keys_translated_to_slug(self):156 """157 Test that user names are correctly translated to slugs158 """159 # existing user with key160 self.assertEquals(github.get_user_keys('Slug_user'),161 [self.public_keys['rsa']])162 # existing user with key163 self.assertEquals(github.get_user_keys('Slug User'),164 [self.public_keys['rsa']])165class GithubPaginatedContentTest(unittest.TestCase):166 def setUp(self):167 self.get_patcher = mock.patch('bootstrap_salt.deploy_lib.github.requests.get')168 self.get = self.get_patcher.start()169 def tearDown(self):170 self.get_patcher.stop()171 def _set_github_response(self, **kwargs):172 self.get.return_value = self._make_result(**kwargs)173 def _make_result(self, status_code=200, links=None, json=None):174 result = mock.Mock(name='Response')175 result.status_code = status_code176 result.links = links or {}177 result.json.return_value = json or []...
test_key_store.py
Source:test_key_store.py
...42 mock_encrypted_file.dump.assert_called_with(43 master_key.encode('utf-8'),44 mock_pickle.dumps.return_value,45 mock_open.return_value.__enter__.return_value)46 assert_valid_status(lambda: store.get_user_keys('local'))47def test_unlock(48 faker: Faker,49 endpoints: Endpoint,50 mock_open: MagicMock,51 mock_encrypted_file: MagicMock,52 mock_pickle: MagicMock):53 path = faker.file_path()54 master_key = faker.password()55 mock_keys = mock_pickle.loads.return_value56 store = KeyStore(path)57 store.unlock(master_key)58 mock_open.assert_called_once_with(path, 'rb')59 mock_encrypted_file.load.assert_called_once_with(60 master_key.encode('utf-8'),61 mock_open.return_value.__enter__.return_value)62 mock_pickle.loads.assert_called_once_with(mock_encrypted_file.load.return_value)63 assert_valid_status(lambda: store.get_user_keys('local'))64 # keys loaded65 assert store.get_user_keys('local') == mock_keys.local66 # master key stored67 store.set_user_keys('local', [])68 mock_encrypted_file.dump.assert_called_once_with(69 master_key.encode('utf-8'),70 mock_pickle.dumps.return_value,71 mock_open.return_value.__enter__.return_value)72def test_unlock_status_change(faker: Faker):73 path = faker.file_path()74 master_key = faker.password()75 store = KeyStore(path)76 store.unlock(master_key)77 assert_invalid_status(lambda: store.initialize(master_key))78 assert_invalid_status(lambda: store.unlock(master_key))79 assert_valid_status(lambda: store.get_user_keys('local'))80def test_lock_status_change(faker: Faker):81 path = faker.file_path()82 master_key = faker.password()83 store = KeyStore(path)84 store.initialize(master_key)85 store.lock()86 assert_invalid_status(lambda: store.get_user_keys('local'))87def test_status_check_locked(faker: Faker, endpoints: Tuple[Endpoint, Endpoint]):88 path = faker.file_path()89 store = KeyStore(path)90 assert_invalid_status(lambda: store.get_email_credential('smtp'))91 assert_invalid_status(lambda: store.set_email_credential('smtp', None))92 assert_invalid_status(lambda: store.get_user_keys('local'))93 assert_invalid_status(lambda: store.set_user_keys('local', []))94 assert_invalid_status(lambda: store.get_user_key('local', endpoints))95 assert_invalid_status(lambda: store.set_master_key('key'))96def test_set_master_key(97 faker: Faker,98 mock_open: MagicMock,99 mock_encrypted_file: MagicMock,100 mock_pickle: MagicMock):101 path = faker.file_path()102 master_key = faker.password()103 store = KeyStore(path)104 store.initialize('')105 store.set_master_key(master_key)106 mock_encrypted_file.dump.assert_called_with(107 master_key.encode('utf-8'),108 mock_pickle.dumps.return_value,109 mock_open.return_value.__enter__.return_value)110def test_email_credential(faker: Faker, mock_encrypted_file: MagicMock):111 path = faker.file_path()112 smtp = MagicMock()113 imap = MagicMock()114 store = KeyStore(path)115 store.initialize('')116 store.set_email_credential('smtp', smtp)117 store.set_email_credential('imap', imap)118 assert store.get_email_credential('smtp') == smtp119 assert store.get_email_credential('imap') == imap120 assert store.get_email_credential('pop3') is None121 mock_encrypted_file.dump.assert_called()122def test_user_keys(faker: Faker, mock_encrypted_file: MagicMock):123 path = faker.file_path()124 local = MagicMock()125 remote = MagicMock()126 store = KeyStore(path)127 store.initialize('')128 store.set_user_keys('local', local)129 store.set_user_keys('remote', remote)130 assert store.get_user_keys('local') == local131 assert store.get_user_keys('remote') == remote132 with pytest.raises(Exception) as execinfo:133 assert store.get_user_keys('invalid')134 assert execinfo.match('invalid type')135 mock_encrypted_file.dump.assert_called()136def test_socket_context(faker: Faker, mock_encrypted_file: MagicMock):137 path = faker.file_path()138 store = KeyStore(path)139 dump = faker.binary(111)140 endpoints = tuple(Endpoint(faker.email(), faker.uuid4()) for _ in range(2))141 store.initialize('')142 store.set_socket_context(endpoints, dump)143 assert store.get_socket_context(endpoints) == dump144 assert store.get_socket_context(tuple(reversed(endpoints))) is None145 mock_encrypted_file.dump.assert_called()146def test_socket_contexts(faker: Faker, mock_encrypted_file: MagicMock):147 path = faker.file_path()...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!