Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nodejs 的一些加密算法 #51

Open
yaogengzhu opened this issue Jul 11, 2024 · 0 comments
Open

nodejs 的一些加密算法 #51

yaogengzhu opened this issue Jul 11, 2024 · 0 comments

Comments

@yaogengzhu
Copy link
Owner

DESkey 处理

/**
 * 截取密钥,使其长度为8字节
 * @param {*} key
 * @returns
 */
function padKeyToEightBytes(key) {
  const keyBuffer = Buffer.from(key);
  const paddedKey = Buffer.alloc(8); // 创建一个8字节的缓冲区
  keyBuffer.copy(paddedKey); // 将原始密钥复制到缓冲区中
  // 如果原始密钥长度小于8字节,用0填充剩余部分
  if (keyBuffer.length < 8) {
    paddedKey.fill(0, keyBuffer.length);
  }
  // 如果原始密钥长度大于8字节,只保留前8字节
  else if (keyBuffer.length > 8) {
    paddedKey.write(key.slice(0, 8));
  }
  return paddedKey;
}

DES 加密处理

/**
 * DES加密的函数
 * @param {'*'} text
 * @param {*} secretKey
 * @returns
 */
function encryptWithDES(text) {
  try {
    let desKey = Buffer.from(
      padKeyToEightBytes('key'),
    );
    var cipher = crypto.createCipheriv('des-ecb', desKey, '');
    let c = cipher.update(text, 'utf8', 'base64');
    c += cipher.final('base64');
    return c;
  } catch (e) {
    console.log(e, 'error');
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant