How to use generate_key_pairs method in lisa

Best Python code snippet using lisa_python

rsa.py

Source: rsa.py Github

copy

Full Screen

...45 gcd, x, y = self.extended_euclid_gcd(A, M)46 while x < 0 :47 x += M48 return x49 def generate_key_pairs(self, bits: int = 16) :50 """51 Generate two key pairs: public key (e, n) and private key (d, n)52 """53 if bits < 4 :54 raise Exception("The number of bits must be greater than 4")55 self.p = prime.generate_prime_number(bits)56 self.q = prime.generate_prime_number(bits)57 self.n = self.p * self.q58 self.phi_n = (self.p-1) * (self.q-1)59 while not self.is_coprime(self.e, self.phi_n) :60 self.e = prime.generate_n_bits_number(bits)61 self.d = self.modulo_multiplicative_inverse(self.e, self.phi_n)62 self.public_key = (self.e, self.n)63 self.private_key = (self.d, self.n)64 def save_public_key(self, filename: str) :65 """66 Save public key as *.pub file67 """68 public_key = self.get_public_key()69 with open(os.path.join(RSA.datadir, filename, (filename + '.pub')), 'w') as f_pub :70 f_pub.write(str(public_key[0]) + '\n')71 f_pub.write(str(public_key[1]))72 def save_private_key(self, filename: str) :73 """74 Save private key as *.pri file75 """76 private_key = self.get_private_key()77 with open(os.path.join(RSA.datadir, filename, (filename + '.pri')), 'w') as f_pri :78 f_pri.write(str(private_key[0]) + '\n')79 f_pri.write(str(private_key[1]))80 def save_key_pairs(self, filename: str) :81 """82 Save both key pairs: public and private key83 """84 if not os.path.exists(os.path.join(RSA.datadir, filename)) :85 os.makedirs(os.path.join(RSA.datadir, filename))86 self.save_public_key(filename)87 self.save_private_key(filename)88 def get_public_key(self) :89 """90 Returns the current public key91 """92 return self.public_key93 def get_private_key(self) :94 """95 Returns the current private key96 """97 return self.private_key98 def encrypt(self, plaintext: bytearray) -> str:99 """100 Encrypt plaintext by public key pair using RSA algorithm101 """102 if len(plaintext) == 0 :103 raise Exception("Plaintext cannot be empty")104 if not isinstance(plaintext, (bytes, bytearray)):105 raise Exception("Plaintext must be instance of bytes or bytearray")106 e, n = self.get_public_key()107 ciphertext = ''108 for i in range(len(plaintext)) :109 c = pow(plaintext[i], e, n)110 ciphertext += r'\{}'.format(hex(c)[1:])111 return ciphertext112 def decrypt(self, ciphertext: str) :113 """114 Decrypt ciphertext by private key pair using RSA algorithm115 """116 if len(ciphertext) == 0 :117 raise Exception("Ciphertext cannot be empty")118 d, n = self.get_private_key()119 ciphertext_list = ciphertext.split("\\x")120 plaintext = []121 for i in range(len(ciphertext_list)) :122 try :123 p = pow(int(ciphertext_list[i], 16), d, n)124 plaintext.append(p)125 except ValueError :126 continue127 return plaintext128# rsa = RSA()129# # rsa.generate_key_pairs(16)130# rsa.generate_key_pairs(64)131# # rsa.generate_key_pairs(256)132# # rsa.generate_key_pairs(1024)133# plaintext = "Kriptografi dan Koding"#.encode("utf-8")134# encrypted = rsa.encrypt(plaintext)135# print(encrypted)136# decrypted = rsa.decrypt(encrypted)137# print(decrypted)...

Full Screen

Full Screen

keys_generator.py

Source: keys_generator.py Github

copy

Full Screen

