wiki:TLSLiteの短いソースコード集

Version 7 (modified by nakiki, 13 years ago) (diff)

--

ランダムバイトの生成

import tlslite.utils.cryptomath as cryptomath

n =  cryptomath.getRandomBytes(20).tostring()
print (n,)

大きな素数の生成

import tlslite.utils.cryptomath as cryptomath

n = cryptomath.getRandomPrime(200, False)
print (n,)

素数かどうかのテスト

import tlslite.utils.cryptomath as cryptomath

n = 1316313479575724008406254458954831022206765279617514697838759L
print cryptomath.isPrime(n, iterations = 20)
n = 1316313479575724008406254458954831022206765229617514697838759L
print cryptomath.isPrime(n, iterations = 20)
  • 適切なiterationsの値とは?

デジタル証明書の読み込み

import tlslite.api as tls

s = open("./clientX509Cert.pem").read()
x509 = tls.X509()
x509.parse(s)
print "fingerprint=", x509.getFingerprint()

べき乗剰余

import tlslite.utils.cryptomath as cryptomath

g = 5
p = cryptomath.getRandomPrime(128)
x = 0x640F7967334E9872
y = 0x40F6BD5315A291DC

Y = cryptomath.powMod(g, y, p) # (Y = g^y mod p)
  • 逆の計算が難しいことを暗号学ではよく利用する。

AESによるデータの暗号化

import tlslite.utils.cipherfactory as cipherfactory

key = 'khkdjsldkfs9321k'
iv = '0248264923047183'
data = '1234567890123456'

enc = cipherfactory.createAES(key, iv)
dec = cipherfactory.createAES(key, iv)

enc_data = enc.encrypt(data)
dec_data = dec.decrypt(enc_data)
if dec_data == data:
  print 'ok'
else:
  print 'ng'
  • 16バイトブロックであることに注意
  • 安全性を保障するには共有鍵は秘密にする必要がある。

TLSサーバ

# -*- coding: utf-8 -*-
#!/usr/bin/python

import socket
import SocketServer as ss
import tlslite.api as tls

# 証明書を使った場合の例
class Handler(ss.StreamRequestHandler):
  def setup(self):
    self.connection = tls.TLSConnection(self.request)
    self.connection.closeSocket = True
    s = open("./serverX509Cert.pem").read()
    x509 = tls.X509()
    x509.parse(s)
    certChain = tls.X509CertChain([x509])
    s = open("./serverX509Key.pem").read()
    privateKey = tls.parsePEMKey(s, private=True)

    settings = tls.HandshakeSettings()
    settings.cipherNames = ["aes128"]
    # 提示されるクライアントの証明書のfingerprint
    checker = tls.Checker(x509Fingerprint= 'cbfef53d18298d7a432720a39232f0ce22e9
a30a')
    self.connection.handshakeServer(certChain=certChain,
      privateKey =privateKey, checker = checker, reqCert = True,
      settings = settings)
    self.rfile = self.connection.makefile('rb', self.rbufsize)
    self.wfile = self.connection.makefile('wb', self.wbufsize)

  def handle(self):
    print 'handle'
    while 1:
      line = self.rfile.readline()
      if len(line) == 0:
        return
      self.wfile.write(line)

class Server(ss.ThreadingTCPServer):
  allow_reuse_address = 1
  daemon_threads = 1

server = Server(('localhost', 3746), Handler)
print 'listening:', server.socket.getsockname()
server.serve_forever()
  • 証明書はTLSLiteのサンプルにあるものです。

TLSクライアント

# -*- coding: utf-8 -*-
#!/usr/bin/python

import socket
import tlslite.api as tls
import sys

DST = ('localhost', 3746)

# 証明書を使った場合の例
def connect(sockaddr):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect(sockaddr)
  sock.settimeout(10)
  conn = tls.TLSConnection(sock)
  conn.closeSocket = True
  s = open("./clientX509Cert.pem").read()
  x509 = tls.X509()
  x509.parse(s)
  print "fingerprint=", x509.getFingerprint()
  certChain = tls.X509CertChain([x509])
  s = open("./clientX509Key.pem").read()
  privateKey = tls.parsePEMKey(s, private=True)
  # 提示されるサーバの証明書のfingerprint
  checker = tls.Checker(x509Fingerprint= '8b8a01e15a2095da731a9b864a30ae272d0381
80')
  conn.handshakeClientCert(certChain = certChain, privateKey = privateKey,
    checker = checker)
  return conn

conn = connect(DST)
rfile = conn.makefile('rb')
while 1:
  print '> ',
  line = sys.stdin.readline()
  if len(line) == 0:
    conn.close()
    print
    break
  conn.write(line)
  line = rfile.readline()
  if len(line) == 0:
    conn.close()
    print 'EOF'
    break
  sys.stdout.write(line)

SRPサーバ

# -*- coding: utf-8 -*-
#!/usr/bin/python

import socket
import SocketServer as ss
import tlslite.api as tls

sharedKeyDB = tls.SharedKeyDB()
sharedKeyDB.create()
sharedKeyDB['nakiki'] = 'nakikinakiki'

# 共有鍵を使った例
class Handler(ss.StreamRequestHandler):
  def setup(self):
    self.connection = tls.TLSConnection(self.request)
    self.connection.closeSocket = True
    settings = tls.HandshakeSettings()
    settings.cipherNames = ["aes128"]
    self.connection.handshakeServer(sharedKeyDB = sharedKeyDB,
      settings = settings)
    self.rfile = self.connection.makefile('rb', self.rbufsize)
    self.wfile = self.connection.makefile('wb', self.wbufsize)

  def handle(self):
    print 'handle'
    while 1:
      line = self.rfile.readline()
      if len(line) == 0:
        return
      self.wfile.write(line)

class Server(ss.ThreadingTCPServer):
  allow_reuse_address = 1
  daemon_threads = 1

server = Server(('localhost', 3747), Handler)
print 'listening:', server.socket.getsockname()
server.serve_forever()

SRPクライアント

# -*- coding: utf-8 -*-
#!/usr/bin/python

import socket
import tlslite.api as tls
import sys

DST = ('localhost', 3747)

# 証明書を使った場合の例
def connect(sockaddr):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect(sockaddr)
  sock.settimeout(10)
  conn = tls.TLSConnection(sock)
  conn.closeSocket = True
  conn.handshakeClientSharedKey(username = 'nakiki', sharedKey = 'nakikinakiki')
  return conn

conn = connect(DST)
rfile = conn.makefile('rb')
while 1:
  print '> ',
  line = sys.stdin.readline()
  if len(line) == 0:
    conn.close()
    print
    break
  conn.write(line)
  line = rfile.readline()
  if len(line) == 0:
    conn.close()
    print 'EOF'
    break
  sys.stdout.write(line)