2009-09-24

Calculating the keytag of a DNSKEY in Python

In DNSEC, sometimes you want to know the "keytag" of a DNSKEY record. Here's a Python implementation that uses dnspython:

import struct

def keytag(dnskey):
"""
Given a dns.rdtypes.ANY.DNSKEY dnskey, compute and return its keytag.

For details, see RFC 2535, section 4.1.6
"""
if dnskey.algorithm == 1:
a = ord(dnskey.key[-3]) << 8
b = ord(dnskey.key[-2])
return a + b
else:
header = struct.pack("!HBB", dnskey.flags, dnskey.protocol, dnskey.algorithm)
key = header + dnskey.key
ac = 0
for i, value in enumerate(ord(x) for x in key):
if i % 2:
ac += value
else:
ac += (value << 8)
ac += (ac >> 16) & 0xffff
return ac & 0xffff

2009-09-15

Using Django's Syncdb outside of Django

I'm working on another project that uses Django's ORM that isn't (yet) a web applicaiton. There's no settings.py file as the application has its own configuration system build on ConfigObj and optparase. But, before you can use the app, you need to create the tables that Django's ORM needs for your Models. If you app lives in a python package named 'fooapp', then put your Django models in fooapp.models and try this code:

from django.conf import settings
from django.core.management.commands import syncdb

opts, args = build_configuration()
my_app = 'fooapp'
settings.configure(
DATABASE_ENGINE=opts['db_engine'],
DATABASE_NAME=opts['db_name'],
DATABASE_USER=opts['db_user'],
DATABASE_PASSWORD=opts['db_pass'],
DATABASE_HOST=opts['db_host'],
DATABASE_PORT=opts['db_port'],
INSTALLED_APPS=(my_app,)
)
cmd = syncdb.Command()
cmd.handle_noargs()



And do let me know if that works. Thanks!