カエサル暗号

30分プログラム、その382。Pythonカエサル暗号。

という理由で作ってみた。

使い方

>>> enc = Encoder(3)
>>> enc.encode(u'abc')
u'def'
>>> enc.encode(u'あいう')
u'ぅぇぉ'

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# 2008-10-05-204214.py -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/10/05 20:42:16
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

import fileinput
class Encoder:
    def __init__(self,n):
        self.n = n

    def encode(self,cs):
        return ''.join(map(self.__d2e,cs))

    def decode(self,cs):
        return ''.join(map(self.__e2d,cs))

    def __d2e(self,c):
        return unichr(ord(c)+self.n)

    def __e2d(self,c):
        return unichr(ord(c)-self.n)


if __name__ == '__main__':
    import sys
    import codecs
    sys.stdin  = codecs.getreader('utf-8')(sys.stdin)
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
    enc = Encoder(16)
    for line in fileinput.input(): 
        x = enc.encode(line)
        print "original: ",line,
        print "encode:   ",x
        print "decode:   ",enc.decode(x),