...6 self.type = type7 self.private_key = None8 self.public_key = None9 self.path = path10 def generate_key_pairs(self):11 self.private_key = rsa.generate_private_key(12 public_exponent=65537,13 key_size=4096,14 backend=default_backend()15 )16 self.public_key = self.private_key.public_key()17 if self.type == 1:18 self.save_pem_keys()19 elif self.type == 2:20 self.save_der_keys()21 def save_pem_keys(self):22 encrypted_privatekey_pem = self.private_key.private_bytes(23 encoding=serialization.Encoding.PEM,24 format=serialization.PrivateFormat.PKCS8,25 encryption_algorithm=serialization.BestAvailableEncryption(password=b'CY6740')26 )27 publickey_pem = self.public_key.public_bytes(28 encoding=serialization.Encoding.PEM,29 format=serialization.PublicFormat.SubjectPublicKeyInfo30 )31 with open(self.path + "privatekey.pem", "w") as prikey_file:32 prikey_file.write(encrypted_privatekey_pem.decode())33 with open(self.path + "publickey-pem.pub", "w") as pubkey_file:34 pubkey_file.write(publickey_pem.decode())35 def save_der_keys(self):36 encrypted_privatekey_der = self.private_key.private_bytes(37 encoding=serialization.Encoding.DER,38 format=serialization.PrivateFormat.PKCS8,39 encryption_algorithm=serialization.BestAvailableEncryption(password=b'CY6740')40 )41 publickey_der = self.public_key.public_bytes(42 encoding=serialization.Encoding.DER,43 format=serialization.PublicFormat.SubjectPublicKeyInfo44 )45 with open(self.path + "privatekey.der", "w") as prikey_file:46 prikey_file.write(encrypted_privatekey_der.decode())47 with open(self.path + "publickey-der.pub", "w") as pubkey_file:48 pubkey_file.write(publickey_der.decode())49if __name__ == "__main__":50 type_of_keys = 2 # Type 1 is for PEM and 2 for DER51 if type_of_keys == 1:52 sender_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​senderkeys/​", type=type_of_keys)53 sender_keys_gen.generate_key_pairs()54 receiver_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​receiverkeys/​", type=type_of_keys)55 receiver_keys_gen.generate_key_pairs()56 attacker_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​attackerkeys/​", type=type_of_keys)57 attacker_keys_gen.generate_key_pairs()58 elif type_of_keys == 2:59 sender_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​senderkeys/​", type=type_of_keys)60 sender_keys_gen.generate_key_pairs()61 receiver_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​receiverkeys/​", type=type_of_keys)62 receiver_keys_gen.generate_key_pairs()63 attacker_keys_gen = KeysGenerator(path="/​home/​abhiram/​Desktop/​CY6740/​ProblemSet-2/​target/​attackerkeys/​", type=type_of_keys)...

Full Screen

Full Screen

ecc.py

Source: ecc.py Github

copy

Full Screen

1import sys2from Crypto.PublicKey import ECC3def generate_key_pairs(id):4 private_key = ECC.generate(curve='P-256')5 public_key = private_key.public_key()6 with open(f'{id}_key.pub', 'w') as f:7 f.write(public_key.export_key(format='PEM'))8 with open(f'{id}_key.pri', 'w') as f:9 f.write(private_key.export_key(format='PEM'))10def main():11 generate_key_pairs(sys.argv[1])12if __name__ == '__main__':...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Handle Multiple Windows In Selenium Python

Automating testing is a crucial step in the development pipeline of a software product. In an agile development environment, where there is continuous development, deployment, and maintenance of software products, automation testing ensures that the end software products delivered are error-free.

Joomla Testing Guide: How To Test Joomla Websites

Before we discuss the Joomla testing, let us understand the fundamentals of Joomla and how this content management system allows you to create and maintain web-based applications or websites without having to write and implement complex coding requirements.

Starting &#038; growing a QA Testing career

The QA testing career includes following an often long, winding road filled with fun, chaos, challenges, and complexity. Financially, the spectrum is broad and influenced by location, company type, company size, and the QA tester’s experience level. QA testing is a profitable, enjoyable, and thriving career choice.

The Art of Testing the Untestable

It’s strange to hear someone declare, “This can’t be tested.” In reply, I contend that everything can be tested. However, one must be pleased with the outcome of testing, which might include failure, financial loss, or personal injury. Could anything be tested when a claim is made with this understanding?

How To Create Custom Menus with CSS Select

When it comes to UI components, there are two versatile methods that we can use to build it for your website: either we can use prebuilt components from a well-known library or framework, or we can develop our UI components from scratch.

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run lisa automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful