Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / examples / simple / client.py
1 # -*- coding: latin-1 -*-
2 #
3 # Copyright (C) AB Strakt
4 # Copyright (C) Jean-Paul Calderone
5 # See LICENSE for details.
6
7 """
8 Simple SSL client, using blocking I/O
9 """
10
11 from OpenSSL import SSL
12 import sys, os, select, socket
13
14 def verify_cb(conn, cert, errnum, depth, ok):
15     # This obviously has to be updated
16     print 'Got certificate: %s' % cert.get_subject()
17     return ok
18
19 if len(sys.argv) < 3:
20     print 'Usage: python[2] client.py HOST PORT'
21     sys.exit(1)
22
23 dir = os.path.dirname(sys.argv[0])
24 if dir == '':
25     dir = os.curdir
26
27 # Initialize context
28 ctx = SSL.Context(SSL.SSLv23_METHOD)
29 ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a certificate
30 ctx.use_privatekey_file (os.path.join(dir, 'client.pkey'))
31 ctx.use_certificate_file(os.path.join(dir, 'client.cert'))
32 ctx.load_verify_locations(os.path.join(dir, 'CA.cert'))
33
34 # Set up client
35 sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
36 sock.connect((sys.argv[1], int(sys.argv[2])))
37
38 while 1:
39     line = sys.stdin.readline()
40     if line == '':
41         break
42     try:
43         sock.send(line)
44         sys.stdout.write(sock.recv(1024))
45         sys.stdout.flush()
46     except SSL.Error:
47         print 'Connection died unexpectedly'
48         break
49
50
51 sock.shutdown()
52 sock.close()