[text] sys

Viewer

  1. 1.CEASER: 
  2.  
  3. #include <iostream>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. bool isAlpha(char ch){
  9.     return isalpha(ch);
  10. }
  11.  
  12. char encryptChar(char c, int shift){
  13.     if(isupper(c)){
  14.         c = (((c-'A')+shift)%26)+'A';
  15.     }
  16.     else if(islower(c)){
  17.         c = (((c-'a')+shift)%26)+'a';
  18.     }
  19.     else{
  20.         return c;
  21.     }
  22.     return c;
  23. }
  24.  
  25. string encryptCaesar(string c, int shift){
  26.     string encryptedtext;
  27.     for(char ch:c){
  28.         encryptedtext+=encryptChar(ch, shift);
  29.     }
  30.     return encryptedtext;
  31. }
  32.  
  33. int main()
  34. {
  35.     string text;
  36.     int n;
  37.     cout<<"Enter text to be encrypted: ";
  38.     getline(cin,text);
  39.     cout<<"Enter key value: ";
  40.     cin>>n;
  41.     cout<<encryptCaesar(text, n);
  42.  
  43.     return 0;
  44. }
  45.  
  46. 2. HILL: 
  47.  
  48. Hill Cipher
  49. #include <iostream>
  50. #include <vector>
  51. #include <cmath>
  52.  
  53. using namespace std;
  54.  
  55. const int MOD = 26; // modulo for encryption
  56.  
  57. // Function to convert character to integer (A -> 0, B -> 1, ..., Z -> 25)
  58. int charToInt(char ch) {
  59.     return ch - 'A';
  60. }
  61.  
  62. // Function to convert integer to character (0 -> A, 1 -> B, ..., 25 -> Z)
  63. char intToChar(int n) {
  64.     return 'A' + n;
  65. }
  66.  
  67. // Function to compute the modular inverse of a number a mod m
  68. int modInverse(int a, int m) {
  69.     a = a % m;
  70.     for (int x = 1; x < m; x++) {
  71.         if ((a * x) % m == 1) {
  72.             return x;
  73.         }
  74.     }
  75.     return -1; // modular inverse doesn't exist
  76. }
  77.  
  78. // Function to encrypt a plaintext using the Hill cipher
  79. string hillEncrypt(const string& plaintext, const vector<vector<int>>& key) {
  80.     int n = key.size();
  81.     string ciphertext = "";
  82.     
  83.     // Padding the plaintext if necessary
  84.     string paddedPlaintext = plaintext;
  85.     int padding = n - (plaintext.length() % n);
  86.     if (padding != n) {
  87.         paddedPlaintext += string(padding, 'X');
  88.     }
  89.  
  90.     // Encryption
  91.     for (int i = 0; i < paddedPlaintext.length(); i += n) {
  92.         vector<int> block(n);
  93.         for (int j = 0; j < n; j++) {
  94.             block[j] = charToInt(paddedPlaintext[i + j]);
  95.         }
  96.  
  97.         for (int j = 0; j < n; j++) {
  98.             int sum = 0;
  99.             for (int k = 0; k < n; k++) {
  100.                 sum += key[j][k] * block[k];
  101.             }
  102.             ciphertext += intToChar(sum % MOD);
  103.         }
  104.     }
  105.  
  106.     return ciphertext;
  107. }
  108.  
  109. int main() {
  110.     // Example key matrix
  111.     vector<vector<int>> key = {{6, 24, 1},
  112.                                 {13, 16, 10},
  113.                                 {20, 17, 15}};
  114.  
  115.     // Example plaintext
  116.     string plaintext = "HELLO";
  117.  
  118.     // Encrypt the plaintext
  119.     string ciphertext = hillEncrypt(plaintext, key);
  120.     
  121.     cout << "Plaintext: " << plaintext << endl;
  122.     cout << "Ciphertext: " << ciphertext << endl;
  123.  
  124.     return 0;
  125. }
  126.  
  127. 3. Playfair/wheatstone cipher:
  128. #include <iostream>
  129. #include <string>
  130. #include <cctype>
  131. #include <vector>
  132.  
  133. using namespace std;
  134.  
  135. // Function to get the position of a character in the key table
  136. void getPos(char ch, int& row, int& col, const char table[][5]) {
  137.   for (int i = 0; i < 5; i++) {
  138.     for (int j = 0; j < 5; j++) {
  139.       if (table[i][j] == toupper(ch)) {
  140.         row = i;
  141.         col = j;
  142.         return;
  143.       }
  144.     }
  145.   }
  146. }
  147.  
  148. // Function to check if a character is unique in the key
  149. bool isUniqueInKey(char ch, const string& key) {
  150.   for (char keyChar : key) {
  151.     if (toupper(ch) == toupper(keyChar)) {
  152.       return false;
  153.     }
  154.   }
  155.   return true;
  156. }
  157.  
  158. // Function to create the Playfair key table
  159. void createTable(const string& key, char table[][5]) {
  160.   // Fill the table with characters from the key (uppercase, no duplicates)
  161.   int index = 0;
  162.   for (char ch : key) {
  163.     ch = toupper(ch);
  164.     if (isalpha(ch) && ch != 'J') {
  165.       table[index / 5][index % 5] = ch;
  166.       index++;
  167.     }
  168.   }
  169.  
  170.   // Fill the remaining table with the rest of the alphabets (excluding J)
  171.   for (char ch = 'A'; ch <= 'Z'; ch++) {
  172.     if (ch != 'J' && isUniqueInKey(ch, key)) {
  173.       table[index / 5][index % 5] = ch;
  174.       index++;
  175.     }
  176.   }
  177. }
  178.  
  179. // Function to encrypt a pair of characters using Playfair cipher
  180. string encryptPair(char ch1, char ch2, const char table[][5]) {
  181.   int row1, col1, row2, col2;
  182.  
  183.   // Get positions of characters in the table
  184.   getPos(ch1, row1, col1, table);
  185.   getPos(ch2, row2, col2, table);
  186.  
  187.   // Handle different cases based on positions
  188.   string encryptedPair;
  189.   if (row1 == row2) {
  190.     // Same row, shift columns (cyclic)
  191.     encryptedPair += table[row1][(col1 + 1) % 5];
  192.     encryptedPair += table[row2][(col2 + 1) % 5];
  193.   } else if (col1 == col2) {
  194.     // Same column, shift rows (cyclic)
  195.     encryptedPair += table[(row1 + 1) % 5][col1];
  196.     encryptedPair += table[(row2 + 1) % 5][col2];
  197.   } else {
  198.     // Different row and column, swap positions within the rectangle
  199.     encryptedPair += table[row1][col2];
  200.     encryptedPair += table[row2][col1];
  201.   }
  202.  
  203.   return encryptedPair;
  204. }
  205.  
  206. string encryptPlayfair(const string& text, const string& key) {
  207.   string encryptedText;
  208.   char table[5][5];
  209.  
  210.   // Create the Playfair key table
  211.   createTable(key, table);
  212.  
  213.   // Handle even number of characters (add 'X')
  214.   string formattedText = text;
  215.   if (text.length() % 2 != 0) {
  216.     formattedText += 'X';
  217.   }
  218.  
  219.   // Process each pair of characters
  220.   for (int i = 0; i < formattedText.length(); i += 2) {
  221.     encryptedText += encryptPair(formattedText[i], formattedText[i + 1], table);
  222.   }
  223.  
  224.   return encryptedText;
  225. }
  226.  
  227. int main() {
  228.   string text, key;
  229.  
  230.   cout << "Enter the text to be encrypted: ";
  231.   getline(cin, text);
  232.  
  233.   cout << "Enter the key: ";
  234.   getline(cin, key);
  235.  
  236.   string encryptedText = encryptPlayfair(text, key);
  237.   cout << "The encrypted text is: " << encryptedText << endl;
  238.  
  239.   return 0;
  240. }
  241.  
  242.  
  243. 5. Vernam Cipher – 
  244.  
  245. def vernam_cipher(text, key):
  246.     # Ensure the length of the key matches the length of the text
  247.     if len(text) != len(key):
  248.         raise ValueError("Key length must be equal to the length of the text")
  249.  
  250.     result = ""
  251.     for i in range(len(text)):
  252.         # XOR each character of the text with the corresponding character of the key
  253.         # Convert characters to ASCII values for bitwise operations
  254.         encrypted_char = chr(ord(text[i]) ^ ord(key[i]))
  255.         result += encrypted_char
  256.     return result
  257.  
  258. # Example usage
  259. text = "Hello"
  260. key = "Secret"
  261. encrypted_text = vernam_cipher(text, key)
  262. print("Encrypted:", encrypted_text)
  263.  
  264. decrypted_text = vernam_cipher(encrypted_text, key)
  265. print("Decrypted:", decrypted_text)
  266.  
  267. RAIL FENCE – 
  268.  
  269. def rail_fence_encrypt(text, rails):
  270.     # Create an empty list to store the rails
  271.     fence = [[] for _ in range(rails)]
  272.     # Initialize variables for tracking the current rail and direction
  273.     rail = 0
  274.     direction = 1
  275.  
  276.     # Place each character of the text on the appropriate rail
  277.     for char in text:
  278.         fence[rail].append(char)
  279.         rail += direction
  280.         # Reverse direction when reaching the top or bottom rail
  281.         if rail == 0 or rail == rails - 1:
  282.             direction *= -1
  283.  
  284.     # Concatenate the characters from each rail to form the encrypted text
  285.     encrypted_text = ''.join(''.join(rail) for rail in fence)
  286.     return encrypted_text
  287.  
  288. def rail_fence_decrypt(text, rails):
  289.     # Create an empty list to store the rails
  290.     fence = [[] for _ in range(rails)]
  291.     # Initialize variables for tracking the current rail and direction
  292.     rail = 0
  293.     direction = 1
  294.  
  295.     # Calculate the length of each rail based on the pattern
  296.     cycle = 2 * (rails - 1)
  297.     full_cycles = len(text) // cycle
  298.     remainder = len(text) % cycle
  299.  
  300.     # Place markers on the appropriate rails to indicate the zigzag pattern
  301.     markers = [rail] * (full_cycles * 2) + [0] * (remainder if remainder <= rails else rails - 1 - remainder + rails) + [rail] * (full_cycles * 2)
  302.  
  303.     # Place each character of the text on the appropriate rail
  304.     for i, char in enumerate(text):
  305.         fence[markers[i]].append(char)
  306.  
  307.     # Concatenate the characters from each rail to form the decrypted text
  308.     decrypted_text = ''.join(''.join(rail) for rail in fence)
  309.     return decrypted_text
  310.  
  311. # Example usage
  312. text = "HELLO"
  313. rails = 3
  314. encrypted_text = rail_fence_encrypt(text, rails)
  315. print("Encrypted:", encrypted_text)
  316.  
  317. decrypted_text = rail_fence_decrypt(encrypted_text, rails)
  318. print("Decrypted:", decrypted_text)
  319.  
  320. 6. ROW COLUMN – 
  321.  
  322. def encrypt(text, key):
  323.     # Calculate the number of columns based on the key length
  324.     num_columns = len(key)
  325.     # Calculate the number of rows needed to accommodate the text
  326.     num_rows = (len(text) + num_columns - 1) // num_columns
  327.     # Pad the text if necessary
  328.     padded_text = text.ljust(num_rows * num_columns)
  329.  
  330.     # Construct the grid based on the number of rows and columns
  331.     grid = [list(padded_text[i:i+num_columns]) for i in range(0, len(padded_text), num_columns)]
  332.     
  333.     # Create a list to store the encrypted columns based on the key order
  334.     encrypted_columns = [grid[j] for j in key]
  335.  
  336.     # Construct the encrypted text by reading off the columns
  337.     encrypted_text = ''.join(''.join(column) for column in encrypted_columns)
  338.     return encrypted_text
  339.  
  340. def decrypt(text, key):
  341.     # Calculate the number of columns based on the key length
  342.     num_columns = len(key)
  343.     # Calculate the number of rows needed to accommodate the text
  344.     num_rows = (len(text) + num_columns - 1) // num_columns
  345.     
  346.     # Construct the grid based on the number of rows and columns
  347.     grid = [list(text[i:i+num_rows]) for i in range(0, len(text), num_rows)]
  348.     
  349.     # Create a list to store the decrypted columns based on the key order
  350.     decrypted_columns = [grid[j] for j in sorted(key)]
  351.  
  352.     # Construct the decrypted text by reading off the columns
  353.     decrypted_text = ''.join(''.join(column) for column in zip(*decrypted_columns))
  354.     return decrypted_text
  355.  
  356. # Example usage
  357. text = "HELLO"
  358. key = [2, 1, 3]  # Example key
  359. encrypted_text = encrypt(text, key)
  360. print("Encrypted:", encrypted_text)
  361.  
  362. decrypted_text = decrypt(encrypted_text, key)
  363. print("Decrypted:", decrypted_text)
  364.  
  365.  
  366.  
  367.  
  368.  
  369. ----------------------------------------------------------------------
  370.  
  371. SSL:
  372.  
  373. SERVER: 
  374.  
  375. import socket 
  376. import ssl 
  377. import tempfile 
  378. import os 
  379.  
  380. HOST = '127.0.0.1' 
  381. PORT = 12345 
  382.  
  383. def generate_self_signed_cert(): 
  384.     certfile = tempfile.NamedTemporaryFile(delete=False) 
  385.     keyfile = tempfile.NamedTemporaryFile(delete=False) 
  386.  
  387.     # Generate a self-signed certificate 
  388.     os.system(f'openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout {keyfile.name} -out {certfile.name} -subj "/CN=localhost"') 
  389.  
  390.     return certfile.name, keyfile.name 
  391.  
  392. def main(): 
  393.     try:
  394.         # Generate self-signed certificate and key 
  395.         certfile, keyfile = generate_self_signed_cert() 
  396.  
  397.         # Create a TCP/IP socket 
  398.         server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
  399.  
  400.         # Bind the socket to the port 
  401.         server_socket.bind((HOST, PORT)) 
  402.  
  403.         # Listen for incoming connections 
  404.         server_socket.listen(1) 
  405.         print(f"Server listening on {HOST}:{PORT}...") 
  406.  
  407.         while True: 
  408.             # Accept incoming connections 
  409.             connection, client_address = server_socket.accept() 
  410.             print(f"Connection from {client_address}") 
  411.  
  412.             # Wrap the connection with SSL 
  413.             ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) 
  414.             ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) 
  415.             ssl_connection = ssl_context.wrap_socket(connection, server_side=True) 
  416.  
  417.             try: 
  418.                 while True: 
  419.                     # Receive data from the client 
  420.                     data = ssl_connection.recv(1024) 
  421.                     if data: 
  422.                         print(f"Received: {data.decode()}") 
  423.                     else: 
  424.                         break 
  425.             finally: 
  426.                 # Close the connection 
  427.                 ssl_connection.close() 
  428.     except Exception as e:
  429.         print(f"An error occurred: {e}")
  430.  
  431. if __name__ == "__main__": 
  432.     main()
  433.  
  434. CLIENT: 
  435.  
  436. import socket 
  437. import ssl 
  438.  
  439. HOST = '127.0.0.1' 
  440. PORT = 12345 
  441.  
  442. def main(): 
  443.     try:
  444.         # Create a TCP/IP socket 
  445.         client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
  446.  
  447.         # Wrap the socket with SSL, ignoring certificate verification errors 
  448.         ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) 
  449.         ssl_context.check_hostname = False 
  450.         ssl_context.verify_mode = ssl.CERT_NONE 
  451.         ssl_socket = ssl_context.wrap_socket(client_socket, server_hostname=HOST) 
  452.  
  453.         try:
  454.             # Connect to the server 
  455.             ssl_socket.connect((HOST, PORT)) 
  456.  
  457.             # Send data to the server 
  458.             message = "21BCE1370 Vrinda" 
  459.             print(f"Sending: {message}") 
  460.             ssl_socket.sendall(message.encode()) 
  461.  
  462.             # Receive data from the server 
  463.             data = ssl_socket.recv(1024) 
  464.             print(f"Received: {data.decode()}") 
  465.         except ConnectionRefusedError:
  466.             print("Connection refused. Make sure the server is running.")
  467.         finally: 
  468.             # Close the connection 
  469.             ssl_socket.close() 
  470.     except Exception as e:
  471.         print(f"An error occurred: {e}")
  472.  
  473. if __name__ == "__main__": 
  474.     main()
  475.  
  476.  
  477.  
  478. 1. AES
  479.  
  480. REC
  481.  
  482.  
  483. import socket
  484. INV_S_BOX_STRING = '52 09 6a d5 30 36 a5 38 bf 40 a3 9e 81 f3 d7 fb' \
  485.                    '7c e3 39 82 9b 2f ff 87 34 8e 43 44 c4 de e9 cb' \
  486.                    '54 7b 94 32 a6 c2 23 3d ee 4c 95 0b 42 fa c3 4e' \
  487.                    '08 2e a1 66 28 d9 24 b2 76 5b a2 49 6d 8b d1 25' \
  488.                    '72 f8 f6 64 86 68 98 16 d4 a4 5c cc 5d 65 b6 92' \
  489.                    '6c 70 48 50 fd ed b9 da 5e 15 46 57 a7 8d 9d 84' \
  490.                    '90 d8 ab 00 8c bc d3 0a f7 e4 58 05 b8 b3 45 06' \
  491.                    'd0 2c 1e 8f ca 3f 0f 02 c1 af bd 03 01 13 8a 6b' \
  492.                    '3a 91 11 41 4f 67 dc ea 97 f2 cf ce f0 b4 e6 73' \
  493.                    '96 ac 74 22 e7 ad 35 85 e2 f9 37 e8 1c 75 df 6e' \
  494.                    '47 f1 1a 71 1d 29 c5 89 6f b7 62 0e aa 18 be 1b' \
  495.                    'fc 56 3e 4b c6 d2 79 20 9a db c0 fe 78 cd 5a f4' \
  496.                    '1f dd a8 33 88 07 c7 31 b1 12 10 59 27 80 ec 5f' \
  497.                    '60 51 7f a9 19 b5 4a 0d 2d e5 7a 9f 93 c9 9c ef' \
  498.                    'a0 e0 3b 4d ae 2a f5 b0 c8 eb bb 3c 83 53 99 61' \
  499.                    '17 2b 04 7e ba 77 d6 26 e1 69 14 63 55 21 0c 7d'.replace(" ", "")
  500.                    
  501. S_BOX_STRING = '63 7c 77 7b f2 6b 6f c5 30 01 67 2b fe d7 ab 76' \
  502.                'ca 82 c9 7d fa 59 47 f0 ad d4 a2 af 9c a4 72 c0' \
  503.                'b7 fd 93 26 36 3f f7 cc 34 a5 e5 f1 71 d8 31 15' \
  504.                '09 83 2c 1a 1b 6e 5a a0 52 3b d6 b3 29 e3 2f 84' \
  505.                '53 d1 00 ed 20 fc b1 5b 6a cb be 39 4a 4c 58 cf' \
  506.                'd0 ef aa fb 43 4d 33 85 45 f9 02 7f 50 3c 9f a8' \
  507.                '51 a3 40 8f 92 9d 38 f5 bc b6 da 21 10 ff f3 d2' \
  508.                'cd 0c 13 ec 5f 97 44 17 c4 a7 7e 3d 64 5d 19 73' \
  509.                '60 81 4f dc 22 2a 90 88 46 ee b8 14 de 5e 0b db' \
  510.                'e0 32 3a 0a 49 06 24 5c c2 d3 ac 62 91 95 e4 79' \
  511.                'e7 c8 37 6d 8d d5 4e a9 6c 56 f4 ea 65 7a ae 08' \
  512.                'ba 78 25 2e 1c a6 b4 c6 e8 dd 74 1f 4b bd 8b 8a' \
  513.                '70 3e b5 66 48 03 f6 0e 61 35 57 b9 86 c1 1d 9e' \
  514.                'e1 f8 98 11 69 d9 8e 94 9b 1e 87 e9 ce 55 28 df' \
  515.                '8c a1 89 0d bf e6 42 68 41 99 2d 0f b0 54 bb 16'.replace(" ", "")
  516.                
  517.                
  518. S_BOX = bytearray.fromhex(S_BOX_STRING)
  519.  
  520.  
  521. INV_S_BOX = bytearray.fromhex(INV_S_BOX_STRING)
  522.  
  523.  
  524. def inv_shift_rows(state: [[int]]) -> [[int]]:
  525.     state[1][1], state[2][1], state[3][1], state[0][1] = state[0][1], state[1][1], state[2][1], state[3][1]
  526.     state[2][2], state[3][2], state[0][2], state[1][2] = state[0][2], state[1][2], state[2][2], state[3][2]
  527.     state[3][3], state[0][3], state[1][3], state[2][3] = state[0][3], state[1][3], state[2][3], state[3][3]
  528.     return
  529.  
  530.  
  531. def inv_sub_bytes(state: [[int]]) -> [[int]]:
  532.     for r in range(len(state)):
  533.         state[r] = [INV_S_BOX[state[r][c]] for c in range(len(state[0]))]
  534.        
  535.  
  536.  
  537.        
  538. def xtime(a: int) -> int:
  539.     if a & 0x80:
  540.         return ((a << 1) ^ 0x1b) & 0xff
  541.     return a << 1
  542.  
  543.  
  544. def xtimes_0e(b):
  545.     # 0x0e = 14 = b1110 = ((x * 2 + x) * 2 + x) * 2
  546.     return xtime(xtime(xtime(b) ^ b) ^ b)
  547.  
  548.  
  549.  
  550.  
  551. def xtimes_0b(b):
  552.     # 0x0b = 11 = b1011 = ((x*2)*2+x)*2+x
  553.     return xtime(xtime(xtime(b)) ^ b) ^ b
  554.  
  555.  
  556.  
  557.  
  558. def xtimes_0d(b):
  559.     # 0x0d = 13 = b1101 = ((x*2+x)*2)*2+x
  560.     return xtime(xtime(xtime(b) ^ b)) ^ b
  561.  
  562.  
  563.  
  564.  
  565. def xtimes_09(b):
  566.     # 0x09 = 9  = b1001 = ((x*2)*2)*2+x
  567.     return xtime(xtime(xtime(b))) ^ b
  568.  
  569.  
  570. def mix_column(col: [int]):
  571.     c_0 = col[0]
  572.     all_xor = col[0] ^ col[1] ^ col[2] ^ col[3]
  573.     col[0] ^= all_xor ^ xtime(col[0] ^ col[1])
  574.     col[1] ^= all_xor ^ xtime(col[1] ^ col[2])
  575.     col[2] ^= all_xor ^ xtime(col[2] ^ col[3])
  576.     col[3] ^= all_xor ^ xtime(c_0 ^ col[3])
  577.  
  578.  
  579. def mix_columns(state: [[int]]):
  580.     for r in state:
  581.         mix_column(r)
  582.  
  583.  
  584. def state_from_bytes(data: bytes) -> [[int]]:
  585.     state = [data[i*4:(i+1)*4] for i in range(len(data) // 4)]
  586.     return state
  587.  
  588.  
  589.  
  590.  
  591. def bytes_from_state(state: [[int]]) -> bytes:
  592.     return bytes(state[0] + state[1] + state[2] + state[3])
  593.  
  594.  
  595. def add_round_key(state: [[int]], key_schedule: [[[int]]], round: int):
  596.     round_key = key_schedule[round]
  597.     for r in range(len(state)):
  598.         state[r] = [state[r][c] ^ round_key[r][c] for c in range(len(state[0]))]
  599.  
  600.  
  601. def inv_mix_column(col: [int]):
  602.     c_0, c_1, c_2, c_3 = col[0], col[1], col[2], col[3]
  603.     col[0] = xtimes_0e(c_0) ^ xtimes_0b(c_1) ^ xtimes_0d(c_2) ^ xtimes_09(c_3)
  604.     col[1] = xtimes_09(c_0) ^ xtimes_0e(c_1) ^ xtimes_0b(c_2) ^ xtimes_0d(c_3)
  605.     col[2] = xtimes_0d(c_0) ^ xtimes_09(c_1) ^ xtimes_0e(c_2) ^ xtimes_0b(c_3)
  606.     col[3] = xtimes_0b(c_0) ^ xtimes_0d(c_1) ^ xtimes_09(c_2) ^ xtimes_0e(c_3)
  607.  
  608.  
  609.  
  610.  
  611. def inv_mix_columns(state: [[int]]) -> [[int]]:
  612.     for g in state:
  613.         inv_mix_column(r)
  614.  
  615.  
  616.  
  617.  
  618. def inv_mix_column_optimized(col: [int]):
  619.     u = xtime(xtime(col[0] ^ col[2]))
  620.     v = xtime(xtime(col[1] ^ col[3]))
  621.     col[0] ^= u
  622.     col[1] ^= v
  623.     col[2] ^= u
  624.     col[3] ^= v
  625.  
  626.  
  627.  
  628.  
  629. def inv_mix_columns_optimized(state: [[int]]) -> [[int]]:
  630.     for r in state:
  631.         inv_mix_column_optimized(r)
  632.     mix_columns(state)
  633.    
  634. def xor_bytes(a: bytes, b: bytes) -> bytes:
  635.     return bytes([x ^ y for (x, y) in zip(a, b)])
  636.  
  637.  
  638.  
  639.  
  640. def rot_word(word: [int]) -> [int]:
  641.     return word[1:] + word[:1]
  642.  
  643.  
  644. def sub_word(word: [int]) -> bytes:
  645.     substituted_word = bytes(S_BOX[i] for i in word)
  646.     return substituted_word
  647.  
  648.  
  649.  
  650.  
  651. def rcon(i: int) -> bytes:
  652.     rcon_lookup = bytearray.fromhex('0102040810204081b36')
  653.     rcon_value = bytes([rcon_lookup[i-1], 0, 0, 0])
  654.     return rcon_value
  655.    
  656. def key_expansion(key: bytes, nb: int = 4) -> [[[int]]]:
  657.  
  658.  
  659.     nk = len(key) // 4
  660.  
  661.  
  662.     key_bit_length = len(key) * 8
  663.  
  664.  
  665.     if key_bit_length == 128:
  666.         nr = 10
  667.     elif key_bit_length == 192:
  668.         nr = 12
  669.     else:  # 256-bit keys
  670.         nr = 14
  671.  
  672.  
  673.     w = state_from_bytes(key)
  674.  
  675.  
  676.     for i in range(nk, nb * (nr + 1)):
  677.         temp = w[i-1]
  678.         if i % nk == 0:
  679.             temp = xor_bytes(sub_word(rot_word(temp)), rcon(i // nk))
  680.         elif nk > 6 and i % nk == 4:
  681.             temp = sub_word(temp)
  682.         w.append(xor_bytes(w[i - nk], temp))
  683.  
  684.  
  685.     return [w[i*4:(i+1)*4] for i in range(len(w) // 4)]
  686.  
  687.  
  688.  
  689.  
  690.  
  691.  
  692. def aes_decryption(cipher: bytes, key: bytes) -> bytes:
  693.  
  694.  
  695.     key_byte_length = len(key)
  696.     key_bit_length = key_byte_length * 8
  697.     nk = key_byte_length // 4
  698.     if key_bit_length == 128:
  699.         nr = 10
  700.     elif key_bit_length == 192:
  701.         nr = 12
  702.     else:  # 256-bit keys
  703.         nr = 14
  704.  
  705.  
  706.     state = state_from_bytes(cipher)
  707.     key_schedule = key_expansion(key)
  708.     add_round_key(state, key_schedule, round=nr)
  709.     for round in range(nr, 0, -1):
  710.         inv_shift_rows(state)
  711.         inv_sub_bytes(state)
  712.         add_round_key(state, key_schedule, round)
  713.         inv_mix_columns(state)
  714.         print("Round ", round, " : ", state)
  715.  
  716.  
  717.     inv_shift_rows(state)
  718.     inv_sub_bytes(state)
  719.     add_round_key(state, key_schedule, round=0)
  720.     plain = bytes_from_state(state)
  721.     return plain
  722.  
  723.  
  724. key = bytearray.fromhex('00010203040060708090a0b0c0d0e0f')
  725. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  726. s.bind(('127.0.0.1', 1111))
  727. s.listen(1)
  728. conn, addr = s.accept()
  729.  
  730.  
  731. data = conn.recv(1024)
  732. print("Received Encrypted Data: ", data)
  733. print("Decrypted Data: ", aes_decryption(data, key).decode('utf-8'))
  734. conn.close()
  735. #1st run receiver.py tehn run sender.py then put in the value in the sender.py and see the output in the receiver.py
  736.  
  737.  
  738.  
  739. SEN
  740. import socket
  741.  
  742.  
  743. # CONSTANTS
  744.  
  745.  
  746. S_BOX_STRING = '63 7c 77 7b f2 6b 6f c5 30 01 67 2b fe d7 ab 76' \
  747.                'ca 82 c9 7d fa 59 47 f0 ad d4 a2 af 9c a4 72 c0' \
  748.                'b7 fd 93 26 36 3f f7 cc 34 a5 e5 f1 71 d8 31 15' \
  749.                '04 c7 23 c3 18 96 05 9a 07 12 80 e2 eb 27 b2 75' \
  750.                '09 83 2c 1a 1b 6e 5a a0 52 3b d6 b3 29 e3 2f 84' \
  751.                '53 d1 00 ed 20 fc b1 5b 6a cb be 39 4a 4c 58 cf' \
  752.                'd0 ef aa fb 43 4d 33 85 45 f9 02 7f 50 3c 9f a8' \
  753.                '51 a3 40 8f 92 9d 38 f5 bc b6 da 21 10 ff f3 d2' \
  754.                'cd 0c 13 ec 5f 97 44 17 c4 a7 7e 3d 64 5d 19 73' \
  755.                '60 81 4f dc 22 2a 90 88 46 ee b8 14 de 5e 0b db' \
  756.                'e0 32 3a 0a 49 06 24 5c c2 d3 ac 62 91 95 e4 79' \
  757.                'e7 c8 37 6d 8d d5 4e a9 6c 56 f4 ea 65 7a ae 08' \
  758.                'ba 78 25 2e 1c a6 b4 c6 e8 dd 74 1f 4b bd 8b 8a' \
  759.                '70 3e b5 66 48 03 f6 0e 61 35 57 b9 86 c1 1d 9e' \
  760.                '8c a1 89 0d bf e6 42 68 41 99 2d 0f b0 54 bb 16'.replace(" ", "")
  761. S_BOX = bytearray.fromhex(S_BOX_STRING)
  762.  
  763.  
  764.  
  765.  
  766. def sub_word(word: [int]) -> bytes:
  767.     substituted_word = bytes(S_BOX[i] for i in word)
  768.     return substituted_word
  769.  
  770.  
  771. def rcon(i: int) -> bytes:
  772.     rcon_lookup = bytearray.fromhex('0100408102040801b36')
  773.     rcon_value = bytes([rcon_lookup[i-1], 0, 0, 0])
  774.     return rcon_value
  775.  
  776.  
  777.  
  778.  
  779. def xor_bytes(a: bytes, b: bytes) -> bytes:
  780.     return bytes([x ^ y for (x, y) in zip(a, b)])
  781.  
  782.  
  783.  
  784.  
  785. def rot_word(word: [int]) -> [int]:
  786.     return word[1:] + word[:1]
  787.  
  788.  
  789.  
  790.  
  791. def key_expansion(key: bytes, nb: int = 4) -> [[[int]]]:
  792.  
  793.  
  794.     nk = len(key) // 4
  795.  
  796.  
  797.     key_bit_length = len(key) * 8
  798.  
  799.  
  800.     if key_bit_length == 128:
  801.         nr = 10
  802.     elif key_bit_length == 192:
  803.         nr = 12
  804.     else:  # 256-bit keys
  805.         nr = 14
  806.  
  807.  
  808.     w = state_from_bytes(key)
  809.  
  810.  
  811.     for i in range(nk, nb * (nr + 1)):
  812.         temp = w[i-1]
  813.         if i % nk == 0:
  814.             temp = xor_bytes(sub_word(rot_word(temp)), rcon(i // nk))
  815.         elif nk > 6 and i % nk == 4:
  816.             temp = sub_word(temp)
  817.         w.append(xor_bytes(w[i - nk], temp))
  818.  
  819.  
  820.     return [w[i*4:(i+1)*4] for i in range(len(w) // 4)]
  821.  
  822.  
  823.  
  824.  
  825. def add_round_key(state: [[int]], key_schedule: [[[int]]], round: int):
  826.     round_key = key_schedule[round]
  827.     for r in range(len(state)):
  828.         state[r] = [state[r][c] ^ round_key[r][c] for c in range(len(state[0]))]
  829.  
  830.  
  831.  
  832.  
  833. def sub_bytes(state: [[int]]):
  834.     for r in range(len(state)):
  835.         state[r] = [S_BOX[state[r][c]] for c in range(len(state[0]))]
  836.  
  837.  
  838.  
  839.  
  840. def shift_rows(state: [[int]]):
  841.     state[0][1], state[1][1], state[2][1], state[3][1] = state[1][1], state[2][1], state[3][1], state[0][1]
  842.     state[0][2], state[1][2], state[2][2], state[3][2] = state[2][2], state[3][2], state[0][2], state[1][2]
  843.     state[0][3], state[1][3], state[2][3], state[3][3] = state[3][3], state[0][3], state[1][3], state[2][3]
  844.  
  845.  
  846.  
  847.  
  848. def xtime(a: int) -> int:
  849.     if a & 0x80:
  850.         return ((a << 1) ^ 0x1b) & 0xff
  851.     return a << 1
  852.  
  853.  
  854.  
  855.  
  856. def mix_column(col: [int]):
  857.     c_0 = col[0]
  858.     all_xor = col[0] ^ col[1] ^ col[2] ^ col[3]
  859.     col[0] ^= all_xor ^ xtime(col[0] ^ col[1])
  860.     col[1] ^= all_xor ^ xtime(col[1] ^ col[2])
  861.     col[2] ^= all_xor ^ xtime(col[2] ^ col[3])
  862.     col[3] ^= all_xor ^ xtime(c_0 ^ col[3])
  863.  
  864.  
  865.  
  866.  
  867. def mix_columns(state: [[int]]):
  868.     for r in state:
  869.         mix_column(r)
  870.  
  871.  
  872.  
  873.  
  874. def state_from_bytes(data: bytes) -> [[int]]:
  875.     state = [data[i*4:(i+1)*4] for i in range(len(data) // 4)]
  876.     return state
  877.  
  878.  
  879.  
  880.  
  881. def bytes_from_state(state: [[int]]) -> bytes:
  882.     return bytes(state[0] + state[1] + state[2] + state[3])
  883.  
  884.  
  885.  
  886.  
  887. def aes_encryption(data: bytes, key: bytes) -> bytes:
  888.     state = state_from_bytes(data)
  889.     key_schedule = key_expansion(key)
  890.     add_round_key(state, key_schedule, round=0)
  891.  
  892.  
  893.     for round in range(1, 11):
  894.         sub_bytes(state)
  895.         shift_rows(state)
  896.         mix_columns(state)
  897.         add_round_key(state, key_schedule, round)
  898.         print("Round ", round, " : ", state)
  899.  
  900.  
  901.     sub_bytes(state)
  902.     shift_rows(state)
  903.     add_round_key(state, key_schedule, round=10)
  904.  
  905.  
  906.     cipher = bytes_from_state(state)
  907.     return cipher
  908.  
  909.  
  910.  
  911.  
  912.  
  913.  
  914.  
  915.  
  916. if name == "main":
  917.    
  918.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  919.     server_address = ('127.0.0.1', 1111)
  920.     s.connect(server_address)
  921.     plaintext = input("Enter the plaintext: ")
  922.  
  923.  
  924.     block_size = 16
  925.     padding_length = block_size - (len(plaintext) % block_size)
  926.     plaintext += chr(padding_length) * padding_length
  927.  
  928.  
  929.  
  930.  
  931.     plaintext_bytes = plaintext.encode()
  932.  
  933.  
  934.     key = bytearray.fromhex('00010203040060708090a0b0c0d0e0f')
  935.     ciphertext = aes_encryption(plaintext_bytes, key)
  936.     print("Ciphertext (hex): ", ciphertext.hex())
  937.     s.sendall(ciphertext)
  938.  
  939.  
  940.  
  941.  
  942.  
  943. 2. DES
  944.  
  945. CLIENT
  946. import socket
  947. INITIAL_PERM = [58, 50, 42, 34, 26, 18, 10, 2,
  948.                 60, 52, 44, 36, 28, 20, 12, 4,
  949.                 62, 54, 46, 38, 30, 22, 14, 6,
  950.                 64, 56, 48, 40, 32, 24, 16, 8,
  951.                 57, 49, 41, 33, 25, 17, 9, 1,
  952.                 59, 51, 43, 35, 27, 19, 11, 3,
  953.                 61, 53, 45, 37, 29, 21, 13, 5,
  954.                 63, 55, 47, 39, 31, 23, 15, 7]
  955.  
  956.  
  957. D = [32, 1, 2, 3, 4, 5, 4, 5,
  958.         6, 7, 8, 9, 8, 9, 10, 11,
  959.         12, 13, 12, 13, 14, 15, 16, 17,
  960.         16, 17, 18, 19, 20, 21, 20, 21,
  961.         22, 23, 24, 25, 24, 25, 26, 27,
  962.         28, 29, 28, 29, 30, 31, 32, 1]
  963.  
  964.  
  965. PERM = [16, 7, 20, 21,
  966.     29, 12, 28, 17,
  967.     1, 15, 23, 26,
  968.     5, 18, 31, 10,
  969.     2, 8, 24, 14,
  970.     32, 27, 3, 9,
  971.     19, 13, 30, 6,
  972.     22, 11, 4, 25]
  973.  
  974.  
  975.  
  976.  
  977. SBOX = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
  978.         [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
  979.         [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
  980.         [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]],
  981.  
  982.  
  983.         [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
  984.         [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
  985.         [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
  986.         [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]],
  987.  
  988.  
  989.         [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
  990.         [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
  991.         [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
  992.         [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]],
  993.  
  994.  
  995.         [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
  996.         [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
  997.         [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
  998.         [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]],
  999.  
  1000.  
  1001.         [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
  1002.         [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
  1003.         [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
  1004.         [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]],
  1005.  
  1006.  
  1007.         [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
  1008.         [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
  1009.         [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
  1010.         [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]],
  1011.  
  1012.  
  1013.         [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
  1014.         [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
  1015.         [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
  1016.         [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]],
  1017.  
  1018.  
  1019.         [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
  1020.         [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
  1021.         [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
  1022.         [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]]
  1023.  
  1024.  
  1025. FPERM = [40, 8, 48, 16, 56, 24, 64, 32,
  1026.             39, 7, 47, 15, 55, 23, 63, 31,
  1027.             38, 6, 46, 14, 54, 22, 62, 30,
  1028.             37, 5, 45, 13, 53, 21, 61, 29,
  1029.             36, 4, 44, 12, 52, 20, 60, 28,
  1030.             35, 3, 43, 11, 51, 19, 59, 27,
  1031.             33, 1, 41, 9, 49, 17, 57, 25]
  1032.  
  1033.  
  1034. # --parity bit drop table
  1035. KEYP = [57, 49, 41, 33, 25, 17, 9,
  1036.         1, 58, 50, 42, 34, 26, 18,
  1037.         10, 2, 59, 51, 43, 35, 27,
  1038.         19, 11, 3, 60, 52, 44, 36,
  1039.         63, 55, 47, 39, 31, 23, 15,
  1040.         7, 62, 54, 46, 38, 30, 22,
  1041.         14, 6, 61, 53, 45, 37, 29,
  1042.         21, 13, 5, 28, 20, 12, 4]
  1043.  
  1044.  
  1045. # Number of bit shifts
  1046. SHIFT_TABLE = [1, 1, 2, 2,
  1047.             2, 2, 2, 2,
  1048.             1, 2, 2, 2,
  1049.             2, 2, 2, 1]
  1050.  
  1051.  
  1052. # Key- Compression Table : Compression of key from 56 bits to 48 bits
  1053. KEY_COMP = [14, 17, 11, 24, 1, 5,
  1054.             3, 28, 15, 6, 21, 10,
  1055.             23, 19, 12, 4, 26, 8,
  1056.             16, 7, 27, 20, 13, 2,
  1057.             41, 52, 31, 37, 47, 55,
  1058.             30, 40, 51, 45, 33, 48,
  1059.             44, 49, 39, 56, 34, 53,
  1060.             46, 42, 50, 36, 29, 32]
  1061.  
  1062.  
  1063.  
  1064.  
  1065. def hex2bin(s):
  1066.     mp = {'0': "0000",
  1067.         '1': "0001",
  1068.         '2': "0010",
  1069.         '3': "0011",
  1070.         '4': "0100",
  1071.         '5': "0101",
  1072.         '6': "0110",
  1073.         '7': "0111",
  1074.         '8': "1000",
  1075.         '9': "1001",
  1076.         'A': "1010",
  1077.         'B': "1011",
  1078.         'C': "1100",
  1079.         'D': "1101",
  1080.         'E': "1110",
  1081.         'F': "1111"}
  1082.     bin = ""
  1083.     for i in range(len(s)):
  1084.         bin = bin + mp[s[i]]
  1085.     return bin
  1086.  
  1087.  
  1088. def bin2hex(s):
  1089.     mp = {"0000": '0',
  1090.         "0001": '1',
  1091.         "0010": '2',
  1092.         "0011": '3',
  1093.         "0100": '4',
  1094.         "0101": '5',
  1095.         "0110": '6',
  1096.         "0111": '7',
  1097.         "1000": '8',
  1098.         "1001": '9',
  1099.         "1010": 'A',
  1100.         "1011": 'B',
  1101.         "1100": 'C',
  1102.         "1101": 'D',
  1103.         "1110": 'E',
  1104.         "1111": 'F'}
  1105.     hex = ""
  1106.     for i in range(0, len(s), 4):
  1107.         ch = ""
  1108.         ch = ch + s[i]
  1109.         ch = ch + s[i + 1]
  1110.         ch = ch + s[i + 2]
  1111.         ch = ch + s[i + 3]
  1112.         hex = hex + mp[ch]
  1113.  
  1114.  
  1115.     return hex
  1116.  
  1117.  
  1118. def bin2dec(binary):
  1119.  
  1120.  
  1121.     binary1 = binary
  1122.     decimal, i, n = 0, 0, 0
  1123.     while(binary != 0):
  1124.         dec = binary % 10
  1125.         decimal = decimal + dec * pow(2, i)
  1126.         binary = binary//10
  1127.         i += 1
  1128.     return decimal
  1129.  
  1130.  
  1131. def dec2bin(num):
  1132.     res = bin(num).replace("0b", "")
  1133.     if(len(res) % 4 != 0):
  1134.         div = len(res) / 4
  1135.         div = int(div)
  1136.         counter = (4 * (div + 1)) - len(res)
  1137.         for i in range(0, counter):
  1138.             res = '0' + res
  1139.     return res
  1140.  
  1141.  
  1142. def permute(k, arr, n):
  1143.     permutation = ""
  1144.     for i in range(0, n):
  1145.         permutation = permutation + k[arr[i] - 1]
  1146.     return permutation
  1147.  
  1148.  
  1149. def shift_left(k, nth_shifts):
  1150.     s = ""
  1151.     for i in range(nth_shifts):
  1152.         for j in range(1, len(k)):
  1153.             s = s + k[j]
  1154.         s = s + k[0]
  1155.         k = s
  1156.         s = ""
  1157.     return k
  1158.  
  1159.  
  1160. def xor(a, b):
  1161.     ans = ""
  1162.     for i in range(len(a)):
  1163.         if a[i] == b[i]:
  1164.             ans = ans + "0"
  1165.         else:
  1166.             ans = ans + "1"
  1167.     return ans
  1168.  
  1169.  
  1170.  
  1171.  
  1172. def encrypt(pt, rkb, rk):
  1173.     pt = hex2bin(pt)
  1174.  
  1175.  
  1176.  
  1177.  
  1178.     pt = permute(pt, INITIAL_PERM, 64)
  1179.     print("After initial permutation", bin2hex(pt))
  1180.  
  1181.  
  1182.  
  1183.  
  1184.     left = pt[0:32]
  1185.     right = pt[32:64]
  1186.     for i in range(0, 16):
  1187.    
  1188.         right_expanded = permute(right, D, 48)
  1189.  
  1190.  
  1191.         xor_x = xor(right_expanded, rkb[i])
  1192.  
  1193.  
  1194.    
  1195.         sbox_str = ""
  1196.         for j in range(0, 8):
  1197.             row = bin2dec(int(xor_x[j * 6] + xor_x[j * 6 + 5]))
  1198.             col = bin2dec(
  1199.                 int(xor_x[j * 6 + 1] + xor_x[j * 6 + 2] + xor_x[j * 6 + 3] + xor_x[j * 6 + 4]))
  1200.             val = SBOX[j][row][col]
  1201.             sbox_str = sbox_str + dec2bin(val)
  1202.  
  1203.  
  1204.  
  1205.  
  1206.         sbox_str = permute(sbox_str, PERM, 32)
  1207.  
  1208.  
  1209.  
  1210.  
  1211.         result = xor(left, sbox_str)
  1212.         left = result
  1213.  
  1214.  
  1215.  
  1216.  
  1217.         if(i != 15):
  1218.             left, right = right, left
  1219.         print("Round ", i + 1, " ", bin2hex(left),
  1220.             " ", bin2hex(right), " ", rk[i])
  1221.  
  1222.  
  1223.     combine = left + right
  1224.  
  1225.  
  1226.     cipher_text = permute(combine, FPERM, 64)
  1227.     return cipher_text
  1228.  
  1229.  
  1230. def keygen(key):
  1231.     key = hex2bin(key)
  1232.     key = permute(key, KEYP, 56)
  1233.  
  1234.  
  1235.     left = key[0:28]
  1236.     right = key[28:56]
  1237.     rkb = []
  1238.     rk = []
  1239.     for i in range(0, 16):
  1240.  
  1241.  
  1242.         left = shift_left(left, SHIFT_TABLE[i])
  1243.         right = shift_left(right, SHIFT_TABLE[i])
  1244.  
  1245.  
  1246.         combine_str = left + right
  1247.  
  1248.  
  1249.  
  1250.  
  1251.         round_key = permute(combine_str, KEY_COMP, 48)
  1252.  
  1253.  
  1254.         rkb.append(round_key)
  1255.         rk.append(bin2hex(round_key))
  1256.     return rkb, rk
  1257.  
  1258.  
  1259. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1260. port = 1234
  1261. ip = '127.0.0.1'
  1262. s.connect((ip, port))
  1263. data = input("Enter Hexadecimal data to send: ")
  1264. key ="AABB09182736CCDD"
  1265.  
  1266.  
  1267. rkb, rk = keygen(key)
  1268.  
  1269.  
  1270. cipher_text = bin2hex(encrypt(data, rkb, rk))
  1271. print("Cipher Text : ", cipher_text)
  1272. s.send(cipher_text.encode())
  1273. s.close()
  1274.  
  1275.  
  1276.  
  1277.  
  1278. SENDER
  1279. import socket
  1280.  
  1281.  
  1282. INITIAL_PERM = [58, 50, 42, 34, 26, 18, 10, 2,
  1283.                 60, 52, 44, 36, 28, 20, 12, 4,
  1284.                 62, 54, 46, 38, 30, 22, 14, 6,
  1285.                 64, 56, 48, 40, 32, 24, 16, 8,
  1286.                 57, 49, 41, 33, 25, 17, 9, 1,
  1287.                 59, 51, 43, 35, 27, 19, 11, 3,
  1288.                 61, 53, 45, 37, 29, 21, 13, 5,
  1289.                 63, 55, 47, 39, 31, 23, 15, 7]
  1290.  
  1291.  
  1292. D = [32, 1, 2, 3, 4, 5, 4, 5,
  1293.         6, 7, 8, 9, 8, 9, 10, 11,
  1294.         12, 13, 12, 13, 14, 15, 16, 17,
  1295.         16, 17, 18, 19, 20, 21, 20, 21,
  1296.         22, 23, 24, 25, 24, 25, 26, 27,
  1297.         28, 29, 28, 29, 30, 31, 32, 1]
  1298.  
  1299.  
  1300. PERM = [16, 7, 20, 21,
  1301.     29, 12, 28, 17,
  1302.     1, 15, 23, 26,
  1303.     5, 18, 31, 10,
  1304.     2, 8, 24, 14,
  1305.     32, 27, 3, 9,
  1306.     19, 13, 30, 6,
  1307.     22, 11, 4, 25]
  1308.  
  1309.  
  1310.  
  1311.  
  1312. SBOX = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
  1313.         [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
  1314.         [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
  1315.         [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]],
  1316.  
  1317.  
  1318.         [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
  1319.         [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
  1320.         [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
  1321.         [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]],
  1322.  
  1323.  
  1324.         [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
  1325.         [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
  1326.         [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
  1327.         [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]],
  1328.  
  1329.  
  1330.         [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
  1331.         [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
  1332.         [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
  1333.         [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]],
  1334.  
  1335.  
  1336.         [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
  1337.         [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
  1338.         [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
  1339.         [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]],
  1340.  
  1341.  
  1342.         [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
  1343.         [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
  1344.         [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
  1345.         [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]],
  1346.  
  1347.  
  1348.         [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
  1349.         [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
  1350.         [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
  1351.         [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]],
  1352.  
  1353.  
  1354.         [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
  1355.         [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
  1356.         [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
  1357.         [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]]
  1358.  
  1359.  
  1360. FPERM = [40, 8, 48, 16, 56, 24, 64, 32,
  1361.             39, 7, 47, 15, 55, 23, 63, 31,
  1362.             38, 6, 46, 14, 54, 22, 62, 30,
  1363.             37, 5, 45, 13, 53, 21, 61, 29,
  1364.             36, 4, 44, 12, 52, 20, 60, 28,
  1365.             35, 3, 43, 11, 51, 19, 59, 27,
  1366.             34, 2, 42, 10, 50, 18, 58, 26,
  1367.             33, 1, 41, 9, 49, 17, 57, 25]
  1368.  
  1369.  
  1370. # --parity bit drop table
  1371. KEYP = [57, 49, 41, 33, 25, 17, 9,
  1372.         1, 58, 50, 42, 34, 26, 18,
  1373.         10, 2, 59, 51, 43, 35, 27,
  1374.         19, 11, 3, 60, 52, 44, 36,
  1375.         63, 55, 47, 39, 31, 23, 15,
  1376.         7, 62, 54, 46, 38, 30, 22,
  1377.         14, 6, 61, 53, 45, 37, 29,
  1378.         21, 13, 5, 28, 20, 12, 4]
  1379.  
  1380.  
  1381. # Number of bit shifts
  1382. SHIFT_TABLE = [1, 1, 2, 2,
  1383.             2, 2, 2, 2,
  1384.             1, 2, 2, 2,
  1385.             2, 2, 2, 1]
  1386.  
  1387.  
  1388. # Key- Compression Table : Compression of key from 56 bits to 48 bits
  1389. KEY_COMP = [14, 17, 11, 24, 1, 5,
  1390.             3, 28, 15, 6, 21, 10,
  1391.             23, 19, 12, 4, 26, 8,
  1392.             16, 7, 27, 20, 13, 2,
  1393.             41, 52, 31, 37, 47, 55,
  1394.             30, 40, 51, 45, 33, 48,
  1395.             44, 49, 39, 56, 34, 53,
  1396.             46, 42, 50, 36, 29, 32]
  1397.  
  1398.  
  1399.  
  1400.  
  1401. def hex2bin(s):
  1402.     mp = {'0': "0000",
  1403.         '1': "0001",
  1404.         '2': "0010",
  1405.         '3': "0011",
  1406.         '4': "0100",
  1407.         '5': "0101",
  1408.         '6': "0110",
  1409.         '7': "0111",
  1410.         '8': "1000",
  1411.         '9': "1001",
  1412.         'A': "1010",
  1413.         'B': "1011",
  1414.         'C': "1100",
  1415.         'D': "1101",
  1416.         'E': "1110",
  1417.         'F': "1111"}
  1418.     bin = ""
  1419.     for i in range(len(s)):
  1420.         bin = bin + mp[s[i]]
  1421.     return bin
  1422.  
  1423.  
  1424. def bin2hex(s):
  1425.     mp = {"0000": '0',
  1426.         "0001": '1',
  1427.         "0010": '2',
  1428.         "0011": '3',
  1429.         "0100": '4',
  1430.         "0101": '5',
  1431.         "0110": '6',
  1432.         "0111": '7',
  1433.         "1000": '8',
  1434.         "1001": '9',
  1435.         "1010": 'A',
  1436.         "1011": 'B',
  1437.         "1100": 'C',
  1438.         "1101": 'D',
  1439.         "1110": 'E',
  1440.         "1111": 'F'}
  1441.     hex = ""
  1442.     for i in range(0, len(s), 4):
  1443.         ch = ""
  1444.         ch = ch + s[i]
  1445.         ch = ch + s[i + 1]
  1446.         ch = ch + s[i + 2]
  1447.         ch = ch + s[i + 3]
  1448.         hex = hex + mp[ch]
  1449.  
  1450.  
  1451.     return hex
  1452.  
  1453.  
  1454. def bin2dec(binary):
  1455.  
  1456.  
  1457.     binary1 = binary
  1458.     decimal, i, n = 0, 0, 0
  1459.     while(binary != 0):
  1460.         dec = binary % 10
  1461.         decimal = decimal + dec * pow(2, i)
  1462.         binary = binary//10
  1463.         i += 1
  1464.     return decimal
  1465.  
  1466.  
  1467. def dec2bin(num):
  1468.     res = bin(num).replace("0b", "")
  1469.     if(len(res) % 4 != 0):
  1470.         div = len(res) / 4
  1471.         div = int(div)
  1472.         counter = (4 * (div + 1)) - len(res)
  1473.         for i in range(0, counter):
  1474.             res = '0' + res
  1475.     return res
  1476.  
  1477.  
  1478. def permute(k, arr, n):
  1479.     permutation = ""
  1480.     for i in range(0, n):
  1481.         permutation = permutation + k[arr[i] - 1]
  1482.     return permutation
  1483.  
  1484.  
  1485. def shift_left(k, nth_shifts):
  1486.     s = ""
  1487.     for i in range(nth_shifts):
  1488.         for j in range(1, len(k)):
  1489.             s = s + k[j]
  1490.         s = s + k[0]
  1491.         k = s
  1492.         s = ""
  1493.     return k
  1494.  
  1495.  
  1496. def xor(a, b):
  1497.     ans = ""
  1498.     for i in range(len(a)):
  1499.         if a[i] == b[i]:
  1500.             ans = ans + "1"
  1501.         else:
  1502.             ans = ans + "0"
  1503.     return ans
  1504.  
  1505.  
  1506. def encrypt(pt, rkb, rk):
  1507.     pt = hex2bin(pt)
  1508.  
  1509.  
  1510.     # Initial Permutation
  1511.     pt = permute(pt, INITIAL_PERM, 64)
  1512.     print("After initial permutation", bin2hex(pt))
  1513.  
  1514.  
  1515.     # Splitting
  1516.     left = pt[0:32]
  1517.     right = pt[32:64]
  1518.     for i in range(0, 16):
  1519.         # Expansion D-box: Expanding the 32 bits data into 48 bits
  1520.         right_expanded = permute(right, D, 48)
  1521.  
  1522.  
  1523.  
  1524.  
  1525.         xor_x = xor(right_expanded, rkb[i])
  1526.  
  1527.  
  1528.  
  1529.  
  1530.         sbox_str = ""
  1531.         for j in range(0, 8):
  1532.             row = bin2dec(int(xor_x[j * 6] + xor_x[j * 6 + 5]))
  1533.             col = bin2dec(
  1534.                 int(xor_x[j * 6 + 1] + xor_x[j * 6 + 2] + xor_x[j * 6 + 3] + xor_x[j * 6 + 4]))
  1535.             val = SBOX[j][row][col]
  1536.             sbox_str = sbox_str + dec2bin(val)
  1537.  
  1538.  
  1539.  
  1540.  
  1541.         sbox_str = permute(sbox_str, PERM, 32)
  1542.  
  1543.  
  1544.         result = xor(left, sbox_str)
  1545.         left = result
  1546.  
  1547.  
  1548.         if(i != 15):
  1549.             left, right = right, left
  1550.         print("Round ", i + 1, " ", bin2hex(left),
  1551.             " ", bin2hex(right), " ", rk[i])
  1552.  
  1553.  
  1554.     combine = left + right
  1555.  
  1556.  
  1557.     cipher_text = permute(combine, FPERM, 64)
  1558.     return cipher_text
  1559.  
  1560.  
  1561. def keygen(key):
  1562.     key = hex2bin(key)
  1563.  
  1564.  
  1565.     key = permute(key, KEYP, 56)
  1566.  
  1567.  
  1568.     left = key[0:28]
  1569.     right = key[28:56]
  1570.     rkb = []
  1571.     rk = []
  1572.     for i in range(0, 16):
  1573.  
  1574.  
  1575.         left = shift_left(left, SHIFT_TABLE[i])
  1576.         right = shift_left(right, SHIFT_TABLE[i])
  1577.  
  1578.  
  1579.  
  1580.  
  1581.         combine_str = left + right
  1582.  
  1583.  
  1584.  
  1585.  
  1586.         round_key = permute(combine_str, KEY_COMP, 48)
  1587.  
  1588.  
  1589.         rkb.append(round_key)
  1590.         rk.append(bin2hex(round_key))
  1591.     return rkb, rk
  1592.  
  1593.  
  1594. key = input("Enter the hex key: ")
  1595.  
  1596.  
  1597. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1598. port = 1234
  1599. ip = '127.0.0.1'
  1600. s.bind((ip, port))
  1601. s.listen(5)
  1602. c, addr = s.accept()
  1603. data = c.recv(1024).decode()
  1604.  
  1605.  
  1606. rkb, rk = keygen(key)
  1607. print("Decryption")
  1608. rkb_rev = rkb[::-1]
  1609. rk_rev = rk[::-1]
  1610. text = bin2hex(encrypt(data, rkb_rev, rk_rev))
  1611. print("Plain Text : ", text)
  1612.  
  1613.  
  1614.  
  1615.  
  1616. 3. DIFFY
  1617. ALICE
  1618. import socket
  1619. import math
  1620.  
  1621.  
  1622. def mod_exp(base, exponent, modulus):
  1623.     return pow(base, exponent, modulus)
  1624.  
  1625.  
  1626. def compute_Y(alpha, X, q):
  1627.     return mod_exp(alpha, X, q)
  1628.  
  1629.  
  1630. def compute_shared_key(Y, X, q):
  1631.     return mod_exp(Y, X, q)
  1632.  
  1633.  
  1634. def alice():
  1635.     alpha = 10  # Specified value
  1636.     q = 16     # Specified value
  1637.  
  1638.  
  1639.     X = int(input("Enter XA for Alice: "))
  1640.  
  1641.  
  1642.     YA = compute_Y(alpha, X, q)
  1643.     print(f"YA={YA}")
  1644.  
  1645.  
  1646.     # Communicate with Dart
  1647.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s_dart:
  1648.         s_dart.connect(('localhost', 5001))
  1649.         s_dart.send(','.join([str(x) for x in [alpha, X, q, YA]]).encode('utf-8'))
  1650.  
  1651.  
  1652.         # Receive YD2 from Dart
  1653.         YD2_dart = int(s_dart.recv(1024).decode('utf-8'))
  1654.         print(f"Received YD2 from Dart: {YD2_dart}")
  1655.  
  1656.  
  1657.         # Compute and display K2
  1658.         K2 = compute_shared_key(YD2_dart, X, q)
  1659.         print(f"K2={K2}")
  1660.  
  1661.  
  1662. if name == "main":
  1663.     alice()
  1664. BOB
  1665. import socket
  1666. import math
  1667.  
  1668.  
  1669. def mod_exp(base, exponent, modulus):
  1670.     return pow(base, exponent, modulus)
  1671.  
  1672.  
  1673. def compute_Y(alpha, X, q):
  1674.     return mod_exp(alpha, X, q)
  1675.  
  1676.  
  1677. def compute_shared_key(Y, X, q):
  1678.     return mod_exp(Y, X, q)
  1679.  
  1680.  
  1681. def bob():
  1682.     alpha = 10  # Specified value
  1683.     q = 16     # Specified value
  1684.  
  1685.  
  1686.     XB = int(input("Enter XB for Bob: "))
  1687.  
  1688.  
  1689.     YB = compute_Y(alpha, XB, q)
  1690.     print(f"YB={YB}")
  1691.  
  1692.  
  1693.     # Communicate with Dart
  1694.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s_dart:
  1695.         s_dart.bind(('localhost', 5002))
  1696.         s_dart.connect(1)
  1697.         print("Bob terminal is listening for Dart on port 5002")
  1698.  
  1699.  
  1700.         conn_dart, addr_dart = s_dart.accept()
  1701.         with conn_dart:
  1702.             print(f"Connection established with Dart: {addr_dart}")
  1703.  
  1704.  
  1705.             # Receive YD1 from Dart
  1706.             YD1_dart = int(conn_dart.recv(1024).decode('utf-8'))
  1707.             print(f"Received YD1 from Dart: {YD1_dart}")
  1708.  
  1709.  
  1710.             # Additional communication with Dart can be added here if needed
  1711.  
  1712.  
  1713.             # Compute and display K1
  1714.             K1 = compute_shared_key(YD1_dart, XB, q)
  1715.             print(f"K1={K1}")
  1716.  
  1717.  
  1718. if name == "main":
  1719.     bob()
  1720. DARTH
  1721. import socket
  1722. import math
  1723.  
  1724.  
  1725. def mod_exp(base, exponent, modulus):
  1726.     return pow(base, exponent, modulus)
  1727.  
  1728.  
  1729. def compute_Y(alpha, X, q):
  1730.     return mod_exp(alpha, X, q)
  1731.    
  1732. def compute_k1(YB, XD1, q):
  1733.     return mod_exp(YB, 5, q)  
  1734.    
  1735. def compute_k2(YA, XD2, q):
  1736.     return mod_exp(YA, XD2, q)
  1737.    
  1738. def compute_shared_key(Y, X, q):
  1739.     return mod_exp(Y, X, q)
  1740.  
  1741.  
  1742. def dart():
  1743.     alpha = 15  # Specified value
  1744.     q = 12     # Specified value
  1745.  
  1746.  
  1747.     # Communicate with Alice
  1748.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s_alice:
  1749.         s_alice.bind(('localhost', 5001))
  1750.         s_alice.listen(1)
  1751.         print("Dart terminal is listening for Alice on port 5001")
  1752.  
  1753.  
  1754.         conn_alice, addr_alice = s_alice.accept()
  1755.         with conn_alice:
  1756.             print(f"Connection established with Alice: {addr_alice}")
  1757.             data_alice = conn_alice.recv(1024).decode('utf-8')
  1758.             alpha, X, q, YA = map(int, data_alice.split(','))
  1759.  
  1760.  
  1761.             print(f"Received data from Alice: alpha={alpha}, X={X}, q={q}, YA={YA}")
  1762.  
  1763.  
  1764.             XD1 = int(input("Enter XD1: "))
  1765.             XD2 = int(input("Enter XD2: "))
  1766.  
  1767.  
  1768.             YD1 = compute_Y(alpha, XD1, q)
  1769.             YD2 = compute_Y(alpha, XD2, q)
  1770.  
  1771.  
  1772.             print(f"YD1={YD1}, YD2={YD2}")
  1773.            
  1774.             K1 = compute_k1(YD1, XD1, q)
  1775.             K2 = compute_k2(YD2, X, q)
  1776.  
  1777.  
  1778.             print(f"K1={K1}, K2={K2}")
  1779.  
  1780.  
  1781.             # Send YD2 to Alice
  1782.             conn_alice.send(str(YD2).encode('utf-8'))
  1783.  
  1784.  
  1785.             # Send YD1 to Bob
  1786.             with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s_bob:
  1787.                 s_bob.connect(('localhost', 5002))
  1788.                 s_bob.send(str(YD1).encode('utf-8'))
  1789.  
  1790.  
  1791.                 # Additional communication with Bob can be added here if needed
  1792.  
  1793.  
  1794. if name == "main":
  1795.     dart()
  1796.  
  1797.  
  1798.  
  1799. 4. MD5
  1800. import math
  1801.  
  1802.  
  1803. # Define MD5 specific functions
  1804. def F(X, Y, Z):
  1805.     return (X & Y) | (~X & Z)
  1806.  
  1807.  
  1808. def G(X, Y, Z):
  1809.     return (X & Z) | (Y & ~Z)
  1810.  
  1811.  
  1812. def H(X, Y, Z):
  1813.     return X ^ Y ^ Z
  1814.  
  1815.  
  1816. def I(X, Y, Z):
  1817.     return Y ^ (X | ~Z)
  1818.  
  1819.  
  1820. # Define shift and constant values
  1821. s = [
  1822.     7, 12, 17, 22,
  1823.     5, 9, 14, 20,
  1824.     4, 11, 16, 23,
  1825.     6, 10, 15, 21
  1826. ]
  1827.  
  1828.  
  1829. K = [int(abs(math.sin(i + 1)) * 2 ** 32) & 0xFFFFFFFF for i in range(64)]
  1830.  
  1831.  
  1832. # Initialize variables
  1833. A = 0x01234567
  1834. B = 0x89ABCDEF
  1835. C = 0xFEDCBA98
  1836. D = 0x76543210
  1837.  
  1838.  
  1839. def md5(message):
  1840.     global A, B, C, D
  1841.     message = bytearray(message, 'utf-8')
  1842.     for i in range(0, len(message), 64):
  1843.         X = [0] * 16
  1844.         for j in range(16):
  1845.             X[j] = int.from_bytes(message[i + j*4:i + j*4 + 4], byteorder='little')
  1846.        
  1847.         AA, BB, CC, DD = A, B, C, D
  1848.        
  1849.         # Round 1
  1850.         for j in range(16):
  1851.             A = (B + ((A + F(B, C, D) + X[j] + K[j]) & 0xFFFFFFFF) << s[j % 4] | (A + F(B, C, D) + X[j] + K[j]) >> (32 - s[j % 4])) & 0xFFFFFFFF
  1852.             A, B, C, D = D, A, B, C
  1853.         print(f"Round 1 - Final Output: {A:08x} {B:08x} {C:08x} {D:08x}")
  1854.        
  1855.         # Round 2
  1856.         for j in range(16):
  1857.             A = (B + ((A + G(B, C, D) + X[(1 + 5*j) % 16] + K[16+j]) & 0xFFFFFFFF) << s[j % 4 + 4] | (A + G(B, C, D) + X[(1 + 5*j) % 16] + K[16+j]) >> (32 - s[j % 4 + 4])) & 0xFFFFFFFF
  1858.             A, B, C, D = D, A, B, C
  1859.         print(f"Round 2 - Final Output: {A:08x} {B:08x} {C:08x} {D:08x}")
  1860.        
  1861.         # Round 3
  1862.         for j in range(16):
  1863.             A = (B + ((A + H(B, C, D) + X[(5 + 3*j) % 16] + K[32+j]) & 0xFFFFFFFF) << s[j % 4 + 8] | (A + H(B, C, D) + X[(5 + 3*j) % 16] + K[32+j]) >> (32 - s[j % 4 + 8])) & 0xFFFFFFFF
  1864.             A, B, C, D = D, A, B, C
  1865.         print(f"Round 3 - Final Output: {A:08x} {B:08x} {C:08x} {D:08x}")
  1866.        
  1867.         # Round 4
  1868.         for j in range(16):
  1869.             A = (B + ((A + I(B, C, D) + X[(7*j) % 16] + K[48+j]) & 0xFFFFFFFF) << s[j % 4 + 12] | (A + I(B, C, D) + X[(7*j) % 16] + K[48+j]) >> (32 - s[j % 4 + 12])) & 0xFFFFFFFF
  1870.             A, B, C, D = D, A, B, C
  1871.         print(f"Round 4 - Final Output: {A:08x} {B:08x} {C:08x} {D:08x}")
  1872.        
  1873.         A = (A + AA) & 0xFFFFFFFF
  1874.         B = (B + BB) & 0xFFFFFFFF
  1875.         C = (C + CC) & 0xFFFFFFFF
  1876.         D = (D + DD) & 0xFFFFFFFF
  1877.    
  1878.     digest = bytearray()
  1879.     for val in (A, B, C, D):
  1880.         digest.extend(val.to_bytes(4, byteorder='little'))
  1881.     final_digest = digest * 4  # Concatenate the 128-bit digest four times to get a 512-bit digest
  1882.     return final_digest.hex()[:32]  # Return only the first 32 characters (128 bits) of the digest
  1883.  
  1884.  
  1885. # Main function
  1886. if name == "main":
  1887.     message = input("Enter a message to encrypt: ")
  1888.     digest = md5(message)
  1889.     print(f"MD5 Digest (128 bits): {digest}")
  1890.  
  1891.  
  1892.  
  1893.  
  1894. 5. RSA
  1895. def gcd(a, b):
  1896.     while b:
  1897.         a, b = b, a % b
  1898.     return a
  1899.  
  1900.  
  1901. def mod_inverse(a, m):
  1902.     m0, x0, x1 = m, 0, 1
  1903.     while a > 1:
  1904.         q = a // m
  1905.         m, a = a % m, m
  1906.         x0, x1 = x1 - q * x0, x0
  1907.     return x1 + m0 if x1 < 0 else x1
  1908.  
  1909.  
  1910. def generate_keypair(p, q):
  1911.     n = p * q
  1912.    
  1913.     totient = (p - 1) * (q - 1)
  1914.    
  1915.    
  1916.  
  1917.  
  1918.     # Choose e such that 1 < e < totient(n) and gcd(e, totient(n)) = 1
  1919.     e = 2
  1920.     while gcd(e, totient) != 1:
  1921.         e += 1
  1922.  
  1923.  
  1924.     # Calculate d, the modular multiplicative inverse of e (mod totient(n))
  1925.     d = mod_inverse(e, totient)
  1926.  
  1927.  
  1928.     public_key = (e, n)
  1929.     private_key = (d, n)
  1930.     print("e:", e)
  1931.     print("where GCD(e, totient(n)=1)")
  1932.  
  1933.  
  1934.     return public_key, private_key
  1935.  
  1936.  
  1937. def encrypt(message, public_key):
  1938.     e, n = public_key
  1939.     return pow(message, e, n)
  1940.  
  1941.  
  1942. def decrypt(ciphertext, private_key):
  1943.     d, n = private_key
  1944.     return pow(ciphertext, d, n)
  1945.  
  1946.  
  1947. # Example input: prime numbers p and q
  1948. p = int(input("Enter prime number p: "))
  1949. q = int(input("Enter prime number q: "))
  1950.  
  1951.  
  1952. # Calculate n and totient
  1953. n = p * q
  1954. print("n:", n)
  1955. totient = (p - 1) * (q - 1)
  1956. print("totient(n):", totient)
  1957.  
  1958.  
  1959. # Generate key pair
  1960. public_key, private_key = generate_keypair(p, q)
  1961.  
  1962.  
  1963.  
  1964.  
  1965. # Display public key and private key
  1966. print("Public key (e, n):", public_key)
  1967. print("Private key (d, n):", private_key)
  1968.  
  1969.  
  1970. # Example message to encrypt
  1971. message = int(input("Enter message to encrypt: "))
  1972.  
  1973.  
  1974. # Encrypt the message
  1975. ciphertext = encrypt(message, public_key)
  1976. print("Encrypted message (C):", ciphertext)
  1977.  
  1978.  
  1979. # Decrypt the message
  1980. decrypted_message = decrypt(ciphertext, private_key)
  1981. print("Decrypted message (M):", decrypted_message)
  1982. # just run, 17, 11, 88
  1983.  
  1984.  
  1985. 6. SHA
  1986. # Initial hash values
  1987. a = 0x6A09E667F3BCC908
  1988. b = 0xBB67AE8584CAA73B
  1989. c = 0x3C6EF372FE94F82B
  1990. d = 0xA54FF53A5F1D36F1
  1991. e = 0x510E527FADE682D1
  1992. f = 0x9B05688C2B3E6C1F
  1993. g = 0x1F83D9ABFB41BD6B
  1994. h = 0x5BE0CD19137E2179
  1995.  
  1996.  
  1997. # Message schedule constants
  1998. K = [
  1999.     0x428A2F98D728AE22, 0x7137449123EF65CD, 0xB5C0FBCFEC4D3B2F, 0xE9B5DBA58189DBBC,
  2000.     0x3956C25BF348B538, 0x59F111F1B605D019, 0x923F82A4AF194F9B, 0xAB1C5ED5DA6D8118,
  2001.     0xD807AA98A3030242, 0x12835B0145706FBE, 0x243185BE4EE4B28C, 0x550C7DC3D5FFB4E2,
  2002.     0x72BE5D74F27B896F, 0x80DEB1FE3B1696B1, 0x9BDC06A725C71235, 0xC19BF174CF692694,
  2003.     0xE49B69C19EF14AD2, 0xEFBE4786384F25E3, 0x0FC19DC68B8CD5B5, 0x240CA1CC77AC9C65,
  2004.     0x2DE92C6F592B0275, 0x4A7484AA6EA6E483, 0x5CB0A9DCBD41FBD4, 0x76F988DA831153B5,
  2005.     0x983E5152EE66DFAB, 0xA831C66D2DB43210, 0xB00327C898FB213F, 0xBF597FC7BEEF0EE4,
  2006.     0xC6E00BF33DA88FC2, 0xD5A79147930AA725, 0x06CA6351E003826F, 0x142929670A0E6E70,
  2007.     0x27B70A8546D22FFC, 0x2E1B21385C26C926, 0x4D2C6DFC5AC42AED, 0x53380D139D95B3DF,
  2008.     0x650A73548BAF63DE, 0x766A0ABB3C77B2A8, 0x81C2C92E47EDAEE6, 0x92722C851482353B,
  2009.     0xA2BFE8A14CF10364, 0xA81A664BBC423001, 0xC24B8B70D0F89791, 0xC76C51A30654BE30,
  2010.     0xD192E819D6EF5218, 0xD69906245565A910, 0xF40E35855771202A, 0x106AA07032BBD1B8,
  2011.     0x19A4C116B8D2D0C8, 0x1E376C085141AB53, 0x2748774CDF8EEB99, 0x34B0BCB5E19B48A8,
  2012.     0x391C0CB3C5C95A63, 0x4ED8AA4AE3418ACB, 0x5B9CCA4F7763E373, 0x682E6FF3D6B2B8A3,
  2013.     0x748F82EE5DEFB2FC, 0x78A5636F43172F60, 0x84C87814A1F0AB72, 0x8CC702081A6439EC,
  2014.     0x90BEFFFA23631E28, 0xA4506CEBDE82BDE9, 0xBEF9A3F7B2C67915, 0xC67178F2E372532B,
  2015.     0xCA273ECEEA26619C, 0xD186B8C721C0C207, 0xEADA7DD6CDE0EB1E, 0xF57D4F7FEE6ED178,
  2016.     0x06F067AA72176FBA, 0x0A637DC5A2C898A6, 0x113F9804BEF90DAE, 0x1B710B35131C471B,
  2017.     0x28DB77F523047D84, 0x32CAAB7B40C72493, 0x3C9EBE0A15C9BEBC, 0x431D67C49C100D4C,
  2018.     0x4CC5D4BECB3E42B6, 0x597F299CFC657E2A, 0x5FCB6FAB3AD6FAEC, 0x6C44198C4A475817,
  2019. ]
  2020.  
  2021.  
  2022. # Initial message schedule
  2023. W = [0] * 80
  2024.  
  2025.  
  2026. # Get user input for the message
  2027. message = input("Enter the message: ").encode('utf-8')
  2028. bit_len = len(message) * 8
  2029. message += b'\x80'
  2030. while (len(message) + 8) % 128 != 0:
  2031.     message += b'\x00'
  2032. message += bit_len.to_bytes(8, 'big')
  2033.  
  2034.  
  2035.  
  2036.  
  2037. # Process the message in blocks of 1024 bits
  2038. for i in range(0, len(message), 128):
  2039.     block = message[i:i+128]
  2040.    
  2041.     # Break the block into 64 64-bit words
  2042.     for j in range(16):
  2043.         W[j] = int.from_bytes(block[j*8:(j+1)*8], 'big')
  2044.  
  2045.  
  2046.     # Extend the 16 64-bit words into 80 64-bit words
  2047.     for j in range(16, 80):
  2048.         s0 = (W[j-15] >> 19 | W[j-15] << 63) ^ (W[j-15] >> 8 | W[j-15] << 56) ^ (W[j-15] >> 7)
  2049.         s1 = (W[j-2] >> 1 | W[j-2] << 45) ^ (W[j-2] >> 61 | W[j-2] << 3) ^ (W[j-2] >> 6)
  2050.         W[j] = (W[j-16] + s0 + W[j-7] + s1) & 0xFFFFFFFFFFFFFFFF
  2051.  
  2052.  
  2053.     # Initialize working variables
  2054.     a, b, c, d, e, f, g, h = a, b, c, d, e, f, g, h
  2055.  
  2056.  
  2057.     # Main loop
  2058.     for j in range(80):
  2059.         s0 = (a >> 28 | a << 36) ^ (a >> 34 | a << 30) ^ (a >> 39 | a << 25)
  2060.         s1 = (e >> 14 | e << 50) ^ (e >> 18 | e << 26) ^ (e >> 41 | e << 23)
  2061.         ch = (e & f) ^ (~e & g)
  2062.         maj = (a & b) ^ (a & c) ^ (b & c)
  2063.         temp1 = h + s1 + ch + K[j] + W[j]
  2064.         temp2 = s0 + maj
  2065.  
  2066.  
  2067.         h = g
  2068.         g = f
  2069.         f = e
  2070.         e = (d + temp1) & 0xFFFFFFFFFFFFFFFF
  2071.         d = c
  2072.         c = b
  2073.         b = a
  2074.         a = (temp1 + temp2) & 0xFFFFFFFFFFFFFFFF
  2075.  
  2076.  
  2077.         # Print values for each word and round
  2078.         print(f"w{j+1:02} = {W[j]:016X} Round {j+1}: a = {a:016X} b = {b:016X} c = {c:016X} d = {d:016X} e = {e:016X} f = {f:016X} g = {g:016X} h = {h:016X}\n")
  2079.     print("new block")  
  2080.  
  2081.  
  2082. # Print the final hash value
  2083. hash_result = (a, b, c, d, e, f, g, h)
  2084. final_hash = ''.join(format(word, '016X') for word in hash_result)
  2085. print(f"Final Hash/Message Digest (512 bits): {final_hash}")
  2086.  
  2087.  
  2088.  
  2089.  
  2090.  
  2091. 7. DSS
  2092. import socket
  2093. import struct
  2094.  
  2095. def sha1(message):
  2096.     # Initialize variables
  2097.     h0 = 0x67452301
  2098.     h1 = 0xEFCDAB89
  2099.     h2 = 0x98BADCFE
  2100.     h3 = 0x10325476
  2101.     h4 = 0xC3D2E1F0
  2102.  
  2103.     # Pre-processing
  2104.     original_message = message
  2105.     message = bytearray(message, 'utf-8')
  2106.     ml = len(original_message) * 8  # Length of original message in bits
  2107.     message.append(0x80)  # Append bit '1' to the message
  2108.     while len(message) % 64 != 56:
  2109.         message.append(0x00)  # Append bits '0' to the message until message length is 64 bits less than multiple of 512
  2110.     message += struct.pack('>Q', ml)  # Append original message length in bits as 64-bit big-endian integer
  2111.  
  2112.     # Process message in 512-bit chunks
  2113.     for i in range(0, len(message), 64):
  2114.         chunk = message[i:i+64]
  2115.  
  2116.         # Break chunk into sixteen 32-bit big-endian words
  2117.         words = [0] * 80
  2118.         for j in range(16):
  2119.             words[j] = struct.unpack('>I', chunk[j*4:j*4+4])[0]
  2120.  
  2121.         # Extend the sixteen 32-bit words into eighty 32-bit words
  2122.         for j in range(16, 80):
  2123.             words[j] = left_rotate(words[j-3] ^ words[j-8] ^ words[j-14] ^ words[j-16], 1)
  2124.  
  2125.         # Initialize hash value for this chunk
  2126.         a = h0
  2127.         b = h1
  2128.         c = h2
  2129.         d = h3
  2130.         e = h4
  2131.  
  2132.         # Main loop
  2133.         for j in range(80):
  2134.             if j < 20:
  2135.                 f = (b & c) | ((~b) & d)
  2136.                 k = 0x5A827999
  2137.             elif 20 <= j < 40:
  2138.                 f = b ^ c ^ d
  2139.                 k = 0x6ED9EBA1
  2140.             elif 40 <= j < 60:
  2141.                 f = (b & c) | (b & d) | (c & d)
  2142.                 k = 0x8F1BBCDC
  2143.             else:
  2144.                 f = b ^ c ^ d
  2145.                 k = 0xCA62C1D6
  2146.  
  2147.             temp = left_rotate(a, 5) + f + e + k + words[j] & 0xFFFFFFFF
  2148.             e = d
  2149.             d = c
  2150.             c = left_rotate(b, 30)
  2151.             b = a
  2152.             a = temp
  2153.  
  2154.         # Add this chunk's hash to result so far
  2155.         h0 = (h0 + a) & 0xFFFFFFFF
  2156.         h1 = (h1 + b) & 0xFFFFFFFF
  2157.         h2 = (h2 + c) & 0xFFFFFFFF
  2158.         h3 = (h3 + d) & 0xFFFFFFFF
  2159.         h4 = (h4 + e) & 0xFFFFFFFF
  2160.  
  2161.     # Produce the final hash value
  2162.     return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)
  2163.  
  2164. def left_rotate(n, d):
  2165.     return ((n << d) | (n >> (32 - d))) & 0xFFFFFFFF
  2166.  
  2167. def calculate_values(p, q, g, k, hm, x):
  2168.     # Calculate y
  2169.     y = pow(g, x, p)
  2170.  
  2171.     # Calculate r
  2172.     r = pow(g, k, p) % q
  2173.  
  2174.     # Calculate s
  2175.     k_inverse = pow(k, -1, q)
  2176.     s = (k_inverse * (int(hm, 16) + x * r)) % q
  2177.  
  2178.     # Calculate w
  2179.     w = pow(s, -1, q)
  2180.  
  2181.     # Calculate u1 and u2
  2182.     u1 = (int(hm, 16) * w) % q
  2183.     u2 = (r * w) % q
  2184.  
  2185.     # Calculate v
  2186.     v = (pow(g, u1, p) * pow(y, u2, p)) % p % q
  2187.  
  2188.     return y, r, s, w, u1, u2, v
  2189.  
  2190. def main():
  2191.     # Client configuration
  2192.     host = '127.0.0.1'
  2193.     port = 12345
  2194.  
  2195.     # Create a socket object
  2196.     client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2197.  
  2198.     # Connect to the server
  2199.     client_socket.connect((host, port))
  2200.  
  2201.     # Gather inputs from the user
  2202.     p = int(input("Enter the value of p: "))
  2203.     q = int(input("Enter the value of q: "))
  2204.     g = int(input("Enter the value of g: "))
  2205.     k = int(input("Enter the value of k (User's per-Message Secret Number): "))
  2206.     message = input("Enter the message: ")
  2207.  
  2208.     # Calculate hash value (SHA-1)
  2209.     hm = sha1(message)
  2210.     print(f"The hash value of {message} (SHA-1): {hm}")
  2211.  
  2212.     x = int(input("Enter the value of x (User's Private Key): "))
  2213.  
  2214.     # Calculate values
  2215.     y, r, s, w, u1, u2, v = calculate_values(p, q, g, k, hm, x)
  2216.  
  2217.     # Print signature
  2218.     print(f"Signature: [r:{r},s:{s}]")
  2219.  
  2220.     # Ask user if they want to send the correct message
  2221.     send_correct = input("Do you want to send the correct message? (y/n): ")
  2222.  
  2223.     if send_correct.lower() == 'y':
  2224.         correct_message = input("Enter the correct message: ")
  2225.         correct_hm = sha1(correct_message)
  2226.         print(f"The hash value of {correct_message} (SHA-1): {correct_hm}")
  2227.  
  2228.         # Calculate u1 for correct message
  2229.         correct_u1 = (int(correct_hm, 16) * w) % q
  2230.  
  2231.         # Calculate v for correct message
  2232.         correct_v = (pow(g, correct_u1, p) * pow(y, u2, p)) % p % q
  2233.  
  2234.         # Send correct message values to the server
  2235.         data = f"{p},{q},{g},{k},{correct_hm},{x},{y},{r},{s},{w},{correct_u1},{u2},{correct_v}"
  2236.     else:
  2237.         # Send original message values to the server
  2238.         data = f"{p},{q},{g},{k},{hm},{x},{y},{r},{s},{w},{u1},{u2},{v}"
  2239.     print("Data Sent successfully to the Client")    
  2240.  
  2241.     # Send inputs and calculated values to the server
  2242.     client_socket.send(data.encode())
  2243.  
  2244.     # Close the connection
  2245.     client_socket.close()
  2246.  
  2247. if _name_ == "_main_":
  2248.     main()
  2249. import socket
  2250.  
  2251. def main():
  2252.     # Server configuration
  2253.     host = '127.0.0.1'
  2254.     port = 12345
  2255.  
  2256.     # Create a socket object
  2257.     server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2258.  
  2259.     # Bind the socket to the address
  2260.     server_socket.bind((host, port))
  2261.  
  2262.     # Listen for incoming connections
  2263.     server_socket.listen(1)
  2264.     print("Server is listening on port", port)
  2265.  
  2266.     # Accept a connection
  2267.     client_socket, addr = server_socket.accept()
  2268.     print("Connection from", addr)
  2269.  
  2270.     # Receive data from the client
  2271.     data = client_socket.recv(1024).decode()
  2272.     print("Received data from server:", data)
  2273.  
  2274.     # Split received data into individual values
  2275.     values = data.split(',')
  2276.  
  2277.     # Display received values
  2278.     print("Received values from server:")
  2279.     print("p:", values[0])
  2280.     print("q:", values[1])
  2281.     print("g:", values[2])
  2282.     print("k:", values[3])
  2283.     print("hm:", values[4])
  2284.     print("x:", values[5])
  2285.     print("y:", values[6])
  2286.     print("s:", values[8])
  2287.     print("\n")
  2288.     print("Verification:")
  2289.     print("w:", values[9])
  2290.     print("u1:", values[10])
  2291.     print("u2:", values[11])
  2292.     print("v:", values[12])
  2293.     print("\n")
  2294.     print("r' (from sender):", values[7])
  2295.     print("v  (calculated):", values[12])
  2296.  
  2297.     # Perform DSS verification
  2298.     r = int(values[8])
  2299.     v = int(values[11])
  2300.     if v == r:
  2301.         print("Digital Signature Standard (DSS) verification Successful")
  2302.     else:
  2303.         print("Digital Signature Standard (DSS) Verification Failed")
  2304.  
  2305.     # Close the connection
  2306.     client_socket.close()
  2307.  
  2308. if _name_ == "_main_":
  2309.     main()

Editor

You can edit this paste and save as new:


File Description
  • sys
  • Paste Code
  • 30 Apr-2024
  • 60.32 Kb
You can Share it: