2020年3月5日木曜日

AES 暗号化

JWT debugger : https://jwt.io/

#!/usr/bin/env python36
# coding=utf-8
import base64
import string, random
import json
from Crypto import Random
from Crypto.Cipher import AES


def generateNewSeed( n=32 ):
  return(''.join([random.choice(string.ascii_letters + string.digits) for i in range(n)]))

class AESCipher(object):
  def __init__(self, seed, block_size=32):
    self.bs = block_size
    if len(seed) >= block_size:
      self.key = seed[:block_size]
    else:
      self.key = self._pad(seed)

  def encrypt(self, raw):
    raw = self._pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw))

  def decrypt(self, enc):
    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
    return self._unpad(cipher.decrypt(enc[AES.block_size:]))

  def _pad(self, s):
    return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

  def _unpad(self, s):
    return s[:-ord(s[len(s)-1:])]

  def _getkey( self ):
    return self.key

  def encryptGCSRToken( self, gcode, ccode, scode, rcode, token ):
    data = { 'gcode':gcode, 'ccode':ccode, 'scode':scode, 'rcode':rcode, 'token':token }
    raw  = json.dumps( data )
    return( self.encrypt( raw ))

  def decryptGCSRToken( self, cipher  ):
    raw = self.decrypt( cipher )
    data = json.loads( raw )
    return data['gcode'], data['ccode'],data['scode'],data['rcode'],data['token']

def main():
  seed = generateNewSeed()

  CIPHER = AESCipher( seed )

  print( "seed=", seed )
  print( "key(getkey)=", CIPHER._getkey() )
  print( "block size=",AES.block_size )

  # 暗号化
  encryption = CIPHER.encrypt("hogefuga")
  print( 'ENCRYPTION =',encryption)

  encryption1 = CIPHER.encrypt("hogefuga")
  print( 'ENCRYPTION1=',encryption1)

  # 復号化
  print(CIPHER.decrypt(encryption))
  print(CIPHER.decrypt(encryption))


  gcode = '901'
  ccode = '1003'
  scode = '0002'
  rcode = '77xxxxxxxxxx1'
  token = 'tokenxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtoken'


  cipher = CIPHER.encryptGCSRToken( gcode, ccode, scode, rcode, token )

  print( 'cipher=', cipher )                 # GCSR +TOKEN 端末内に格納

  gcode, ccode, scode, rcode, token = CIPHER.decryptGCSRToken( cipher )

  print( gcode )
  print( ccode )
  print( scode )
  print( rcode )
  print( token )


if __name__ == "__main__":
    main()

0 件のコメント:

コメントを投稿

zabbix7 amazon linux2023 インストール postgres15

【postgres】 dnf -y install postgresql15-server postgresql15-server-devel postgresql-setup initdb passwd postgres vi `find / -name pg_hba.con...