Using sockets and/or threading in Python, how can I run the encryption and decryption (separate files) 100 times only running the programs once?

P

Preston Watts

Guest
Preston Watts Asks: Using sockets and/or threading in Python, how can I run the encryption and decryption (separate files) 100 times only running the programs once?
As of right now, I have my program working where it encrypts the message in the server program and then sends it to the client which is a separate program. The client then decrypts the message and prints the plaintext message to the terminal. Currently, it is only set up to do this once, but I was wondering how I could do this to have it run 100 times. The library for the cryptography algorithms is the python cryptography library. My end goal would be if the user decides to enter "2" which is the choice where the program would do encryption and decryption 100 times. The server would be able to send each encrypted message to the client and the client would decrypt it, doing that each time for 100 times.

AES_alice.py (server code)

Code:
import os, socket, threading
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding


PORT = 7777
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)

def generate_key_AES():
    # generate secret key and write key to shared file
    secret_key = os.urandom(16)
    return secret_key

def encrypt_AES(plaintext_msg, key):
    # add padding bits to message if message is too long or too short (not multiple of key)
    padder = padding.PKCS7(128).padder()
    plaintext_msg = padder.update(plaintext_msg)
    plaintext_msg += padder.finalize()
    # create random initilization vector
    iv = os.urandom(16)
    # begin the AES encryption
    AES_cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    AES_encryptor = AES_cipher.encryptor()
    AES_ciphertext = AES_encryptor.update(plaintext_msg) + AES_encryptor.finalize()
    return iv, AES_ciphertext

# establish connection with client and accept request
server = socket.socket()
server.bind(ADDR)
server.listen()
plaintext_msg = ""
while True:
    user_choice = input("Enter 1 for Encryption --- Enter 2 for AES time testing --- Enter 0 for Program Quit: ")
    if int(user_choice) == 1:
        while len(plaintext_msg) != 18:
            plaintext_msg = input("Enter plaintext message to be encrypted (must be 18 bytes): ")
        plaintext_msg = bytes(plaintext_msg, 'utf-8')
        key = generate_key_AES()
        iv, ciphertext = encrypt_AES(plaintext_msg, key)
        client, addr = server.accept()
        client.send(key)
        client.send(iv)
        client.send(ciphertext)
    elif int(user_choice) == 2:
        while len(plaintext_msg) != 7:
            plaintext_msg = input("Enter plaintext message to be encrypted (must be 7 bytes): ")
        plaintext_msg = bytes(plaintext_msg, 'utf-8')
        key = generate_key_AES()
        iv, ciphertext = encrypt_AES(plaintext_msg, key)
        client, addr = server.accept()
        client.send(key)
        client.send(iv)
        client.send(ciphertext)
    elif int(user_choice) == 0:
        server.close()
        exit()

AES_bob.py (client code)

Code:
import socket, threading
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding

PORT = 7777
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)

def decrypt_AES(key, iv, ciphertext_msg):
    # begin the AES decryption
    AES_cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    AES_decryptor = AES_cipher.decryptor()
    AES_plaintext = AES_decryptor.update(ciphertext_msg)
    # unpad the resulting ciphertext to only leave the original message
    unpadder = padding.PKCS7(128).unpadder()
    AES_plaintext = unpadder.update(AES_plaintext)
    AES_plaintext += unpadder.finalize()
    print(AES_plaintext.decode())

# establish connection with server and save values sent from server
client = socket.socket()
client.connect(ADDR)
key = client.recv(16)
iv = client.recv(16)
ciphertext = client.recv(32)
# call the decrypt function and pass in correct values
print("Message decrypted using AES decryption:")
decrypt_AES(key, iv, ciphertext)
client.close()

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.
 
/forums/whats-new/news-feed

Unreplied Posts

If statement in C++ with more than one variable

ralph2437 Asks: If statement in C++ with more than one variable
I started trying to code in C++ and I made a very simple game. As the game has more than one viable solution, I tried to make an if with more than one variable, but it doesn't seem to work as it doesn't matter the number I type, it always says I'm correct.

