JavaScript“ String.fromCharCode”返回的字符集与Python的“ chr”函数不同

时间:2019-08-06 16:42:25

标签: javascript python chr fromcharcode

我正在尝试运行一种加密算法,该算法采用输入消息,将其分为四个字符的块,将“ x”位从前向后移动,然后将其转换回四个加扰的字符。尽管我不太确定,但我相信这被称为分块密码。在Python中运行时,该程序可以完美加密和解密。但是,将代码手动转换为JavaScript之后,我从String.fromCharCode方法获得了一些奇怪的结果。简而言之,即使消息和密钥保持相同,JavaScript方法也比Python返回更多的字符,特别是“”字符。对于如何解决此问题以及确切是什么的问题,我将不胜感激。

此代码用于我正在开发的工具,我需要尽快完成它。我已经尝试使用Node Package Manager中的utf8模块将JavaScript字符编码转换为“ UTF-8”,但无济于事。我多次检查了我的代码,除了进行字符转换外,Python和JavaScript代码还在做同样的事情,并产生相同的数字和值。在下面的代码中,我要提到的问题源自JavaScript代码中的“ reconstructMsg”函数。

// JavaScript:
import integerBitLength from 'integer-bit-length';

// Function to break message into chunks
function chunkMsg(message, chunkSize = 4) {
  // Create an array to store the chunks
  let msgChunks = [];
  // Control
  let chunk = 0,
    chunkCount = Math.floor(message.length / chunkSize) + 1;

  // Iterate through the message
  for (let num of [
    ...Array(chunkCount * chunkSize).keys()
  ]) {
    // Make room for the next chunk's number
    chunk = chunk << 8;
    // Make sure that 'num' is within the length of 'message'
    if (num < message.length) chunk += message[num].charCodeAt(0);
    // Check if there are the ascii values of four characters in the chunk
    if (integerBitLength(chunk) > (chunkSize - 1) * 8) {
      // Append chunk
      msgChunks.push(chunk);
      // Reset chunk
      chunk = 0;
    }
  }

  // Return the chunk array
  return msgChunks;
}

// Function to reconstruct message
function reconstructMsg(chunks, chunkSize = 4) {
  // Empty message
  let msg = '';
  // Iterate through all of the chunks
  for (let i = 0; i < chunks.length; i++) {
    let chunk = chunks[i];
    // Loop through each chunk
    for (let j = 0; j < chunkSize; j++) {
      // NOTES on the below code
      // (8 * (chunk_size - 1 - j)) is the number of bits to chop off of the end
      // (chunk >> <above_code>) chops the number of bits above off of the chunk
      // <above_code> % 2 ** 8 takes only the first 8 bits from the above code
      // because 2 ** 8 = 256
      // the modulo function (x % y) can have a max value of "y - 1" and 8 bits can have a max value of 255
      // In other words, because everything above the 8th bit is a multiple of 256, we ignore them
      let number = (chunk >>> (8 * (chunkSize - 1 - j))) % 2 ** 8;
      // Add the character with the above keycode to the message
      msg += String.fromCharCode(number);
    }
  }
  // Return the message
  return msg;
}

// Function to encrypt chunks in a message
function encryptMsg(chunks, key, chunkSize = 4) {
  // List of encrypted chunks
  let cipherList = [];
  // Set the maximum amount of bits
  let bitCount = chunkSize * 8;
  // Iterate through the chunks
  for (let i of [
    ...Array(chunks.length).keys()
  ]) {
    // Set chunk
    let chunk = chunks[i];
    // Set the bits to carry
    let carry = chunk % 2 ** key;
    // Make room for the remaining bits to be places at the end
    carry = (carry << (bitCount - key)) >>> 0;
    // Combine the shifted characters
    let cipher = (chunk >>> key) + carry;
    // Add cipher
    cipherList.push(cipher);
  }
  // Return the cipher list
  return cipherList;
}
# Python:
# Function to chunk message into sets of 32-bits
def chunk_msg(msg, chunk_size=4):
    # Create a list to store the chunks
    msg_chunks = []

    # Control variables
    chunk = 0
    chunk_count = len(msg) // chunk_size + 1

    # Iterate through the message
    for i in range(chunk_count * chunk_size):
        # Make room for the next character's number
        chunk = chunk << 8
        # Make sure that i is within the length of the function
        if i < len(msg):
            chunk += ord(msg[i])
        # If the chunk has 4 characters in their ascii encoding, save the chunk
        if chunk.bit_length() > (chunk_size - 1) * 8:
            msg_chunks.append(chunk)
            chunk = 0
    # Return the chunks
    return msg_chunks


# Function to reconstruct message
def reconstruct_msg(chunks, chunk_size=4):
    # Empty message
    msg = ""
    # Iterate through all of the chunks
    for i in range(len(chunks)):
        chunk = chunks[i]
        # Loop through each chunk
        for j in range(chunk_size):
            # NOTES on the below code
            # (8 * (chunk_size - 1 - j)) is the number of bits to chop off of the end
            # (chunk >> <above_code>) chops the number of bits above off of the chunk
            # <above_code> % 2 ** 8 takes only the first 8 bits from the above code
            # because 2 ** 8 = 256
            # the modulo function (x % y) can have a max value of "y - 1" and 8 bits can have a max value of 255
            # In other words, because everything above the 8th bit is a multiple of 256, we ignore them
            number = (chunk >> (8 * (chunk_size - 1 - j))) % 2**8
            print(number)
            # Add the character with the above keycode to the message
            msg += chr(number)
            print(f"\n\n{chr(number)}")

    # Return the message
    return msg


# Function to encrypt chunks
def apply_rotate(msg_list, key, chunk_size=4):
    cipher_list = []
    # Set the maximum amount of bits
    bit_count = chunk_size * 8
    # Iterate through each message chunk
    for i in range(len(msg_list)):
        # Set chunk
        chunk = msg_list[i]
        print(chunk)
        # Set the bits to carry
        carry = chunk % (2**key)
        # Make room for the remaining bits to be placed on the end
        carry = carry << (bit_count - key)
        # Combine the shifted characters into a variable
        cipher = (chunk >> key) + carry
        # Add the encoded chunk to the list
        cipher_list.append(cipher)
    print(cipher_list)
    # Return the cipher list
    return cipher_list

按顺序运行上述功能时: chunkMsg,encryptMsg和reconstructMsg,消息为“ Hello”,密钥为12,Python生成正确的字符串“ÆÄVð”,而JavaScript生成错误的字符串“ÆÄVð”(Ä之间存在未定义的字符以及V,V和ð,以及ð和消息的结尾。问题一旦发布,它们可能不会出现在问题中。

我再次感谢您在此问题上的任何帮助,如果问题有点冗长,我深表歉意。

0 个答案:

没有答案