Mã hóa/giải mã hex và base64

8/23/2024, 8:02:26 AM

当前为 2024-08-23 提交的版本,查看 最新版本

// ==UserScript==
// @name        Mã hóa/giải mã hex và base64
// @namespace   Violentmonkey Scripts
// @match       *://*.*/*
// @grant       none
// @version     1.0.1
// @author      -
// @description 8/23/2024, 8:02:26 AM
// ==/UserScript==
const isHexStr = str => /^(0x|0X)?([0-9a-fA-F]{2})+$/g.test(str.trim());

const isBase64 = str => /^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)?$/g.test(str.trim());

function hex2Str(hexStr) {
  hexStr=hexStr.toString().trim();
  if (!isHexStr(hexStr)) return false;
  if (hexStr.startsWith('0x') || hexStr.startsWith('0X')) hexStr=hexStr.slice(2);
  let result='';
  for (let i=0; i<hexStr.length; i+=2) result+=String.fromCharCode(parseInt(hexStr.slice(i,i+2),16))
  return result;
}

function str2Hex(str) {
  str = str.toString().trim();
  let result = '';
  for (let i = 0; i < str.length; i++) result += str.charCodeAt(i).toString(16)
  return result;
}

(function main(){
  document.body.insertAdjacentHTML('beforeend',`
  <style>
  #us_hexdecode_dialog {
    max-width:60%;
  }

  #us_hexdecode_dialog::backdrop{
    background-color: rgb(117 190 218 / 50%);
  }
  </style>
  <dialog id="us_hexdecode_dialog"><div></div><button>OK</button></dialog>`);
  const dialog=document.getElementById('us_hexdecode_dialog');
  document.addEventListener("contextmenu", e => {
    let str='';
    let aE=document.activeElement;
    if (aE?.tagName=='TEXTAREA' ||(aE?.tagName=='INPUT' && aE?.type=='text')) str=aE.value.substring(aE.selectionStart,aE.selectionEnd).trim();
    else  str=document.getSelection().toString().trim();
    if (/(^(.{4}\s)+.{4}$)|(^(.{2}\s)+.{2}$)/.test(str)) str=str.replaceAll(/[ ]/g,'');
    if (str=='') return;
    e.preventDefault();
    let htmlStr='';

    const dialog_div=dialog.querySelector('div');
    dialog_div.innerHTML='';
    if (isHexStr(str)) dialog_div.innerHTML+=`Hex decode: ${hex2Str(str)}<br/><br/>`;
    else dialog_div.innerHTML+=`Hex encode: ${str2Hex(str)}<br/><br/>`;

    if (isBase64(str)) dialog_div.innerHTML+=`Base64 decode: ${atob(str)}`;
    else dialog_div.innerHTML+=`Base64 encode: ${btoa(unescape(encodeURIComponent(str)))}`;

    dialog.querySelector('button').onclick=()=>dialog.close();
    dialog.showModal();
  },true)
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址