Skip to content

Instantly share code, notes, and snippets.

@yuitest
Created December 8, 2014 13:42
Show Gist options
  • Select an option

  • Save yuitest/7ec3854b05756a7e3daa to your computer and use it in GitHub Desktop.

Select an option

Save yuitest/7ec3854b05756a7e3daa to your computer and use it in GitHub Desktop.
# coding: utf-8
import crypt
import ctypes
import ctypes.util
import sys
u'''\
残念なことに Python 3 の crypt.crypt は、引数が bytes ではなく unicode 文字列になっている。
Python 2 ならば そのまま crypt.crypt を使う。
Python 2 でないなら ctypes 経由で用意して返す。
引数は crypt((bytearray)word, (bytearray)salt)
'''
def get_crypt():
if sys.version_info.major == 2:
def crypt_(word, salt):
return crypt.crypt(str(word), str(salt))
return crypt_
search_targets = ('libcrypt', 'libc')
for c in search_targets:
p = ctypes.util.find_library(c)
if p is not None:
break
else:
raise Exception('require crypt(3) library.')
cryptlib = ctypes.CDLL(p)
cryptlib.crypt.argtypes = (ctypes.c_char_p, ctypes.c_char_p)
cryptlib.crypt.restype = ctypes.c_char_p
def crypt_(word, salt):
return cryptlib.crypt(bytes(word), bytes(salt))
return crypt_
# coding: utf-8
import crypt
import string
import unicodedata
import get_crypt
def trip(
text,
_crypt=get_crypt.get_crypt(),
_salty=string.digits + string.ascii_letters + u'./'
):
if isinstance(text, bytes):
text = text.decode(u'utf8')
text = unicodedata.normalize(u'NFC', text)
word = bytearray((ord(char) & 255 | 128)
for char in text)[:13]
salt = bytearray(ord(char) if char in _salty else ord(b'.')
for char in text + u'H.')[:2]
return _crypt(word, salt)[3:]
def test():
answer_pairs = (
(b'', b'jPpg5.obl6'),
(b'舞24C送刀刀刀', b'mQDddDDDmE'),
(b'刀刀刀刀ながい夜', b'HHHhHVDpfI'),
(b'落ね刀★どてすぎ', b'stdioUH90w'),
(b'test', b'0wLIpW0gyQ'),
)
for input_, result in answer_pairs:
assert trip(input_) == result
assert trip(input_.decode('utf8')) == result
if __name__ == '__main__':
test()
while True:
try:
text = raw_input()
except EOFError:
break
print(trip(text))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment