Skip to content
Browse files

working on key tool

git-svn-id: svn://forre.st/undns@1189 470744a7-cac9-478e-843e-5ec1b25c69e8
  • Loading branch information...
1 parent 63d6467 commit 5a49daf2af8d20f164b5a1578c8aba94b75a976b forrest committed Mar 7, 2011
Showing with 142 additions and 4 deletions.
  1. +50 −4 server.py
  2. +19 −0 test.sh
  3. +55 −0 tool.py
  4. +18 −0 util.py
View
54 server.py
@@ -1,21 +1,67 @@
+import os
+import sys
+import random
+import hashlib
+
import twisted.names.common, twisted.names.client, twisted.names.dns, twisted.names.server
del twisted
-
from twisted import names
from twisted.internet import reactor, defer
from twisted.python import failure
-class Mine(names.common.ResolverBase):
+from entangled.kademlia import node, datastore
+
+# config
+
+port = random.randrange(49152, 65535)
+print "PORT:", port
+
+def parse(x):
+ ip, port = x.split(':')
+ return ip, int(port)
+knownNodes = map(parse, sys.argv[1:])
+
+my_data = ("i live at port %i" % (port,), "teehee port %i is the place to be" % (port,))
+
+# DHT
+
+dbFilename = '/tmp/undns%i.db' % (port,)
+if os.path.isfile(dbFilename):
+ os.remove(dbFilename)
+dataStore = datastore.SQLiteDataStore(dbFile=dbFilename)
+
+n = node.Node(udpPort=port, dataStore=dataStore)
+n.joinNetwork(knownNodes)
+
+print "ID:", n.id.encode('hex')
+
+def store(*args):
+ n.iterativeStore(hashlib.sha1(my_data[0]).digest(), my_data[1])
+ reactor.callLater(15, store)
+n._joinDeferred.addCallback(store)
+
+def print_loop():
+ n.printContacts()
+ reactor.callLater(10, print_loop)
+print_loop()
+
+# DNS
+
+class UnDNSResolver(names.common.ResolverBase):
+ def __init__(self, dht):
+ names.common.ResolverBase.__init__(self)
+ self.dht = dht
def _lookup(self, name, cls, type, timeout):
if not name.endswith('.undns.forre.st'):
return defer.fail(failure.Failure(names.dns.DomainError(name)))
name2 = name[:-len('.undns.forre.st')]
print name2, names.dns.QUERY_CLASSES[cls], names.dns.QUERY_TYPES[type], timeout
return defer.fail(failure.Failure(names.dns.AuthoritativeDomainError(name)))
-f = names.server.DNSServerFactory(authorities=[Mine()], clients=[names.client.createResolver()], verbose=1000)
-
+f = names.server.DNSServerFactory(authorities=[UnDNSResolver(n)], clients=[names.client.createResolver()])
reactor.listenTCP(53, f)
reactor.listenUDP(53, names.dns.DNSDatagramProtocol(f))
+# global
+
reactor.run()
View
19 test.sh
@@ -0,0 +1,19 @@
+export PYTHONPATH=~/repos/pycrypto/build/lib.linux-i686-2.7/
+
+python tool.py generate > .key
+
+echo key:
+cat .key
+
+python tool.py info .key > .url
+
+echo url:
+cat .url
+
+python tool.py encode .key <(echo -n hello, world) > .packet
+
+echo packet:
+cat .packet
+
+echo decode:
+python tool.py decode .packet $(cat .url)
View
55 tool.py
@@ -0,0 +1,55 @@
+import sys
+import hashlib
+import json
+
+from Crypto.PublicKey import RSA
+from Crypto import Random
+
+import util
+
+rng = Random.new().read
+
+def key_to_tuple(k):
+ if k.has_private():
+ return (k.n, k.e, k.d, k.p, k.q, k.u)
+ else:
+ return (k.n, k.e)
+
+def tuple_to_key(t):
+ return RSA.construct(map(long, t))
+
+def key_to_address(k):
+ hash = int(hashlib.sha1(RSApubkey.exportKey()).hexdigest(), 16)
+ return util.int_to_string(hash, util.alphabet) + ".undns.forre.st"
+
+if sys.argv[1] == "generate":
+ RSAkey = RSA.generate(1024, rng)
+ print json.dumps(key_to_tuple(RSAkey.key))
+
+elif sys.argv[1] == "info":
+ RSApubkey = tuple_to_key(json.loads(open(sys.argv[2]).read())).publickey()
+ print key_to_address(RSApubkey)
+
+elif sys.argv[1] == "encode":
+ RSAkey = tuple_to_key(json.loads(open(sys.argv[2]).read()))
+ if not RSAkey.has_private():
+ print "not a private key"
+ sys.exit(1)
+ RSApubkey = RSAkey.publickey()
+
+ data = open(sys.argv[3]).read()
+
+ packet = {'pubkey': key_to_tuple(RSApubkey.key), 'data': data, 'data_hash_signed': RSAkey.sign(hashlib.sha1(data).digest(), rng)}
+ print json.dumps(packet)
+
+elif sys.argv[1] == "decode":
+ packet = json.loads(open(sys.argv[2]).read())
+ RSApubkey = tuple_to_key(packet['pubkey'])
+ data = packet['data']
+ data_hash_signed = packet['data_hash_signed']
+
+ address = sys.argv[3]
+
+ print "pubkey matches:", key_to_address(RSApubkey) == address
+ print "data valid:", RSApubkey.verify(hashlib.sha1(data).digest(), data_hash_signed)
+ print "data:", repr(data)
View
18 util.py
@@ -0,0 +1,18 @@
+def int_to_string(i, alphabet):
+ res = []
+ while True:
+ res.append(i % len(alphabet))
+ i //= len(alphabet)
+ if not i:
+ break
+ return ''.join(alphabet[x] for x in reversed(res))
+def string_to_int(s, alphabet):
+ acc = 0
+ place_value = 1
+ for char in s[::-1]:
+ acc += place_value * alphabet.index(char)
+ place_value *= len(alphabet)
+ return acc
+
+alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'
+

0 comments on commit 5a49daf

Please sign in to comment.
Something went wrong with that request. Please try again.