You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入错误密码解锁CryptoJS加密内容时如何显示提示框

解决错误密码时显示提示框的问题

当使用CryptoJS解密错误密码时,decrypted.toString(CryptoJS.enc.Utf8)会返回空字符串(因为解密后的字节无法解析为有效的UTF-8文本)。我们可以利用这个特性来判断密码是否正确,再通过你已有的#decrypt-alert容器展示错误提示。

以下是修改后的完整代码,我标注了关键改动点:

<div id="decrypt-box">
  <div class="decrypt-form" id="decryption" data-href="U2FsdGVkX1+Fg5XynZFlZHmhvMhAw9l7jlKt2WEpYYWEkOy7L360rZ7xd19TvoXp">
    <div> password to unlock: asd</div>
    <form action="#" id="decrypt-form" method="post">
      <input autofocus="" id="decrypt-password" name="password" placeholder="Password" type="password" />
      <input class="decrypt-button" type="submit" value="Unlock" />
    </form>
    <div id="decrypt-alert" style="color: red; margin-top: 10px;"></div> <!-- 先加基础样式让提示更醒目 -->
  </div>
</div>
<div id='decrypt-content'></div>

<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<script>
document.getElementById('decrypt-form').addEventListener('submit', function(e) {
  e.preventDefault();
  
  var c = document.getElementById('decryption');
  var encryptedMsg = c.getAttribute('data-href');
  var passphrase = document.getElementById('decrypt-password').value;
  var decrypted = CryptoJS.AES.decrypt(encryptedMsg, passphrase);
  decrypted = decrypted.toString(CryptoJS.enc.Utf8);
  
  // 获取提示框和内容容器元素
  const alertBox = document.getElementById('decrypt-alert');
  const contentBox = document.getElementById('decrypt-content');
  
  if (decrypted) {
    // 解密成功:展示内容,清空提示
    contentBox.innerHTML = decrypted;
    alertBox.textContent = '';
  } else {
    // 解密失败:显示错误提示,清空旧内容(可选)
    alertBox.textContent = '密码错误,请重试!';
    contentBox.innerHTML = ''; // 可选操作:避免残留之前的内容
  }
});
</script>

关键改动说明:

  • 给#decrypt-alert添加了红色文字的基础样式,让错误提示一眼就能看到(你也可以换成自定义的CSS类来控制样式)。
  • 新增了解密结果的判断逻辑:
    • 若decrypted不为空,说明密码正确,正常展示解密内容并清空提示框。
    • 若decrypted为空,说明密码错误,在提示框中显示错误信息,同时可选清空内容容器避免残留旧内容。

额外优化小建议:

  • 可以给提示框加个淡入淡出的动画,提升用户体验。
  • 如果担心加密内容本身就是空字符串导致误判,可以在加密时给原始内容加个特定前缀(比如[VALID_CONTENT]),解密后检查是否包含该前缀来确认解密成功。

内容的提问来源于stack exchange,提问作者my notmypt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:34:42