def generate_keys(self, cr, uid, ids, key_length=1024, key_gen_number=0x10001, context=None): """ Generate key pairs: private and public. """ if context is None: context = {} for signer in self.browse(cr, uid, ids): # Random seed Rand.rand_seed(os.urandom(key_length)) # Generate key pair key = RSA.gen_key(key_length, key_gen_number, lambda *x: None) # Create memory buffers pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() # Save keys to buffers key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) w = { 'key': pri_mem.getvalue(), 'pub': pub_mem.getvalue(), } self.write(cr, uid, signer.id, w) return True
def sign(request): #to do print 'LOG:sign -------------- from ' + getClientIp(request) #the user HaiChiang is fixed in the database user = User.objects.get(userName='******') #create the signrequest signRequest = {} key_handle = user.key_handle Rand.rand_seed(os.urandom(1024)) challenge = urlsafe_b64encode(Rand.rand_bytes(32)) signRequest['signRequests'] = [{'challenge': challenge, 'version': 'U2F_V2', 'appId': 'http://localhost:8000', 'keyHandle': key_handle, "sessionId":"123456"}] #signRequest['registerRequests'] = [] strong_signRequest = {} strong_signRequest['Challenge'] = signRequest strong_signRequest['Message'] = '' strong_signRequest['Error'] = '' user.challenge = challenge return JsonResponse(strong_signRequest)
def encrypt_block(blob, pubkey): """ Encrypt the given blob of data, given the public key provided. :return The encrypted blob. """ # Make a MemoryBuffer of the message. inbuf = BIO.MemoryBuffer(blob) # Seed the PRNG. Rand.rand_seed(os.urandom(1024)) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt to. x509 = X509.load_cert(pubkey) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: AES 256 bit in CBC mode. s.set_cipher(SMIME.Cipher('aes_256_cbc')) # Encrypt the buffer. p7 = s.encrypt(inbuf) temp_buff = BIO.MemoryBuffer() s.write(temp_buff, p7) x = temp_buff.read() return x
def _create_new_rsa_key_pairs(self): """ Creates a new rsa key-pair. """ def _blank_callback(self): "Replace the default dashes as output upon key generation" return algorithm = 'rsa' for mode, key_pair in Cryptor._VALID_MODES.get(algorithm).iteritems(): # Random seed Rand.rand_seed(os.urandom(Cryptor.RSA_KEY_LENGTH)) # Generate key pair key = RSA.gen_key(Cryptor.RSA_KEY_LENGTH, 65537, _blank_callback) # create and save the public key to file filename = key_pair.get('public', None) if key.save_pub_key(''.join(filename)) > 0: print '(*) Created new {0} {1} {2}'.format(algorithm, mode, filename) else: print '( ) Failed to create new {0} {1} {2}'.format(algorithm, mode, filename) # create and save the private key to file filename = key_pair.get('private', None) # key.save_key('user-private-local.pem'), e.g if suffix='' if filename: if key.save_key(''.join(filename), None) > 0: print '(*) Created new {0} {1} key {2}'.format(algorithm, mode, filename) else: print '( ) Failed to create new {0} {1} key {2}'.format(algorithm, mode, filename)
def login(self,pin): self.session = self.pkcs11.openSession(self.tokenSlot) self.session.login(pin=pin) random = ''.join(chr(i) for i in self.session.generateRandom(size=1024)) objects = self.session.findObjects() my_cert = None privkey_id = None for obj in objects: print self.session.getAttributeValue(obj, [PyKCS11.CKA_LABEL]) my_cert = self.FindMyCert(my_cert, obj) privkey_id = self.FindPrivateId(obj, privkey_id) self.key_id = ''.join(chr(c) for c in privkey_id[0]).encode('hex') self.my_cert = X509.load_cert_der_string(''.join(chr(c) for c in my_cert)) Rand.rand_seed(random) # init the OpenSSL engine and load the user cert & private key ssl_key = 'slot_' + str(self.tokenSlot) + '-id_' + self.key_id self.my_pkey = self.engine.load_private_key(ssl_key, pin) ctx = SSL.Context('sslv23') m2.ssl_ctx_use_x509(ctx.ctx,self.my_cert.x509) m2.ssl_ctx_use_pkey_privkey(ctx.ctx,self.my_pkey.pkey) if not m2.ssl_ctx_check_privkey(ctx.ctx): raise ValueError, 'public/private key mismatch' ctx.set_verify(SSL.verify_peer, 10) self.ssl_ctx = ctx print self.my_cert print self.my_pkey self.session.logout() print str(threading.currentThread().name)+" finished"
def make_key_pair(key_length=1024): "Make public/private keys" Rand.rand_seed (os.urandom (key_length)) key = RSA.gen_key (key_length, 65537, blank_callback) pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) return pub_mem.getvalue(), pri_mem.getvalue()
def make_key_pair(key_length=2048): "Make public/private keys" Rand.rand_seed(os.urandom(key_length)) key = RSA.gen_key(key_length, 65537, blank_callback) pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) return pub_mem.getvalue(), pri_mem.getvalue()
def gen_challenge(): enrollRequest = {} enrollRequest['signrequest'] = [] Rand.rand_seed(os.urandom(1024)) #challenge = urlsafe_b64encode(Rand.rand_bytes(32)) challenge = "mLkHCmQZGbZEXefhWByeKo5zTFldYLIZFRGeHdvTFBc=" enrollRequest['registerRequests'] = [{'challenge': challenge, 'version': 'U2F_V2', 'appId': 'http://localhost:8000'}] return enrollRequest, challenge
def _sign(self, action_result, message): # Make a MemoryBuffer of the message. buf = BIO.MemoryBuffer(message) # Seed the random number generator with 1024 random bytes (8192 bits). Rand.rand_seed(os.urandom(1024)) # Instantiate an SMIME object; set it up; sign the buffer. s = SMIME.SMIME() s.load_key_bio(BIO.MemoryBuffer(self._keys['private']), BIO.MemoryBuffer(self._keys['public'])) return s, s.sign(buf, SMIME.PKCS7_DETACHED)
def generatewalletkeys(self,fname): privpem=fname+"-private.pem" pubpem=fname+"-public.pem" # Random seed Rand.rand_seed (os.urandom (self.KEY_LENGTH)) # Generate key pair key = RSA.gen_key (self.KEY_LENGTH, 65537) #Save private key key.save_key (privpem, None) #Save public key key.save_pub_key (pubpem) print "Wallet keys has been generated" return
def RunOnce(self): """This is run only once.""" # Initialize the PRNG. Rand.rand_seed(Rand.rand_bytes(1000)) # Counters used here stats.STATS.RegisterCounterMetric("grr_client_unknown") stats.STATS.RegisterCounterMetric("grr_decoding_error") stats.STATS.RegisterCounterMetric("grr_decryption_error") stats.STATS.RegisterCounterMetric("grr_rekey_error") stats.STATS.RegisterCounterMetric("grr_authenticated_messages") stats.STATS.RegisterCounterMetric("grr_unauthenticated_messages") stats.STATS.RegisterCounterMetric("grr_rsa_operations")
def generatekeys(self): # Random seed Rand.rand_seed (os.urandom (self.KEY_LENGTH)) # Generate key pair key = RSA.gen_key (self.KEY_LENGTH, 65537) # Create memory buffers pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() # Save keys to buffers key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) # Get keys public_key = pub_mem.getvalue() private_key = pri_mem.getvalue() return public_key, private_key
def sign(filename, pkey, cert, signed_file): """Sign a text file""" try: handle = open(filename, 'rb') filebio = BIO.File(handle) signer = SMIME.SMIME() signer.load_key(pkey, cert) Rand.rand_seed(os.urandom(2048)) p7f = signer.sign(filebio) data = BIO.MemoryBuffer(None) p7f.write_der(data) with open(signed_file, 'wb') as handle: handle.write(data.read()) return True except (IOError, SMIME.SMIME_Error, SMIME.PKCS7_Error), msg: raise ValueError(str(msg))
def test_seed_add(self): self.assertIsNone(Rand.rand_seed(os.urandom(1024))) # XXX Should there be limits on the entropy parameter? self.assertIsNone(Rand.rand_add(os.urandom(2), 0.5)) Rand.rand_add(os.urandom(2), -0.5) Rand.rand_add(os.urandom(2), 5000.0)
def gen_enroll_challenge(): enrollRequest = {} enrollRequest['SignRequest'] = [] Rand.rand_seed(os.urandom(1024)) challenge = urlsafe_b64encode(Rand.rand_bytes(32)) enrollRequest['RegisterRequest'] = [{'challenge': challenge, 'version': 'U2F_V2', 'appId': 'http://localhost:8000'}] enrollRequest['sessionId'] = '123456' strong_enrollRequest = {} strong_enrollRequest['Challenge'] = enrollRequest strong_enrollRequest['Message'] = '' strong_enrollRequest['Error'] = '' return strong_enrollRequest, challenge
def test_seed_add(self): if sys.version_info >= (2, 4): assert Rand.rand_seed(os.urandom(1024)) is None # XXX Should there be limits on the entropy parameter? assert Rand.rand_add(os.urandom(2), 0.5) is None Rand.rand_add(os.urandom(2), -0.5) Rand.rand_add(os.urandom(2), 5000.0)
def RunOnce(self): """This is run only once.""" # Initialize the PRNG. seed = Rand.rand_bytes(1000) if not seed: raise RuntimeError("Unable to initialize random seed.") Rand.rand_seed(seed) # Counters used here stats.STATS.RegisterCounterMetric("grr_client_unknown") stats.STATS.RegisterCounterMetric("grr_decoding_error") stats.STATS.RegisterCounterMetric("grr_decryption_error") stats.STATS.RegisterCounterMetric("grr_rekey_error") stats.STATS.RegisterCounterMetric("grr_authenticated_messages") stats.STATS.RegisterCounterMetric("grr_unauthenticated_messages") stats.STATS.RegisterCounterMetric("grr_rsa_operations")
def seed_prng(): """ Seed the pseudorandom number generator """ sources = [ 'sensors_temperatures', 'users', 'virtual_memory', 'net_connections', 'pids', 'disk_partitions' ] try: # Python 3 Rand.rand_seed( bytes(''.join([str(getattr(psutil, a, str)()) for a in sources]), 'utf-8')) except TypeError: # Python 2 Rand.rand_seed(str([getattr(psutil, a, str)() for a in sources])) return True
def generate_keys(self, cr, uid, ids, key_length=1024, key_gen_number=0x10001, context=None): """ Generate key pairs: private and public. """ if context is None: context = {} for signer in self.browse(cr, uid, ids): # Random seed Rand.rand_seed(os.urandom(key_length)) # Generate key pair key = RSA.gen_key(key_length, key_gen_number, lambda *x: None) # Create memory buffers pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() # Save keys to buffers key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) w = {"key": pri_mem.getvalue(), "pub": pub_mem.getvalue()} self.write(cr, uid, signer.id, w) return True
def generate_keys(self, key_length=1024, key_gen_number=0x10001): """ Generate key pairs: private and public. """ for signer in self: # Random seed Rand.rand_seed(os.urandom(key_length)) # Generate key pair key = RSA.gen_key(key_length, key_gen_number, lambda *x: None) # Create memory buffers pri_mem = BIO.MemoryBuffer() pub_mem = BIO.MemoryBuffer() # Save keys to buffers key.save_key_bio(pri_mem, None) key.save_pub_key_bio(pub_mem) w = { 'key': pri_mem.getvalue(), 'pub': pub_mem.getvalue(), } signer.write(w) return True
def init(): Rand.rand_seed(os.urandom(num_random_bits/8))
def main(): # seeding the PRNG with 1024 random bytes from OS # from M2Crypto Rand.rand_seed (os.urandom (1024)) while 1: #====================================================== # draw MAIN SCREEN mainScreen = MainScreen() centerWindow(mainScreen, WINDOW_WIDTH_MS, WINDOW_HEIGHT_MS) mainScreen.mainloop() #====================================================== ### begin connecting to the srver # buffer length buffer_length = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # require a certificate from the server myhost = 'localhost' myport = 4321 try: # ssl.CERT_NONE : cause we are using a self signed certificate ssl_sock = ssl.wrap_socket(s,cert_reqs=ssl.CERT_NONE,ssl_version=ssl.PROTOCOL_TLSv1) ssl_sock.connect((myhost, myport)) #print repr(ssl_sock.getpeername()) #print ssl_sock.cipher() #begin to receive DH key exchange data from server #in order of p,g,g^a serverDH_p = base64.b64decode(ssl_sock.read(buffer_length)) serverDH_g = base64.b64decode(ssl_sock.read(buffer_length)) serverDH_pub = base64.b64decode(ssl_sock.read(buffer_length)) myDHobject = DH.set_params(serverDH_p, serverDH_g) # pick random p and generate g^b in myDhobject.pub myDHobject.gen_key() ssl_sock.sendall(base64.b64encode(myDHobject.pub)) # generate shared AES Key sharedAESkey = myDHobject.compute_key(serverDH_pub) # print 'shared AES Key ', hexlify(sharedAESkey) # now we have a secure shared 256-bit AES key to send data around # it was Diffie Hellman, so even if TLS was borked, hopefully noone knows it except: #ZZZ change to msgbox tkMessageBox.showwarning(title = "Connection Error", message = "Cannot connect to server.") ssl_sock.close() # mainScreen.destroy() # print 'Cannot connect to server', myhost , ':' , myport continue #====================================================== # draw AUTHENTICATION SCREEN authScreen = AuthScreen() centerWindow(authScreen, WINDOW_WIDTH_AUTH, WINDOW_HEIGHT_AUTH) authScreen.mainloop() # voterID, privateRSAKey and PIN are valid #====================================================== # start validating login # get the chosen IV in base64 chosen_IV_inbase64 = ssl_sock.read(buffer_length) # decode it from base64 chosen_IV = b64decode(chosen_IV_inbase64) # print 'got chosen_IV ', hexlify(chosen_IV) # voterID || PIN voterID_PIN = voterID + voterPIN # print 'voterID_PIN ', str(voterID_PIN) # calculate sha256 hash of voterID || PIN in base64 hash_of_voterID_PIN_inbase64 = RSAKeyHandling.sha256hash_base64(voterID_PIN) # print 'hash of voterID_PIN in base 64 ', hash_of_voterID_PIN_inbase64 # encrypt it using AES 256 # key = sharedAESKey # IV = chosen_IV encrypted_AES_hash = RSAKeyHandling.AES_encryptor(sharedAESkey, hash_of_voterID_PIN_inbase64, chosen_IV) # convert it into base64 encrypted_AES_hash_inbase64 = base64.b64encode(encrypted_AES_hash) # send it to the server ssl_sock.sendall(encrypted_AES_hash_inbase64) # print 'sent to server encrypted_AES_hash_inbase64 ', encrypted_AES_hash_inbase64 # wait for server to return user_exists or user_has_voted user_exists_base64 = ssl_sock.read(buffer_length) # decode it from base64 user_exists = base64.b64decode(user_exists_base64) # print hexlify(user_exists) # decrypt it from AES using sharedAESkey and chosenIV user_exists = RSAKeyHandling.AES_decryptor(sharedAESkey, user_exists, chosen_IV) # print user_exists if user_exists == 'LOL_NO_WAY': # ZZZ change to msgbox tkMessageBox.showerror(title = "Not Eligible User", message = "Sorry, User Not Eligible to Vote") #print 'Sorry, user not eligible to vote' ssl_sock.close() continue ## ZZZ restart GUI , how ? # if user is eligible to vote # load privatekey rsakey = RSA.load_key(privateRSAKey, RSAKeyHandling.empty_callback) try: # user_exists must contain the hash_normal encrypted with public key # decrypt it decrypted_hash = rsakey.private_decrypt(user_exists, RSA.pkcs1_padding) except: # decryption didn't work # ZZZ change to msgbox tkMessageBox.showerror(title = "Decyption Error", message = "Sorry, Wrong User Credentials") ssl_sock.close() continue ## ZZZ restart GUI , how ? if decrypted_hash != hash_of_voterID_PIN_inbase64: # ZZZ change to msgbox tkMessageBox.showerror(title = "Decryption Error", message = "Sorry, Wrong User Credentials") # print 'Sorry, wrong user credentials' ssl_sock.close() continue # sys.exit() # now the user is authenticated and we can go on # start voting #====================================================== #draw choice screen for president/congress/counsel/ polls = { "president" : (1, 3), "congress" : (1, 5), "counsel" : (2, 4) } votes = { "president" : None, "congress" : None, "counsel" : None } for poll in polls: window = Group(poll, polls[poll][0], polls[poll][1]) # def __init__(self, _vf, _ms, _mo, master=None): centerWindow(window, WINDOW_WIDTH_MAIN, WINDOW_HEIGHT_MAIN) window.mainloop() votes[poll] = tuple(userVote) # store user vote del userVote[:] # clear user vote # send the votes to server # print votes votes_string = json.dumps(votes) # convert votes to base64 votes_string_inbase64 = base64.b64encode(votes_string) # to load it later # votes_n = json.loads(vote_str) # begin to encrypt votes encrypted_votes_string = RSAKeyHandling.AES_encryptor(sharedAESkey, votes_string_inbase64, chosen_IV) # convert it to base64 encrypted_votes_string_inbase64 = base64.b64encode(encrypted_votes_string) # send it to the server ssl_sock.sendall(encrypted_votes_string_inbase64) # wait for the thank you note encrypted_thankyou_inbase64 = ssl_sock.read(buffer_length) # decode it from base64 encrypted_thankyou = base64.b64decode(encrypted_thankyou_inbase64) # decrypt it using AES decrypted_thankyou = RSAKeyHandling.AES_decryptor(sharedAESkey, encrypted_thankyou, chosen_IV) print decrypted_thankyou # draw END SCREEN endScreen = EndScreen() centerWindow(endScreen, WINDOW_WIDTH_ES, WINDOW_HEIGHT_MS) endScreen.mainloop() # note that closing the SSLSocket will also close the underlying socket ssl_sock.close()
def init(): Rand.rand_seed(os.urandom(NUM_RANDOM_BITS / 8))
emailOriginalMessageID = lineFeedType.join( filter(lambda x: x.lower().startswith("message-id:"), parsedHeader)) # Generate new body, which will be encrypted. emailUUID = str(uuid.uuid1()) emailBoundaryString = '==_Part_' + emailUUID emailNewBody = 'Content-Type: multipart/mixed; boundary="' + emailBoundaryString + '"' + lineFeedType emailNewBody += lineFeedType emailNewBody += '--' + emailBoundaryString + lineFeedType emailNewBody += emailContentHeaders + lineFeedType emailNewBody += lineFeedType emailNewBody += emailBody + lineFeedType emailNewBody += '--' + emailBoundaryString + '--' + lineFeedType # Seed the random number generator with 1024 random bytes (8192 bits). Rand.rand_seed(os.urandom(1024)) # An invalid key is an error, tell user via X-Crypt-Header. try: pubKeyIsInvalid = False cert = X509.load_cert(sys.argv[1]) x509Stack = X509.X509_Stack() x509Stack.push(cert) except: pubKeyIsInvalid = True if pubKeyIsInvalid: sys.stdout.write("X-Crypt: Encryption by <" + socket.gethostname() + "> failed due to bad key." + lineFeedType) sys.stdout.write(emailData) sys.exit(0)
options = [ Bcfg2.Options.BooleanOption( cf=("encryption", "lax_decryption"), help="Decryption failures should cause warnings, not errors"), Bcfg2.Options.Option( cf=("encryption", "algorithm"), default="aes_256_cbc", type=lambda v: v.lower().replace("-", "_"), help="The encryption algorithm to use"), Bcfg2.Options.Option( cf=("encryption", "*"), dest='passphrases', default=dict(), help="Encryption passphrases")] Bcfg2.Options.get_parser().add_component(_OptionContainer) Rand.rand_seed(os.urandom(1024)) def _cipher_filter(cipher, instr): """ M2Crypto reads and writes file-like objects, so this uses StringIO to pass data through it """ inbuf = StringIO(instr) outbuf = StringIO() while 1: buf = inbuf.read() if not buf: break outbuf.write(cipher.update(buf)) outbuf.write(cipher.final()) rv = outbuf.getvalue() inbuf.close()
def _handle_encrypt_email(self, param): # Implement the handler here # use self.save_progress(...) to send progress messages back to the platform self.save_progress("In action handler for: {0}".format( self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) # Access action parameters passed in the 'param' dictionary # Required values can be accessed directly # message_body = bytes(str(param['message_body']).encode("utf-8")) try: message_body = bytes( self._handle_py_ver_compat_for_input_str( param['message_body'])) except: return action_result.set_status( phantom.APP_ERROR, "Please verify the value of 'message_body' action parameter") self.save_progress(SMIME_ENCRYPT_PROGRESS_MSG) try: # Create a temporary buffer. tmp = BIO.MemoryBuffer(message_body) Rand.rand_seed(os.urandom(1024)) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt the signed message to. x509 = X509.load_cert_string(self._keys['public']) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the temporary buffer. p7 = s.encrypt(tmp) except Exception as e: error_msg = self._get_error_message_from_exception(e) self.save_progress(SMIME_ENCRYPT_ERR_MSG.format(err=error_msg)) return action_result.set_status( phantom.APP_ERROR, SMIME_ENCRYPT_ERR_MSG.format(err=error_msg)) # Output p7 in mail-friendly format. try: out = BIO.MemoryBuffer() s.write(out, p7) except Exception as e: err = self._get_error_message_from_exception(e) return action_result.set_status( phantom.APP_ERROR, "Error occurred while writing the message in mail-friendly format. {}" .format(err)) self.save_progress(SMIME_ENCRYPT_OK_MSG) # Add the response into the data section try: action_result.add_data({'SMIME': {'message': out.read()}}) except Exception as e: err = self._get_error_message_from_exception(e) return action_result.set_status( phantom.APP_ERROR, "Error occurred while adding data to the 'action_result'. {}". format(err)) # Return success, no need to set the message, only the status # BaseConnector will create a textual message based off of the summary dictionary return action_result.set_status(phantom.APP_SUCCESS, SMIME_ENCRYPT_OK_MSG)