主要使用了 ed25519 庫
加解密和驗證代碼
// Common.js and ECMAScript Modules (ESM)
import * as ed from '@noble/ed25519';
// If you're using single file, use global variable instead: `window.nobleEd25519`
const verifyEd = async function (prikey, pubkey) {
console.log("你輸入的私鑰是:" + prikey)
console.log("環境變量中的公鑰是:" + pubkey)
// ====================
// 新私鑰開始
// ====================
// const newPrivateKey = ed.utils.randomPrivateKey();
// const privateKeyStr = Buffer.from(newPrivateKey).toString('base64');
// console.log("new privateKey=>", privateKeyStr)
// ====================
// 新私鑰結束
// ====================
const privateKeyStr = prikey
const privateKey = Buffer.from(privateKeyStr, 'base64');
// console.log("parsed privateKey=>", privateKey)
// ====================
// 新公鑰開始
// ====================
// const newPublicKey = await ed.getPublicKey(privateKey);
// const publicKeyStr = Buffer.from(newPublicKey).toString('base64');
// console.log("new publicKey=>", publicKeyStr)
// ====================
// 新公鑰結束
// ====================
const publicKeyStr = pubkey
const publicKey = Buffer.from(publicKeyStr, 'base64');
// console.log("parsed publicKey=>", publicKey)
try {
const valiPass = "123456";
const message = Uint8Array.from(valiPass, x => x.charCodeAt(0))
// const messageStr = Buffer.from(message).toString('base64');
// console.log("校驗密碼:", valiPass)
const signature = await ed.sign(message, privateKey);
const isValid = await ed.verify(signature, message, publicKey);
// console.log("驗證結果:", isValid ? "有效" : "無效")
return isValid;
} catch (e) {
console.warn("校驗失敗,請檢查密碼", e)
return false;
}
}
const privateKeyStr = "prikey";
const publicKeyStr = "pubkey"
const valiResult = verifyEd(privateKeyStr, publicKeyStr)
valiResult.then(function(item){
console.log("item=>", item)
})