Code:
int main() {
string Username;
cout << "Type your name: "; cin >> Username; cout << endl;
cout << " Welcome, " << Username << endl;
cout << "   Guess this number!\n";
int Ale = 0;
while(Ale == 0){
    int const ContraC = 134, ContraC2 = 143, ContraC3 = 341, ContraC4 = 314, ContraC5 = 431, ContraC6 = 413;
    int Contra;

    cout << endl;
    cout << "  It is an integer, the three digits add up to 8, and the product of their digits is 12"; cout << endl;
    cout << "  >>>>>>> Type the password and press Enter:"; cin >> Contra;

    if(Contra == ContraC, ContraC2, ContraC3, ContraC4, ContraC5, ContraC6){
        cout << "   Good job! Now press any key to exit the game";
        Ale = 2;
        cout << endl;
        cout << endl;
    } else {
        cout << "   Try again!";
        Ale = 0;
        cout << endl;
    }
}
system("pause > nul");

I saw that the error is here if(Contra == ContraC, ContraC2, ContraC3, ContraC4, ContraC5, ContraC6){ because if I change it to this:

Code:
if(Contra == ContraC){

it only works with the first variable.

I was wondering how I can use more than one variable in this if. Thank you, ralph.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

PHPSpreadsheet: How to find last cell in worksheet

ND_Coder Asks: PHPSpreadsheet: How to find last cell in worksheet
According to the PHPSpreadsheet docs "Accessing cells in a Spreadsheet should be pretty straightforward." but the only references are to finding cells by cell coordinate such as:

Code:
$spreadsheet->getActiveSheet()
    ->getCell('B8')
    ->setValue('Some value');

What I am trying to do is something I thought would be simple and that is to locate the last cell with input and make that the active cell. I am finding references in SO and PHPSpreadsheet docs to an iterator like this:

Code:
foreach ($worksheet->getRowIterator() as $row) {
    echo '<tr>' . PHP_EOL;
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(TRUE);

... but that seems like a lot just to find the last cell with input. Does anyone have any bright ideas on this? Is there any type of end-of-worksheet code in PHPSpreadsheet?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Smooth model created in Blender has surface imperfections in SceneKit

West1 Asks: Smooth model created in Blender has surface imperfections in SceneKit
So, this might be a SceneKit/iOS problem -- but it might instead be a Blender problem. This question presupposes the former.

Let's say I open a fresh project in Blender (nothing fancy) and export the default cube it creates as a dae file. I then import that dae file into my Xcode SceneKit project.

This particular SceneKit project consists of a scene in which a small ball rolls around on the top surface of a cube.

The problem: If I use SceneKit's built-in SCNBox shape for the cube (with a static, convexHull physics body), the ball rolls smoothly, as desired. But if I use the model exported from Blender, the ball bounces along the cube's surface as though it were covered in small, invisible bumps.

What I've tried:

  1. I tried increasing the ball's mass from 2.0 to 100.0 just to see if that would affect the outcome.
  2. I tried applying some smoothing modifiers to the model in Blender in hopes that it would be free of imperfections.
  3. I tried converting the dae file to SceneKit's own scn file.
  4. I tried configuring the SCNPhysicsShape's options parameter in various ways, including the use of .scale, .type, .collisionMargin, and .keepAsCompound. Example:

Code:
let shape = SCNPhysicsShape(node: cube, options: [.scale: cube.scale, .collisionMargin: 0.1])
  1. I tried changing the friction and restitution of both the cube and ball. Less friction/restitution did not solve the problem, nor did more of it.
  2. I tried disabling continuous collision detection by removing the ball's continuousCollisionDetectionThreshold.

I'm not sure how the following code will help diagnose this problem, but here it is anyway:

Code:
//Create the cube's physics body:
let shape = SCNPhysicsShape(node: cube)             
cube.physicsBody = SCNPhysicsBody(type: .static, shape: shape)

cube.physicsBody?.categoryBitMask = CollisionTypes.floor.rawValue
cube.physicsBody?.collisionBitMask = CollisionTypes.dynamicObjects.rawValue
cube.physicsBody?.contactTestBitMask = CollisionTypes.nothing.rawValue
cube.physicsBody?.isAffectedByGravity = false
cube.physicsBody?.allowsResting = false
cube.physicsBody?.restitution = 0.5
cube.physicsBody?.friction = 0.75

//Create the ball's physics body:
let ballGeo = SCNSphere(radius: 0.5)
ballNode?.physicsBody = SCNPhysicsBody(
   type: .dynamic,
   shape: SCNPhysicsShape(
        geometry: ballGeo
   )
)
        
ballNode?.physicsBody?.categoryBitMask = CollisionTypes.dynamicObjects.rawValue
ballNode?.physicsBody?.contactTestBitMask = CollisionTypes.staticObjects.rawValue
ballNode?.physicsBody?.collisionBitMask = CollisionTypes.staticObjects.rawValue | CollisionTypes.floor.rawValue
ballNode?.physicsBody?.allowsResting = false
ballNode?.physicsBody?.continuousCollisionDetectionThreshold = 0.9 //Tried it with and without this property.
ballNode?.physicsBody?.restitution = 0.5
ballNode?.physicsBody?.charge = 4.0
ballNode?.physicsBody?.friction = 0.2
ballNode?.physicsBody?.rollingFriction = 1.0
ballNode?.physicsBody?.angularDamping = 0.4
ballNode?.physicsBody?.mass = 2.0

Question: Why might this problem be occurring? Is it a SceneKit problem, as this question presupposes -- or is it a Blender problem about which I will need to post a question on another forum?

Thanks for your help.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

The last few steps of Porting a Github App to Back4App

Rewind Asks: The last few steps of Porting a Github App to Back4App
I am trying to get a Github Node.js App onto Back4App. It has no databases, it is just an app that needs to run permanently and restart automatically whenever Back4App goes down for maintenance.

From reading, I now realise I need to make a copy of my GitHub project on my local machine first, rather than going straight from Github to Back4App. This is obviously different from my previous host.

This is what I have done so far:

  1. I have made a copy of my Github project on my local machine using ‘$ git clone ’. I have put this in my local directory ‘C:\GIT Local\peerjs-server’
  2. I have b4a.exe in my System32
  3. I have set up my ‘Account Key’ and connected it to my local pc with ‘$ b4a configure accountkey’
  4. I have set up a blank project in my back4app account and named it ‘MyNodeJSApp’.

This is what I still need help with. This is what I need to still do:


  1. I need to work out how to copy my local project in my local folder ‘C:\GIT Local\peerjs-server’ to the correct directories of by Back4App project. I do not know where I should be copying this or how to do it. It is just a node.js project which can be found here: ‘https://github.com/peers/peerjs-server’.


  2. I need to work out how to start my project so it permanently runs on Back4App and will automatically restart if Back4App goes down for maintenance. (There may be a script in these file on here GitHub - peers/peerjs-server: Server for PeerJS, because this seemed to happen automatically on my previous host.)


  3. I need to know what links I then need to put in my client code. It needs to point to my new Back4App project instead of my old previous host project. It needs the correct port. My old code using my old host was:

    let peer = new Peer(idStr, { host: "rgppeerserver.myoldhost.com", port: 443, /* path: '/myapp',*/ secure: true, debug: 0 });

Can anyone give me some tips on 5, 6, 7?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

How can I somehow combine EventCallback<T>?

Sinaesthetic Asks: How can I somehow combine EventCallback<T>?
So I found myself in a situation where I need to subclass a few Blazor components, but one of the reasons is that I need to essentially create a decorator that extends it's functionality. Part of that extension is to tack on some additional event handling. Since components use EventCallback now which isn't a delegate time, I can't simply add another handler to it like you could with multicast delegates. I can replace it, but then that means any consumer of that component cannot register any handler of their own, so now I'm trying to wrap it. Here's a pseudo representation of the scenario and what I'm trying to do

Code:
public class OriginalBlazorComponent : ComponentBase
{
    [Parameter]
    public EventCallback<int> SomethingChanged { get; set; }

    private async Task SomeInternalProcess()
    {
        // ... some work here
        await SomethingChanged.InvokeAsync(1);
    }
}

public class MySubclassedComponent : OriginalBlazorComponent
{
    public override async Task SetParametersAsync(ParameterView parameters)
    {
        // I want to combine anything that the user may have registered with my own handling
        SomethingChanged = EventCallback.Factory.Create(this, async (int i) => 
        {
            // this causes a stack overflow because i just replaced it with this callback
            // so it's essentially calling itself by this point.
            await SomethingChanged.InvokeAsync(i); 

            await DoMyOwnStuff(i);
        });
        
        await base.SetParametersAsync(this);
    }
}

The idea here is that I'm just making sure that the user's handler has been bound by addressing this in SetParametersAsync() so that I can wrap it in a new callback that will call their handler first and then run mine after. But since it's the base component that has the logic which will invoke the EventCallback, that means I need to replace that specific property with my new handler, but in doing so, that means the new handler is calling the old handler which is actually now the new handler, so it's now an infinitely recursive call stack, and causes a stack overflow.

So my first thought was that if I could somehow get a copy of the original EventCallback, or at least extract its delegate so I can create a new callback, then it wouldn't be referencing itself anymore (confused because it's a struct, I thought it would always naturally be a copy), but I can't find any way to do that. I tried just using EventCallback.Factory.Create(this, SomethingChanged) in hopes that it would create a completely new instance of the callback using the same delegate, but it didn't change anything; same result.

This would of course be a non-issue if I could override the original component's SomeInternalProcess() method so that I could insert my process there before or after calling the base method, but it's a 3rd party library.

So in short, is there some way to achieve the same effect as a multicast delegate so that I can preserve any registered handlers but combine with my own? Or is there at least some way dereference the original EventCallback or extract its delegate so that I can create a new one?

e.g.

Code:
// how do I acheive something akin to
SomethingChanged += MyDelegate;

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Latest posts

Top