Skip to content

Instantly share code, notes, and snippets.

@mozurin
Created March 22, 2021 18:00
Show Gist options
  • Save mozurin/40ba8521537c304140272e8775bc6be6 to your computer and use it in GitHub Desktop.
Save mozurin/40ba8521537c304140272e8775bc6be6 to your computer and use it in GitHub Desktop.
5ch (2ch) trip calculator snippet.
# 5ch (2ch) trip calculator snippet
import re
import base64
import hashlib
from passlib.hash import des_crypt
DEFAULT_CHARSET = 'ms932'
TRIP_MARK = '◆'
SALT_TRANSLATOR = bytes.maketrans(rb':;<=>?@[\]^_`', b'ABCDEFGabcdef')
re_raw_trip = re.compile(
'^#(?P<bytes>[a-zA-Z0-9]{16})(?P<salt>[a-zA-Z0-9./]{,2})$'
)
def entrip(name: str, charset: str = DEFAULT_CHARSET) -> str:
'''
Encrypt trip key value in handle name field to trip.
'''
if '#' not in name:
return name
prefix, tripkey = name.split('#', 1)
tripkey = bytes(tripkey, encoding=charset)
if len(tripkey) < 12:
# 10 digits, normal
salt = bytes(
c if 0x2e <= c <= 0x7a else 0x2e for c in (tripkey + b'H.')[1:3]
).translate(SALT_TRANSLATOR)
return (
prefix + TRIP_MARK +
des_crypt.hash(tripkey, salt=salt.decode('ascii'))[-10:]
)
if tripkey.startswith(b'#') or tripkey.startswith(b'$'):
# 10 digits, raw key
m = re_raw_trip.match(tripkey.decode(charset))
if not m:
# unsupported; reserved for future use
return prefix + TRIP_MARK + '???'
else:
return (
prefix + TRIP_MARK +
des_crypt.hash(
bytes.fromhex(m.group('bytes')),
salt=(m.group('salt') + '..')[:2]
)[-10:]
)
# 12 digits, normal
return (
prefix + TRIP_MARK +
base64.b64encode(
hashlib.sha1(tripkey).digest()
)[:12].decode('ascii').replace('+', '.')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment