Re: 正在研究js-md5
发表于 : 2025年 7月 22日 23:36
gemini, SJCL:
代码: 全选
<!DOCTYPE html>
<html>
<head>
<title>SJCL PBKDF2 範例</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sjcl/1.0.3/sjcl.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="text"], input[type="password"] { width: 300px; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #0056b3; }
.output-container { margin-top: 20px; padding: 15px; border: 1px solid #e0e0e0; background-color: #f9f9f9; border-radius: 5px; }
pre { white-space: pre-wrap; word-break: break-all; background-color: #eee; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<h1>SJCL PBKDF2 密碼派生</h1>
<p>輸入一個密碼,SJCL 將使用 PBKDF2 算法從中派生出一個金鑰(密文)。</p>
<div>
<label for="password">密碼:</label>
<input type="password" id="password" value="MyStrongPassword123!" />
</div>
<div>
<label for="salt">鹽 (Salt):</label>
<input type="text" id="salt" value="some_random_salt_string" />
</div>
<div>
<label for="iterations">迭代次數 (Iterations):</label>
<input type="number" id="iterations" value="10000" min="1000" />
</div>
<button onclick="deriveKey()">派生金鑰</button>
<div class="output-container">
<h2>結果:</h2>
<p>派生出的金鑰 (十六進制表示):</p>
<pre id="derivedKeyOutput"></pre>
<p>錯誤訊息:</p>
<pre id="errorOutput" style="color: red;"></pre>
</div>
<script>
function deriveKey() {
const password = document.getElementById('password').value;
const salt = document.getElementById('salt').value;
const iterations = parseInt(document.getElementById('iterations').value, 10);
const keyOutput = document.getElementById('derivedKeyOutput');
const errorOutput = document.getElementById('errorOutput');
keyOutput.textContent = '';
errorOutput.textContent = '';
if (!password || !salt || isNaN(iterations) || iterations < 1) {
errorOutput.textContent = '請輸入有效的密碼、鹽和迭代次數。';
return;
}
try {
// 將密碼和鹽轉換為 SJCL 位陣列格式
const passwordBits = sjcl.codec.utf8String.toBits(password);
const saltBits = sjcl.codec.utf8String.toBits(salt);
// 使用 PBKDF2 派生金鑰
// sjcl.misc.pbkdf2(密碼, 鹽, 迭代次數, 輸出金鑰的位元數 (可選), 雜湊函數 (可選))
// 預設雜湊函數為 SHA-256
const derivedKeyBits = sjcl.misc.pbkdf2(passwordBits, saltBits, iterations, 256); // 256 位元輸出金鑰
// 將派生出的金鑰從位陣列轉換為十六進制字串以便顯示
const derivedKeyHex = sjcl.codec.hex.fromBits(derivedKeyBits);
keyOutput.textContent = derivedKeyHex;
} catch (e) {
errorOutput.textContent = '金鑰派生失敗: ' + e.message;
console.error('PBKDF2 Error:', e);
}
}
</script>
</body>
</html>