[컴][웹] node-simple-encryptor 의 decrypt 를 python 으로 구현하기

node-simple-encryptor 를 python  에서 / 복호화 함수 / 암호화 함수 / 아도니스 암호화 / 복호화 / 파이썬으로

node-simple-encryptor 의 decrypt 를 python 으로 구현

Adonijs 의 Encryptor 는 node-simple-encryptor 를 사용한다. 여기서는 Encryptor.decrypt() 의 decrypt 부분을 python 으로 구현해 보자.


node-simple-encryptor 의 decrypt() 부분


module.exports = function(opts) {
  if( typeof(opts) == 'string' ) {
    opts = {
      key: opts,
      hmac: true,
      debug: false
    };
  }
  var key = opts.key;
  var verifyHmac = opts.hmac;
  var debug = opts.debug;
  var reviver = opts.reviver;

  ...
  // Use SHA-256 to derive a 32-byte key from the specified string.
  // NOTE: We could alternatively do some kind of key stretching here.
  var cryptoKey = crypto.createHash('sha256').update(key).digest();
  ...

  function decrypt(cipherText) {
    if( !cipherText ) {
      return null;
    }
    try {
      if( verifyHmac ) {
        // Extract the HMAC from the start of the message:
        var expectedHmac = cipherText.substring(0, 64);
        // The remaining message is the IV + encrypted message:
        cipherText = cipherText.substring(64);
        // Calculate the actual HMAC of the message:
        var actualHmac = hmac(cipherText);
        if( !scmp(Buffer.from(actualHmac, 'hex'), Buffer.from(expectedHmac, 'hex')) ) {
          throw new Error('HMAC does not match');
        }
      }

      // Extract the IV from the beginning of the message:
      var iv = new Buffer(cipherText.substring(0,32), 'hex');
      // The remaining text is the encrypted JSON:
      var encryptedJson = cipherText.substring(32);

      // Make sure to use the 'iv' variant when creating the decipher object:
      var decipher = crypto.createDecipheriv('aes256', cryptoKey, iv);
      // Decrypt the JSON:
      var json = decipher.update(encryptedJson, 'base64', 'utf8') + decipher.final('utf8');

      // Return the parsed object:
      return JSON.parse(json, reviver);
    } catch( e ) {
      // If we get an error log it and ignore it. Decrypting should never fail.
      if( debug ) {
        console.error('Exception in decrypt (ignored): %s', e);
      }
      return null;
    }
  }

python 구현

class NodeSimpleEncrypter:
    """

    """


    KEY = b"FFfBEVh5Dr1BhJiEi3mnCsB6nByGv1iL"
    IV_LEN = 16

    def __init__(self):
        pass


    @staticmethod
    def decryptForV2(value):
        m = hashlib.sha256()
        m.update(NodeSimpleEncrypter.KEY)
        key = m.digest()

        cipherText = value[64:]

        ivstr = cipherText[:32]
        iv = binascii.unhexlify(ivstr)

        encodedBody = cipherText[32:]
        body = base64.b64decode(encodedBody)

        # CBC MODE
        # https://gist.github.com/forkd/168c9d74b988391e702aac5f4aa69e41
        # https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode
        aes = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)

        return unpad(aes.decrypt(body), AES.block_size)

댓글 없음:

댓글 쓰기