const hexToBytes = hex => new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
const deriveKey = async hexKey => {
const rawKey = hexToBytes(hexKey);
const baseKey = await crypto.subtle.importKey(
"raw", rawKey, "HKDF", false, ["deriveKey"]
);
return crypto.subtle.deriveKey(
{
name: "HKDF",
hash: "SHA-256",
salt: new Uint8Array(16),
info: new TextEncoder().encode("AES-GCM Key Derivation")
},
baseKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
};
const encrypt = async (text, hexKey) => {
const key = await deriveKey(hexKey);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoded = new TextEncoder().encode(text);
const ciphertext = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
encoded
);
const combined = new Uint8Array(iv.length + ciphertext.byteLength);
combined.set(iv);
combined.set(new Uint8Array(ciphertext), iv.length);
return Array.from(combined).map(b => b.toString(16).padStart(2, '0')).join("");
};
const decrypt = async (hexCiphertext, hexKey) => {
const key = await deriveKey(hexKey);
const combined = hexToBytes(hexCiphertext);
const iv = combined.slice(0, 12);
const ciphertext = combined.slice(12);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
key,
ciphertext
);
return new TextDecoder().decode(decrypted);
};
(async (message) => {
const myKey = window.app.appId;
dv.paragraph(`元のメッセージ: ${message}`);
const encryptedHex = await encrypt(message, myKey);
dv.paragraph(`暗号化された16進数文字列: ${encryptedHex}`);
const decryptedText = await decrypt(encryptedHex, myKey);
dv.paragraph(`復号されたメッセージ ${decryptedText}`);
})("ここにテキスト");js: (async()=>{const hexToBytes=hex=>new Uint8Array(hex.match(/.{1,2}/g).map(byte=>parseInt(byte,16)));const deriveKey=async hexKey=>{const rawKey=hexToBytes(hexKey);const baseKey=await crypto.subtle.importKey("raw",rawKey,"HKDF",false,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(16),info:new TextEncoder().encode("AES-GCM Key Derivation")},baseKey,{name:"AES-GCM",length:256},false,["encrypt","decrypt"]);};const decrypt=async(hexCiphertext,hexKey)=>{const key=await deriveKey(hexKey);const combined=hexToBytes(hexCiphertext);const iv=combined.slice(0,12);const ciphertext=combined.slice(12);const decrypted=await crypto.subtle.decrypt({name:"AES-GCM",iv:iv},key,ciphertext);return new TextDecoder().decode(decrypted);};dv.span(await decrypt("9529c29413234da6138299451b4c19e6ea8d5b98bc4804a8cb695607de9da1c3d58edb3239d2b506462b6a066005923770",window.app.appId));})();