{"id":30700142,"url":"https://github.com/operasoftware/tlslite","last_synced_at":"2025-09-02T11:44:22.443Z","repository":{"id":5999560,"uuid":"7222428","full_name":"operasoftware/tlslite","owner":"operasoftware","description":"Modified version of Public Domain TLSLite library. Extended and instrumented to handle TLS 1.2, extensions, and performing various tests of TLS Server compliance","archived":false,"fork":false,"pushed_at":"2012-12-18T12:01:45.000Z","size":557,"stargazers_count":8,"open_issues_count":0,"forks_count":4,"subscribers_count":39,"default_branch":"master","last_synced_at":"2024-04-14T06:01:55.328Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/operasoftware.png","metadata":{"files":{"readme":"readme.txt","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-12-18T11:42:11.000Z","updated_at":"2021-11-15T11:23:46.000Z","dependencies_parsed_at":"2022-08-30T05:05:12.548Z","dependency_job_id":null,"html_url":"https://github.com/operasoftware/tlslite","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/operasoftware/tlslite","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/operasoftware%2Ftlslite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/operasoftware%2Ftlslite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/operasoftware%2Ftlslite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/operasoftware%2Ftlslite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/operasoftware","download_url":"https://codeload.github.com/operasoftware/tlslite/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/operasoftware%2Ftlslite/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273279960,"owners_count":25077318,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-02T02:00:09.530Z","response_time":77,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-02T11:43:39.584Z","updated_at":"2025-09-02T11:44:22.431Z","avatar_url":"https://github.com/operasoftware.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\ntlslite version 0.3.8                                      February 21, 2005\nTrevor Perrin \u003ctrevp at trevp.net\u003e\nhttp://trevp.net/tlslite/\n============================================================================\n\n\nTable of Contents\n==================\n1  Introduction\n2  License/Acknowledgements\n3  Installation\n4  Getting Started with the Command-Line Tools\n5  Getting Started with the Library\n6  Using TLS Lite with httplib\n7  Using TLS Lite with xmlrpclib\n8  Using TLS Lite with poplib or imaplib\n9  Using TLS Lite with smtplib\n10 Using TLS Lite with SocketServer\n11 Using TLS Lite with asyncore\n12 Using TLS Lite with Twisted\n13 SECURITY CONSIDERATIONS\n14 History\n15 References\n\n\n1 Introduction\n===============\nTLS Lite is a free python library that implements SSL v3, TLS v1, and \nTLS v1.1 [0]. TLS Lite supports non-traditional authentication methods \nsuch as SRP [1], shared keys [2], and cryptoIDs [3], in addition to X.509\ncertificates.  TLS Lite is pure python, however it can access OpenSSL [4], \ncryptlib [5], pycrypto [9], and GMPY [10] for faster crypto operations.  TLS \nLite integrates with httplib, xmlrpclib, poplib, imaplib, smtplib,\nSocketServer, asyncore, and Twisted.\n\nAPI documentation is available in the 'docs' directory.\n\nIf you have questions or feedback, feel free to contact me.\n\n\n2 Licenses/Acknowledgements\n============================\nAll code here is public domain.\n\nThanks to Bram Cohen for his public domain Rijndael implementation.\n\nThanks to Edward Loper for Epydoc, which generated the API docs.\n\nUpdated by Yngve N. Pettersen, Opera Software ASA, 2009-2012\n\n\n3 Installation\n===============\nRequirements:\n  Python 2.2 or greater is required.\n\nOptions:\n  - If you have cryptoIDlib [8], you can use cryptoID certificate chains for\n  authentication.  CryptoIDlib is the sister library to TLS Lite; it was\n  written by the same author, and has a similar interface.\n\n  - If you have the M2Crypto [6] interface to OpenSSL, this will be used for\n  fast RSA operations and fast ciphers.\n\n  - If you have the cryptlib_py [7] interface to cryptlib, this will be used\n  for random number generation and fast ciphers.  If TLS Lite can't find an\n  OS-level random-number generator (i.e. /dev/urandom on UNIX or CryptoAPI on\n  Windows), then you must MUST install cryptlib.\n\n  - If you have pycrypto [9], this will be used for fast ciphers and fast RSA\n  operations.\n\n  - If you have the GMPY [10] interface to GMP, this will be used for fast RSA\n  and SRP operations.\n\n  - These modules don't need to be present at installation - you can install\n  them any time.\n\nOn Windows:\n  Run the installer in the 'installers' directory.\n  *OR*\n  Run 'setup.py install' (this only works if your system has a compiler\n  available).\n\nAnywhere else:\n  - Run 'python setup.py install'\n\nTest the Installation:\n  - The 'tls.py' script should have been copied onto your path.  If not,\n    you may have to copy it there manually.\n  - From the distribution's ./test subdirectory, run:\n      tls.py servertest localhost:4443 .\n  - While the test server is waiting, run:\n      tls.py clienttest localhost:4443 .\n\n  If both say \"Test succeeded\" at the end, you're ready to go.\n\n  (WARNING: Be careful running these (or any) scripts from the distribution's\n  root directory.  Depending on your path, the scripts may load the local copy\n  of the library instead of the installed version, with unpredictable\n  results).\n\n\n4 Getting Started with the Command-Line Tools\n==============================================\ntlslite comes with two command-line scripts: 'tlsdb.py' and 'tls.py'.  They\ncan be run with no arguments to see a list of commands.\n\n'tlsdb.py' lets you manage shared key or verifier databases.  These databases\nstore usernames associated with either shared keys, or SRP password verifiers.\nThese databases are used by a TLS server when authenticating clients with\nshared keys or SRP.\n\n'tls.py' lets you run test clients and servers.  It can be used for testing\nother TLS implementations, or as example code for using tlslite.  To run an\nSRP server, try something like:\n\n  tlsdb.py createsrp verifierDB\n  tlsdb.py add verifierDB alice abra123cadabra 1024\n  tlsdb.py add verifierDB bob swordfish 2048\n\n  tls.py serversrp localhost:443 verifierDB\n\nThen you can try connecting to the server with:\n\n  tls.py clientsrp localhost:443 alice abra123cadabra\n\n\n5 Getting Started with the Library\n===================================\nUsing the library is simple.  Whether you're writing a client or server, there\nare six steps:\n1) Create a socket and connect it to the other party.\n2) Construct a TLSConnection instance with the socket.\n3) Call a handshake function on TLSConnection to perform the TLS handshake.\n4) Check the results to make sure you're talking to the right party.\n5) Use the TLSConnection to exchange data.\n6) Call close() on the TLSConnection when you're done.\n\nTLS Lite also integrates with httplib, xmlrpclib, poplib, imaplib, smtplib, \nSocketServer, asyncore, and Twisted.  When used with these, some of the steps \nare performed for you.  See the sections following this one for details.\n\n5 Step 1 - create a socket\n---------------------------\nBelow demonstrates a socket connection to Amazon's secure site.  It's a good\nidea to set the timeout value, so if the other side fails to respond you won't\nend up waiting forever.\n\n  from socket import *\n  sock = socket(AF_INET, SOCK_STREAM)\n  sock.connect( (\"www.amazon.com\", 443) )\n  sock.settimeout(10)  #Only on python 2.3 or greater\n\n5 Step 2 - construct a TLSConnection\n-------------------------------------\n  from tlslite.api import *\n  connection = TLSConnection(sock)\n\n5 Step 3 - call a handshake function (client)\n----------------------------------------------\nIf you're a client, there's several different handshake functions you can\ncall, depending on how you want to authenticate:\n\n  connection.handshakeClientCert()\n  connection.handshakeClientCert(certChain, privateKey)\n  connection.handshakeClientSRP(\"alice\", \"abra123cadabra\")\n  connection.handshakeClientSharedKey(\"alice\", \"PaVBVZkYqAjCQCu6UBL2xgsnZhw\")\n  connection.handshakeClientUnknown(srpCallback, certCallback)\n\nThe ClientCert function without arguments is used when connecting to a site\nlike Amazon, which doesn't require client authentication.  The server will\nauthenticate with a certificate chain.\n\nThe ClientCert function can also be used to do client authentication with an\nX.509 or cryptoID certificate chain.  To use cryptoID chains, you'll need the\ncryptoIDlib library [8].  To use X.509 chains, you'll need some way of\ncreating these, such as OpenSSL (see http://www.openssl.org/docs/HOWTO/ for\ndetails).\n\nBelow are examples of loading cryptoID and X.509 certificate chains:\n\n  #Load cryptoID certChain and privateKey.  Requires cryptoIDlib.\n  from cryptoIDlib.CertChain import CertChain\n  s = open(\"./test/clientCryptoIDChain.xml\").read()\n  certChain = CertChain()\n  certChain.parse(s)\n  s = open(\"./test/clientCryptoIDKey.xml\").read()\n  privateKey = parseXMLKey(s, private=True)\n\n  #Load X.509 certChain and privateKey.\n  s = open(\"./test/clientX509Cert.pem\").read()\n  x509 = X509()\n  x509.parse(s)\n  certChain = X509CertChain([x509])\n  s = open(\"./test/clientX509Key.pem\").read()\n  privateKey = parsePEMKey(s, private=True)\n\nThe SRP and SharedKey functions both do mutual authentication with a username\nand password.  The difference is this: SRP is slow but safer when using low-\nentropy passwords, since the SRP protocol is not vulnerable to offline\ndictionary attacks.  Using shared keys is faster, but it's only safe when\nused with high-entropy secrets.  In general, you should prefer SRP for human-\nmemorable passwords, and use shared keys only when your performance needs\noutweigh the inconvenience of handling large random strings.\n\n[WARNING: shared keys and SRP are internet-drafts; these protocols may change,\nwhich means future versions of tlslite may not be compatible with this one.\nThis is less likely with SRP, more likely with shared-keys.]\n\nThe Unknown function is used when you're not sure if the server requires\nclient authentication.\t If the server requests SRP or certificate-based\nauthentication, the appropriate callback will be triggered, and you should\nreturn a tuple containing either a (username, password) or (certChain,\nprivateKey), as appropriate.  Alternatively, you can return None, which will\ncancel the handshake from an SRP callback, or cause it to continue without\nclient authentication (if the server is willing) from a certificate callback.\n\nIf you want more control over the handshake, you can pass in a\nHandshakeSettings instance.  For example, if you're performing SRP, but you\nonly want to use SRP parameters of at least 2048 bits, and you only want to use\nthe AES-256 cipher, and you only want to allow TLS (version 3.1), not SSL\n(version 3.0), you can do:\n\n  settings = HandshakeSettings()\n  settings.minKeySize = 2048\n  settings.cipherNames = [\"aes256\"]\n  settings.minVersion = (3,1)\n  connection.handshakeClientSRP(\"alice\", \"abra123cadabra\", settings=settings)\n\nFinally, every TLSConnection has a session object.  You can try to resume a\nprevious session by passing in the session object from the old session.  If\nthe server remembers this old session and supports resumption, the handshake\nwill finish more quickly.  Otherwise, the full handshake will be done.  For\nexample:\n\n  connection.handshakeClientSRP(\"alice\", \"abra123cadabra\")\n  .\n  .\n  oldSession = connection.session\n  connection2.handshakeClientSRP(\"alice\", \"abra123cadabra\", session=\n  oldSession)\n\n5 Step 3 - call a handshake function (server)\n----------------------------------------------\nIf you're a server, there's only one handshake function, but you can pass it\nseveral different parameters, depending on which types of authentication\nyou're willing to perform.\n\nTo perform SRP authentication, you have to pass in a database of password\nverifiers.  The VerifierDB class manages an in-memory or on-disk verifier\ndatabase.\n\n  #On-disk database (use no-arg constructor if you want an in-memory DB)\n  verifierDB = VerifierDB(\"./test/verifierDB\")\n\n  #Open the pre-existing database (can also 'create()' a new one)\n  verifierDB.open()\n\n  #Add to the database\n  verifier = VerifierDB.makeVerifier(\"alice\", \"abra123cadabra\", 2048)\n  verifierDB[\"alice\"] = verifier\n\n  #Perform a handshake using the database\n  connection.handshakeServer(verifierDB=verifierDB)\n\nTo perform shared key authentication, you have to pass in a database of shared\nkeys.  The SharedKeyDB class manages an in-memory or on-disk shared key\ndatabase.\n\n  sharedKeyDB = SharedKeyDB(\"./test/sharedkeyDB\")\n  sharedKeyDB.open()\n  sharedKeyDB[\"alice\"] = \"PaVBVZkYqAjCQCu6UBL2xgsnZhw\"\n  connection.handshakeServer(sharedKeyDB=sharedKeyDB)\n\nTo perform authentication with a certificate and private key, the server must\nload these as described in the previous section, then pass them in.  If the\nserver sets the reqCert boolean to True, a certificate chain will be requested\nfrom the client.\n\n  connection.handshakeServer(certChain=certChain, privateKey=privateKey,\n                             reqCert=True)\n\nYou can pass in any combination of a verifier database, a shared key database,\nand a certificate chain/private key.  The client will use one of them to\nauthenticate.  In the case of SRP and a certificate chain/private key, they\nboth may be used.\n\nYou can also pass in a HandshakeSettings object, as described in the last\nsection, for finer control over handshaking details.  Finally, the server can\nmaintain a SessionCache, which will allow clients to use session resumption:\n\n  sessionCache = SessionCache()\n  connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache)\n\nIt should be noted that the session cache, and the verifier and shared key\ndatabases, are all thread-safe.\n\n5 Step 4 - check the results\n-----------------------------\nIf the handshake completes without raising an exception, authentication\nresults will be stored in the connection's session object.  The following\nvariables will be populated if applicable, or else set to None:\n\n  connection.session.srpUsername       #string\n  connection.session.sharedKeyUsername #string\n  connection.session.clientCertChain   #X509CertChain or\n                                       #cryptoIDlib.CertChain.CertChain\n  connection.session.serverCertChain   #X509CertChain or\n                                       #cryptoIDlib.CertChain.CertChain\n\nBoth types of certificate chain object support the getFingerprint() function,\nbut with a difference.  X.509 objects return the end-entity fingerprint, and\nignore the other certificates.  CryptoID fingerprints (aka \"cryptoIDs\") are\nbased on the root cryptoID certificate, so you have to call validate() on the\nCertChain to be sure you're really talking to the cryptoID.\n\nX.509 certificate chain objects may also be validated against a list of\ntrusted root certificates.  See the API documentation for details.\n\nTo save yourself the trouble of inspecting fingerprints after the handshake,\nyou can pass a Checker object into the handshake function.  The checker will be\ncalled if the handshake completes successfully.  If the other party's\ncertificate chain isn't approved by the checker, a subclass of\nTLSAuthenticationError will be raised.  For example, to perform a handshake\nwith a server based on its X.509 fingerprint, do:\n\n  try:\n    checker = Checker(\\\n              x509Fingerprint='e049ff930af76d43ff4c658b268786f4df1296f2')\n    connection.handshakeClientCert(checker=checker)\n  except TLSAuthenticationError:\n    print \"Authentication failure\"\n\nIf the handshake fails for any reason, an exception will be raised.  If the\nsocket timed out or was unexpectedly closed, a socket.error or\nTLSAbruptCloseError will be raised.  Otherwise, either a TLSLocalAlert or\nTLSRemoteAlert will be raised, depending on whether the local or remote\nimplementation signalled the error.  The exception object has a 'description'\nmember which identifies the error based on the codes in RFC 2246.  A\nTLSLocalAlert also has a 'message' string that may have more details.\n\nExample of handling a remote alert:\n\n  try:\n      [...]\n  except TLSRemoteAlert, alert:\n      if alert.description == AlertDescription.unknown_srp_username:\n          print \"Unknown user.\"\n  [...]\n\nFiguring out what went wrong based on the alert may require some\ninterpretation, particularly with remote alerts where you don't have an error\nstring, and where the remote implementation may not be signalling alerts\nproperly.  Many alerts signal an implementation error, and so should rarely be\nseen in normal operation (unexpected_message, decode_error, illegal_parameter,\ninternal_error, etc.).\n\nOthers alerts are more likely to occur.  Below are some common alerts and\ntheir probable causes, and whether they are signalled by the client or server.\n\nClient bad_record_mac:\n - bad shared key password\n\nClient handshake failure:\n - SRP parameters are not recognized by client\n\nClient user_canceled:\n - The client might have returned None from an SRP callback.\n\nClient insufficient_security:\n - SRP parameters are too small\n\nClient protocol_version:\n - Client doesn't support the server's protocol version\n\nServer protocol_version:\n - Server doesn't support the client's protocol version\n\nServer bad_record_mac:\n - bad SRP username or password\n\nServer unknown_srp_username\n - bad SRP username (bad_record_mac could be used for the same thing)\n\nServer handshake_failure:\n - bad shared key username\n - no matching cipher suites\n\n5 Step 5 - exchange data\n-------------------------\nNow that you have a connection, you can call read() and write() as if it were\na socket.SSL object.  You can also call send(), sendall(), recv(), and\nmakefile() as if it were a socket.  These calls may raise TLSLocalAlert,\nTLSRemoteAlert, socket.error, or TLSAbruptCloseError, just like the handshake\nfunctions.\n\nOnce the TLS connection is closed by the other side, calls to read() or recv()\nwill return an empty string.  If the socket is closed by the other side\nwithout first closing the TLS connection, calls to read() or recv() will return\na TLSAbruptCloseError, and calls to write() or send() will return a\nsocket.error.\n\n5 Step 6 - close the connection\n--------------------------------\nWhen you're finished sending data, you should call close() to close the\nconnection down.  When the connection is closed properly, the socket stays\nopen and can be used for exchanging non-secure data, the session object can be\nused for session resumption, and the connection object can be re-used by\ncalling another handshake function.\n\nIf an exception is raised, the connection will be automatically closed; you\ndon't need to call close().  Furthermore, you will probably not be able to re-\nuse the socket, the connection object, or the session object, and you\nshouldn't even try.\n\nBy default, calling close() will leave the socket open.  If you set the\nconnection's closeSocket flag to True, the connection will take ownership of\nthe socket, and close it when the connection is closed.\n\n\n6 Using TLS Lite with httplib\n==============================\nTLS Lite comes with an HTTPTLSConnection class that extends httplib to work\nover SSL/TLS connections.  Depending on how you construct it, it will do\ndifferent types of authentication.\n\n  #No authentication whatsoever\n  h = HTTPTLSConnection(\"www.amazon.com\", 443)\n  h.request(\"GET\", \"\")\n  r = h.getresponse()\n  [...]\n\n  #Authenticate server based on its X.509 fingerprint\n  h = HTTPTLSConnection(\"www.amazon.com\", 443,\n          x509Fingerprint=\"e049ff930af76d43ff4c658b268786f4df1296f2\")\n  [...]\n\n  #Authenticate server based on its X.509 chain (requires cryptlib_py [7])\n  h = HTTPTLSConnection(\"www.amazon.com\", 443,\n          x509TrustList=[verisignCert],\n          x509CommonName=\"www.amazon.com\")\n  [...]\n\n  #Authenticate server based on its cryptoID\n  h = HTTPTLSConnection(\"localhost\", 443,\n          cryptoID=\"dmqb6.fq345.cxk6g.5fha3\")\n  [...]\n\n  #Mutually authenticate with SRP\n  h = HTTPTLSConnection(\"localhost\", 443,\n          username=\"alice\", password=\"abra123cadabra\")\n  [...]\n\n  #Mutually authenticate with a shared key\n  h = HTTPTLSConnection(\"localhost\", 443,\n          username=\"alice\", sharedKey=\"PaVBVZkYqAjCQCu6UBL2xgsnZhw\")\n  [...]\n\n  #Mutually authenticate with SRP, *AND* authenticate the server based\n  #on its cryptoID\n  h = HTTPTLSConnection(\"localhost\", 443,\n          username=\"alice\", password=\"abra123cadabra\",\n          cryptoID=\"dmqb6.fq345.cxk6g.5fha3\")\n  [...]\n\n\n7 Using TLS Lite with xmlrpclib\n================================\nTLS Lite comes with an XMLRPCTransport class that extends xmlrpclib to work\nover SSL/TLS connections.  This class accepts the same parameters as\nHTTPTLSConnection (see previous section), and behaves similarly.  Depending on\nhow you construct it, it will do different types of authentication.\n\n  from tlslite.api import XMLRPCTransport\n  from xmlrpclib import ServerProxy\n\n  #No authentication whatsoever\n  transport = XMLRPCTransport()\n  server = ServerProxy(\"https://localhost\", transport)\n  server.someFunc(2, 3)\n  [...]\n\n  #Authenticate server based on its X.509 fingerprint\n  transport = XMLRPCTransport(\\\n          x509Fingerprint=\"e049ff930af76d43ff4c658b268786f4df1296f2\")  \n  [...]\n\n\n8 Using TLS Lite with poplib or imaplib\n========================================\nTLS Lite comes with POP3_TLS and IMAP4_TLS classes that extend poplib and\nimaplib to work over SSL/TLS connections.  These classes can be constructed\nwith the same parameters as HTTPTLSConnection (see previous section), and \nbehave similarly.\n\n  #To connect to a POP3 server over SSL and display its fingerprint:\n  from tlslite.api import *\n  p = POP3_TLS(\"---------.net\")\n  print p.sock.session.serverCertChain.getFingerprint()\n  [...]\n\n  #To connect to an IMAP server once you know its fingerprint:\n  from tlslite.api import *\n  i = IMAP4_TLS(\"cyrus.andrew.cmu.edu\",\n          x509Fingerprint=\"00c14371227b3b677ddb9c4901e6f2aee18d3e45\")\n  [...]  \n  \n\n9 Using TLS Lite with smtplib\n==============================\nTLS Lite comes with an SMTP_TLS class that extends smtplib to work\nover SSL/TLS connections.  This class accepts the same parameters as\nHTTPTLSConnection (see previous section), and behaves similarly.  Depending \non how you call starttls(), it will do different types of authentication.\n\n  #To connect to an SMTP server once you know its fingerprint:\n  from tlslite.api import *\n  s = SMTP_TLS(\"----------.net\")\n  s.starttls(x509Fingerprint=\"7e39be84a2e3a7ad071752e3001d931bf82c32dc\")\n  [...]\n\n\n10 Using TLS Lite with SocketServer\n====================================\nYou can use TLS Lite to implement servers using Python's SocketServer\nframework.  TLS Lite comes with a TLSSocketServerMixIn class.  You can combine\nthis with a TCPServer such as HTTPServer.  To combine them, define a new class\nthat inherits from both of them (with the mix-in first). Then implement the\nhandshake() method, doing some sort of server handshake on the connection\nargument.  If the handshake method returns True, the RequestHandler will be\ntriggered.  Below is a complete example of a threaded HTTPS server.\n\n  from SocketServer import *\n  from BaseHTTPServer import *\n  from SimpleHTTPServer import *\n  from tlslite.api import *\n\n  s = open(\"./serverX509Cert.pem\").read()\n  x509 = X509()\n  x509.parse(s)\n  certChain = X509CertChain([x509])\n\n  s = open(\"./serverX509Key.pem\").read()\n  privateKey = parsePEMKey(s, private=True)\n\n  sessionCache = SessionCache()\n\n  class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer):\n      def handshake(self, tlsConnection):\n          try:\n              tlsConnection.handshakeServer(certChain=certChain,\n                                            privateKey=privateKey,\n                                            sessionCache=sessionCache)\n              tlsConnection.ignoreAbruptClose = True\n              return True\n          except TLSError, error:\n              print \"Handshake failure:\", str(error)\n              return False\n\n  httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler)\n  httpd.serve_forever()\n\n\n11 Using TLS Lite with asyncore\n================================\nTLS Lite can be used with subclasses of asyncore.dispatcher.  See the comments\nin TLSAsyncDispatcherMixIn.py for details.  This is still experimental, and\nmay not work with all asyncore.dispatcher subclasses.\n\nBelow is an example of combining Medusa's http_channel with\nTLSAsyncDispatcherMixIn:\n\n  class http_tls_channel(TLSAsyncDispatcherMixIn,\n                         http_server.http_channel):\n      ac_in_buffer_size = 16384\n\n      def __init__ (self, server, conn, addr):\n          http_server.http_channel.__init__(self, server, conn, addr)\n          TLSAsyncDispatcherMixIn.__init__(self, conn)\n          self.tlsConnection.ignoreAbruptClose = True\n          self.setServerHandshakeOp(certChain=certChain,\n                                    privateKey=privateKey)\n\n\n12 Using TLS Lite with Twisted\n===============================\nTLS Lite can be used with Twisted protocols.  Below is a complete example of\nusing TLS Lite with a Twisted echo server.\n\nThere are two server implementations below.  Echo is the original protocol,\nwhich is oblivious to TLS.  Echo1 subclasses Echo and negotiates TLS when the\nclient connects.  Echo2 subclasses Echo and negotiates TLS when the client\nsends \"STARTTLS\".\n\n  from twisted.internet.protocol import Protocol, Factory\n  from twisted.internet import reactor\n  from twisted.protocols.policies import WrappingFactory\n  from twisted.protocols.basic import LineReceiver\n  from twisted.python import log\n  from twisted.python.failure import Failure\n  import sys\n  from tlslite.api import *\n\n  s = open(\"./serverX509Cert.pem\").read()\n  x509 = X509()\n  x509.parse(s)\n  certChain = X509CertChain([x509])\n\n  s = open(\"./serverX509Key.pem\").read()\n  privateKey = parsePEMKey(s, private=True)\n\n  verifierDB = VerifierDB(\"verifierDB\")\n  verifierDB.open()\n\n  class Echo(LineReceiver):\n      def connectionMade(self):\n          self.transport.write(\"Welcome to the echo server!\\r\\n\")\n\n      def lineReceived(self, line):\n          self.transport.write(line + \"\\r\\n\")\n\n  class Echo1(Echo):\n      def connectionMade(self):\n          if not self.transport.tlsStarted:\n              self.transport.setServerHandshakeOp(certChain=certChain,\n                                                  privateKey=privateKey,\n                                                  verifierDB=verifierDB)\n          else:\n              Echo.connectionMade(self)\n\n      def connectionLost(self, reason):\n          pass #Handle any TLS exceptions here\n\n  class Echo2(Echo):\n      def lineReceived(self, data):\n          if data == \"STARTTLS\":\n              self.transport.setServerHandshakeOp(certChain=certChain,\n                                                  privateKey=privateKey,\n                                                  verifierDB=verifierDB)\n          else:\n              Echo.lineReceived(self, data)\n\n      def connectionLost(self, reason):\n          pass #Handle any TLS exceptions here\n\n  factory = Factory()\n  factory.protocol = Echo1\n  #factory.protocol = Echo2\n\n  wrappingFactory = WrappingFactory(factory)\n  wrappingFactory.protocol = TLSTwistedProtocolWrapper\n\n  log.startLogging(sys.stdout)\n  reactor.listenTCP(1079, wrappingFactory)\n  reactor.run()\n\n\n13 Security Considerations\n===========================\nTLS Lite is beta-quality code.  It hasn't received much security analysis.\nUse at your own risk.\n\n\n14 History\n===========\n0.3.8 - 2/21/2005\n - Added support for poplib, imaplib, and smtplib\n - Added python 2.4 windows installer\n - Fixed occassional timing problems with test suite\n0.3.7 - 10/05/2004\n - Added support for Python 2.2\n - Cleaned up compatibility code, and docs, a bit\n0.3.6 - 9/28/2004\n - Fixed script installation on UNIX\n - Give better error message on old Python versions\n0.3.5 - 9/16/2004\n - TLS 1.1 support\n - os.urandom() support\n - Fixed win32prng on some systems\n0.3.4 - 9/12/2004\n - Updated for TLS/SRP draft 8\n - Bugfix: was setting _versioncheck on SRP 1st hello, causing problems\n   with GnuTLS (which was offering TLS 1.1)\n - Removed _versioncheck checking, since it could cause interop problems\n - Minor bugfix: when cryptlib_py and and cryptoIDlib present, cryptlib\n   was complaining about being initialized twice\n0.3.3 - 6/10/2004\n - Updated for TLS/SRP draft 7\n - Updated test cryptoID cert chains for cryptoIDlib 0.3.1\n0.3.2 - 5/21/2004\n - fixed bug when handling multiple handshake messages per record (e.g. IIS)\n0.3.1 - 4/21/2004\n - added xmlrpclib integration\n - fixed hanging bug in Twisted integration\n - fixed win32prng to work on a wider range of win32 sytems\n - fixed import problem with cryptoIDlib\n - fixed port allocation problem when test scripts are run on some UNIXes\n - made tolerant of buggy IE sending wrong version in premaster secret\n0.3.0 - 3/20/2004\n - added API docs thanks to epydoc\n - added X.509 path validation via cryptlib\n - much cleaning/tweaking/re-factoring/minor fixes\n0.2.7 - 3/12/2004\n - changed Twisted error handling to use connectionLost()\n - added ignoreAbruptClose\n0.2.6 - 3/11/2004\n - added Twisted errorHandler\n - added TLSAbruptCloseError\n - added 'integration' subdirectory\n0.2.5 - 3/10/2004\n - improved asynchronous support a bit\n - added first-draft of Twisted support\n0.2.4 - 3/5/2004\n - cleaned up asyncore support\n - added proof-of-concept for Twisted\n0.2.3 - 3/4/2004\n - added pycrypto RSA support\n - added asyncore support\n0.2.2 - 3/1/2004\n - added GMPY support\n - added pycrypto support\n - added support for PEM-encoded private keys, in pure python\n0.2.1 - 2/23/2004\n - improved PRNG use (cryptlib, or /dev/random, or CryptoAPI)\n - added RSA blinding, to avoid timing attacks\n - don't install local copy of M2Crypto, too problematic\n0.2.0 - 2/19/2004\n - changed VerifierDB to take per-user parameters\n - renamed tls_lite -\u003e tlslite\n0.1.9 - 2/16/2004\n - added post-handshake 'Checker'\n - made compatible with Python 2.2\n - made more forgiving of abrupt closure, since everyone does it:\n   if the socket is closed while sending/recv'ing close_notify,\n   just ignore it.\n0.1.8 - 2/12/2004\n - TLSConnections now emulate sockets, including makefile()\n - HTTPTLSConnection and TLSMixIn simplified as a result\n0.1.7 - 2/11/2004\n - fixed httplib.HTTPTLSConnection with multiple requests\n - fixed SocketServer to handle close_notify\n - changed handshakeClientNoAuth() to ignore CertificateRequests\n - changed handshakeClient() to ignore non-resumable session arguments\n0.1.6 - 2/10/2004\n - fixed httplib support\n0.1.5 - 2/09/2004\n - added support for httplib and SocketServer\n - added support for SSLv3\n - added support for 3DES\n - cleaned up read()/write() behavior\n - improved HMAC speed\n0.1.4 - 2/06/2004\n - fixed dumb bug in tls.py\n0.1.3 - 2/05/2004\n - change read() to only return requested number of bytes\n - added support for shared-key and in-memory databases\n - added support for PEM-encoded X.509 certificates\n - added support for SSLv2 ClientHello\n - fixed shutdown/re-handshaking behavior\n - cleaned up handling of missing_srp_username\n - renamed readString()/writeString() -\u003e read()/write()\n - added documentation\n0.1.2 - 2/04/2004\n - added clienttest/servertest functions\n - improved OpenSSL cipher wrappers speed\n - fixed server when it has a key, but client selects plain SRP\n - fixed server to postpone errors until it has read client's messages\n - fixed ServerHello to only include extension data if necessary\n0.1.1 - 2/02/2004\n - fixed close_notify behavior\n - fixed handling of empty application data packets\n - fixed socket reads to not consume extra bytes\n - added testing functions to tls.py\n0.1.0 - 2/01/2004\n - first release\n\n\n15 References\n==============\n[0] http://www.ietf.org/html.charters/tls-charter.html\n[1] http://www.trevp.net/tls_srp/draft-ietf-tls-srp-07.html\n[2] http://www.ietf.org/internet-drafts/draft-ietf-tls-sharedkeys-02.txt\n[3] http://www.trevp.net/cryptoID/\n[4] http://www.openssl.org/\n[5] http://www.cs.auckland.ac.nz/~pgut001/cryptlib/\n[6] http://sandbox.rulemaker.net/ngps/m2/\n[7] http://trevp.net/cryptlibConverter/\n[8] http://www.trevp.net/cryptoID/\n[9] http://www.amk.ca/python/code/crypto.html\n[10] http://gmpy.sourceforge.net/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foperasoftware%2Ftlslite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foperasoftware%2Ftlslite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foperasoftware%2Ftlslite/lists"}