def threadSMIME(): # Seed the PRNG. Rand.load_file('randpool.dat', -1) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt to. x509 = X509.load_cert('recipient.pem') 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 buffer. p7 = s.encrypt(buf) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() out.write('From: [email protected]\n') out.write('To: [email protected]\n') out.write('Subject: M2Crypto S/MIME testing\n') s.write(out, p7) print out.read() # Save the PRNG's state. Rand.save_file('randpool.dat')
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 test_file_name(self): if "RANDFILE" in os.environ: self.assertEqual(Rand.rand_file_name(), os.environ["RANDFILE"]) else: self.assertEqual(Rand.rand_file_name(), os.path.join(os.environ["HOME"], ".rnd"))
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 test_pseudo_bytes(self): with self.assertRaises(MemoryError): Rand.rand_pseudo_bytes(-1) self.assertEqual(Rand.rand_pseudo_bytes(0), ('', 1)) a, b = Rand.rand_pseudo_bytes(1) self.assertEqual(len(a), 1) self.assertEqual(b, 1)
def main(keylen, hashalg): global rsa, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen) pubkeyfilename = 'rsa%dpubkey.pem' % (keylen) if makenewkey: print ' making and saving a new key' rsa = RSA.gen_key(keylen, exponent) rsa.save_key(pvtkeyfilename, None ) # no pswd callback rsa.save_pub_key(pubkeyfilename) else: print ' loading an existing key' rsa = RSA.load_key(pvtkeyfilename) print ' rsa key length:', len(rsa) if not rsa.check_key(): raise 'key is not initialised' # since we are testing signing and verification, let's not # be fussy about the digest. Just make one. md = EVP.MessageDigest(hashalg) md.update('can you spell subliminal channel?') dgst = md.digest() print ' hash algorithm: %s' % hashalg if showdigest: print ' %s digest: \n%s' % (hashalg, base64.encodestring(dgst)) test(rsa, dgst) # test_asn1(rsa, dgst) test_speed(rsa, dgst) Rand.save_file('randpool.dat')
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 encrypt(input_bio, cert, keyring_source, cypher): """ Encrypts the input data with the public key in the certificate from keyring source with selected cypher. @type input_bio: M2Crypto.BIO @param input_bio: input data to encrypt. @type cert: filepath or M2Crypto.BIO or M2Crypto.X509.X509 @param cert: the recipient certificate reference from filepath, could be from file, from memory or from pkcs11 smartcard, based on keyring_soruce input parameter. @type keyring_source: str @keyword keyring_source: the type of the source for input certificate, used to recall the appropriate method for encrypter settings. Ammitted values are: file, memory, pkcs11. @type cypher: str @keyword cypher: the cypher to use for encryption of the data, run "openssl enc -help" for supported cyphers, you have to choose a public key cypher from availables. @rtype: M2Crypto.SMIME.PKCS7 @return: the PKCS#7 encrypted data in PEM format. """ encrypter = SMIME.SMIME() x509 = set_certificate(cert, keyring_source) sk = X509.X509_Stack() sk.push(x509) encrypter.set_x509_stack(sk) encrypter.set_cipher(SMIME.Cipher(cypher)) Rand.load_file('randpool.dat', -1) try: p7 = encrypter.encrypt(input_bio) except SMIME.SMIME_Error, e: logging.error('smime error: ' + str(e)) raise
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 test_load_save(self): try: os.remove('tests/randpool.dat') except OSError: pass self.assertIn(Rand.load_file('tests/randpool.dat', -1), [0, -1]) self.assertEqual(Rand.save_file('tests/randpool.dat'), 1024) self.assertEqual(Rand.load_file('tests/randpool.dat', -1), 1024)
def test_load_save(self): try: os.remove("test/randpool.dat") except OSError: pass assert Rand.load_file("test/randpool.dat", -1) == 0 assert Rand.save_file("test/randpool.dat") == 1024 assert Rand.load_file("test/randpool.dat", -1) == 1024
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 encrypt(self, plaintext): """Encrypts plaintext, returns (salt, iv, ciphertext) tuple""" salt = Rand.rand_bytes(self._SALT_LEN) key = self._make_key(salt) iv = Rand.rand_bytes(self._IV_LEN) encryptor = self._make_encryptor(key, iv) ciphertext = encryptor.update(plaintext) ciphertext += encryptor.final() return salt, iv, ciphertext
def test_pseudo_bytes(self): with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) with self.assertRaises(MemoryError): Rand.rand_pseudo_bytes(-1) self.assertEqual(Rand.rand_pseudo_bytes(0), (b'', 1)) a, b = Rand.rand_pseudo_bytes(1) self.assertEqual(len(a), 1) self.assertEqual(b, 1)
def get_ssl_context(): from M2Crypto import Rand Rand.load_file('randpool.dat', -1) ctx = init_context('sslv23', 'server.pem', 'ca.pem', SSL.verify_none) #SSL.verify_peer | SSL.verify_fail_if_no_peer_cert) ctx.set_tmp_dh('dh1024.pem') Rand.save_file('randpool.dat') return ctx
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 shutdown(profileDir): """ Shut down the cryptographic services. You must call startup() before doing cryptographic operations again. @param profileDir: The profile directory. A snapshot of current entropy state will be saved into a file in this directory. It is not a fatal error if the file cannot be created. """ Rand.save_file(_randpoolPath(profileDir)) m2threading.cleanup()
def startup(profileDir): """ Initialize the cryptographic services before doing any other cryptographic operations. @param profileDir: The profile directory. Additional entropy will be loaded from a file in this directory. It is not a fatal error if the file does not exist. """ m2threading.init() Rand.load_file(_randpoolPath(profileDir), -1)
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 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 __init__(self, handler, host='localhost', port=8000): threading.init() Rand.load_file('../randpool.dat', -1) ctx=echod_lib.init_context('sslv3','server.pem', 'ca.pem', SSL.verify_peer) ctx.set_tmp_dh('dh1024.pem') config = Config() server = TCPServer.__connection(self, host, port) while 1: server.OpenConnection() server.HandleConnection(handler,config.config,ctx) server.CloseConnection() Rand.save_file('../randpool.dat') threading.cleanup()
def start(self, handler, ssl, host, port,config): if ssl: Rand.load_file('ssl/randpool.dat', -1) ctx=echod_lib.init_context('sslv3','ssl/server.pem', 'ssl/ca.pem', SSL.verify_none) ctx.set_tmp_dh('ssl/dh1024.pem') if port==8000: port += 1 else: ctx = None server = self.__connection(host, port) while 1: server.OpenConnection() server.HandleConnection(handler,config.config,ctx) server.CloseConnection()
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 pubkey2swarmid(livedict): if DEBUG: print >> sys.stderr, 'pubkey2swarmid:', livedict.keys() if livedict['authmethod'] == 'None': return Rand.rand_bytes(20) else: return sha(livedict['pubkey']).digest()
def send_data(data): if c.encipher: data = struct.pack('!I', len(data)) + data if len(data)%16 > 0: data += Rand.rand_bytes(16 - (len(data)%16)) data = c.encipher.update(data)+c.encipher.final() send_xmpp_message(get_client_jid(), c.remote_jid, 'DATA %s %s' % (c.id, encode(data)))
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 encode(self, data): d = { 'salt': base64.b64encode(Rand.rand_bytes(8)), 'digest': 'sha1', 'validFrom': self._formatDate(datetime.datetime.utcnow()), 'validTo': self._formatDate( datetime.datetime.utcnow() + datetime.timedelta( seconds=self._lifetime ) ), 'data': data } self._pkey.reset_context(md=d['digest']) self._pkey.sign_init() fields = [] for k, v in d.items(): fields.append(k) self._pkey.sign_update(v) d['signedFields'] = ','.join(fields) d['signature'] = base64.b64encode(self._pkey.sign_final()) d['certificate'] = self._x509.as_pem() return base64.b64encode(json.dumps(d))
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 ssl_encrypt(plaintext, passwd, algorithm=None, salt=None): """ Encrypt data in a format that is openssl compatible. :param plaintext: The plaintext data to encrypt :type plaintext: string :param passwd: The password to use to encrypt the data :type passwd: string :param algorithm: The cipher algorithm to use :type algorithm: string :param salt: The salt to use. If none is provided, one will be randomly generated. :type salt: bytes :returns: string - The base64-encoded, salted, encrypted string. The string includes a trailing newline to make it fully compatible with openssl command-line tools. """ if salt is None: salt = Rand.rand_bytes(8) # pylint: disable=E1101,E1121 hashes = [md5(passwd + salt).digest()] for i in range(1, 3): hashes.append(md5(hashes[i - 1] + passwd + salt).digest()) # pylint: enable=E1101,E1121 key = hashes[0] + hashes[1] iv = hashes[2] crypted = str_encrypt(plaintext, key=key, salt=salt, iv=iv, algorithm=algorithm) return b64encode("Salted__" + salt + crypted) + "\n"
def generate_response1(randomB,peeridB,keypairA): randomA = Rand.rand_bytes(num_random_bits/8) response1 = {} response1['certA'] = str(keypairA.pub().get_der()) response1['rA'] = randomA response1['B'] = peeridB response1['SA'] = sign_response(randomA,randomB,peeridB,keypairA) return [randomA,bencode(response1)]
def rand_bytes(n_bytes): return Rand.rand_bytes(n_bytes)
def test_bytes(self): with self.assertRaises(MemoryError): Rand.rand_bytes(-1) self.assertEqual(Rand.rand_bytes(0), b'') self.assertEqual(len(Rand.rand_bytes(1)), 1)
def __init__(self): # type: () -> None self._key = Rand.rand_bytes(self._keylen)
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)
def test_pseudo_bytes(self): self.assertRaises(MemoryError, Rand.rand_pseudo_bytes, -1) assert Rand.rand_pseudo_bytes(0) == ('', 1) a, b = Rand.rand_pseudo_bytes(1) assert len(a) == 1 assert b == 1
def init(): Rand.rand_seed(os.urandom(num_random_bits / 8))
def generate_challenge(): randomB = Rand.rand_bytes(num_random_bits / 8) return [randomB, bencode(randomB)]
def keygen(length=40): return binascii.b2a_base64(Rand.rand_bytes(length))
def test_bytes(self): self.assertRaises(MemoryError, Rand.rand_bytes, -1) assert Rand.rand_bytes(0) == '' assert len(Rand.rand_bytes(1)) == 1
PUB_KEY_DER_PREFIX = "3059301306072a8648ce3d020106082a8648ce3d030107034200" \ .decode('hex') def pub_key_from_der(der): return EC.pub_key_from_der(PUB_KEY_DER_PREFIX + der) def websafe_decode(data): if isinstance(data, unicode): data = data.encode('utf-8') data += '=' * (-len(data) % 4) return urlsafe_b64decode(data) def websafe_encode(data): return urlsafe_b64encode(data).replace('=', '') def sha_256(data): h = sha256() h.update(data) return h.digest() Rand.rand_seed(os.urandom(1024)) def rand_bytes(n_bytes): return Rand.rand_bytes(n_bytes)
def setUp(self): """ override TestAsServer """ TestAsServer.setUp(self) Rand.load_file('randpool.dat', -1)
def test_verify_fail2(self): dsa = DSA.load_key(self.privkey) r, s = dsa.sign(self.data) dsa2 = DSA.load_params(self.param) assert not dsa2.check_key() self.assertRaises(AssertionError, dsa2.verify, self.data, r, s) def test_genparam_setparam_genkey(self): dsa = DSA.gen_params(1024, self.callback) assert len(dsa) == 1024 p = dsa.p q = dsa.q g = dsa.g dsa2 = DSA.set_params(p, q, g) assert not dsa2.check_key() dsa2.gen_key() assert dsa2.check_key() r, s = dsa2.sign(self.data) assert dsa2.verify(self.data, r, s) def suite(): return unittest.makeSuite(DSATestCase) if __name__ == '__main__': Rand.load_file('randpool.dat', -1) unittest.TextTestRunner().run(suite()) Rand.save_file('randpool.dat')