...
This commit is contained in:
114
www/index.html
Normal file
114
www/index.html
Normal file
@@ -0,0 +1,114 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Rust WebAssembly Crypto Example</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.container {
|
||||
border: 1px solid #ddd;
|
||||
padding: 20px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
button {
|
||||
background-color: #4CAF50;
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
font-size: 16px;
|
||||
margin: 4px 2px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
input, textarea {
|
||||
padding: 8px;
|
||||
margin: 5px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
width: 80%;
|
||||
}
|
||||
.result {
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
background-color: #f5f5f5;
|
||||
border-radius: 4px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.key-display {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.note {
|
||||
font-style: italic;
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Rust WebAssembly Crypto Example</h1>
|
||||
|
||||
<div class="container">
|
||||
<h2>Keypair Generation</h2>
|
||||
<div>
|
||||
<button id="keypair-button">Generate Keypair</button>
|
||||
</div>
|
||||
<div class="result" id="keypair-result">Result will appear here</div>
|
||||
<div class="key-display" id="pubkey-display"></div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<h2>Message Signing</h2>
|
||||
<div>
|
||||
<textarea id="sign-message" placeholder="Enter message to sign" rows="3">Hello, this is a test message to sign</textarea>
|
||||
<button id="sign-button">Sign Message</button>
|
||||
</div>
|
||||
<div class="result" id="signature-result">Signature will appear here</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<h2>Signature Verification</h2>
|
||||
<div>
|
||||
<textarea id="verify-message" placeholder="Enter message to verify" rows="3"></textarea>
|
||||
<textarea id="verify-signature" placeholder="Enter signature to verify" rows="3"></textarea>
|
||||
<button id="verify-button">Verify Signature</button>
|
||||
</div>
|
||||
<div class="result" id="verify-result">Verification result will appear here</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<h2>Symmetric Encryption</h2>
|
||||
<div>
|
||||
<textarea id="encrypt-message" placeholder="Enter message to encrypt" rows="3">This is a secret message that will be encrypted</textarea>
|
||||
<button id="encrypt-button">Generate Key & Encrypt</button>
|
||||
</div>
|
||||
<div class="key-display" id="sym-key-display"></div>
|
||||
<div class="note" id="nonce-display">Note: Nonce is handled internally</div>
|
||||
<div class="result" id="encrypt-result">Encrypted data will appear here</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<h2>Symmetric Decryption</h2>
|
||||
<div>
|
||||
<input type="text" id="decrypt-key" placeholder="Enter key (hex)" />
|
||||
<div class="note">Note: Nonce is now extracted automatically from the ciphertext</div>
|
||||
<textarea id="decrypt-ciphertext" placeholder="Enter ciphertext (hex)" rows="3"></textarea>
|
||||
<button id="decrypt-button">Decrypt</button>
|
||||
</div>
|
||||
<div class="result" id="decrypt-result">Decrypted data will appear here</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="./js/index.js"></script>
|
||||
</body>
|
||||
</html>
|
146
www/js/index.js
Normal file
146
www/js/index.js
Normal file
@@ -0,0 +1,146 @@
|
||||
// Import our WebAssembly module
|
||||
import init, {
|
||||
keypair_new,
|
||||
keypair_pub_key,
|
||||
keypair_sign,
|
||||
keypair_verify,
|
||||
generate_symmetric_key,
|
||||
encrypt_symmetric,
|
||||
decrypt_symmetric
|
||||
} from '../../pkg/webassembly.js';
|
||||
|
||||
// Helper function to convert ArrayBuffer to hex string
|
||||
function bufferToHex(buffer) {
|
||||
return Array.from(new Uint8Array(buffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
// Helper function to convert hex string to Uint8Array
|
||||
function hexToBuffer(hex) {
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < hex.length; i += 2) {
|
||||
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize the WebAssembly module
|
||||
await init();
|
||||
|
||||
console.log('WebAssembly crypto module initialized!');
|
||||
|
||||
// Set up the keypair generation example
|
||||
document.getElementById('keypair-button').addEventListener('click', () => {
|
||||
try {
|
||||
const result = keypair_new();
|
||||
if (result === 0) {
|
||||
document.getElementById('keypair-result').textContent = 'Keypair generated successfully!';
|
||||
|
||||
// Get and display the public key
|
||||
try {
|
||||
const pubKey = keypair_pub_key();
|
||||
document.getElementById('pubkey-display').textContent = `Public Key: ${bufferToHex(pubKey)}`;
|
||||
} catch (e) {
|
||||
document.getElementById('pubkey-display').textContent = `Error getting public key: ${e}`;
|
||||
}
|
||||
} else {
|
||||
document.getElementById('keypair-result').textContent = `Error generating keypair: ${result}`;
|
||||
}
|
||||
} catch (e) {
|
||||
document.getElementById('keypair-result').textContent = `Error: ${e}`;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up the signing example
|
||||
document.getElementById('sign-button').addEventListener('click', () => {
|
||||
const message = document.getElementById('sign-message').value;
|
||||
const messageBytes = new TextEncoder().encode(message);
|
||||
|
||||
try {
|
||||
const signature = keypair_sign(messageBytes);
|
||||
const signatureHex = bufferToHex(signature);
|
||||
document.getElementById('signature-result').textContent = `Signature: ${signatureHex}`;
|
||||
|
||||
// Store the signature for verification
|
||||
document.getElementById('verify-signature').value = signatureHex;
|
||||
document.getElementById('verify-message').value = message;
|
||||
} catch (e) {
|
||||
document.getElementById('signature-result').textContent = `Error signing: ${e}`;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up the verification example
|
||||
document.getElementById('verify-button').addEventListener('click', () => {
|
||||
const message = document.getElementById('verify-message').value;
|
||||
const messageBytes = new TextEncoder().encode(message);
|
||||
const signatureHex = document.getElementById('verify-signature').value;
|
||||
const signatureBytes = hexToBuffer(signatureHex);
|
||||
|
||||
try {
|
||||
const isValid = keypair_verify(messageBytes, signatureBytes);
|
||||
document.getElementById('verify-result').textContent =
|
||||
isValid ? 'Signature is valid!' : 'Signature is NOT valid!';
|
||||
} catch (e) {
|
||||
document.getElementById('verify-result').textContent = `Error verifying: ${e}`;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up the symmetric encryption example
|
||||
document.getElementById('encrypt-button').addEventListener('click', () => {
|
||||
try {
|
||||
// Generate key
|
||||
const key = generate_symmetric_key();
|
||||
|
||||
// Display key
|
||||
const keyHex = bufferToHex(key);
|
||||
document.getElementById('sym-key-display').textContent = `Key: ${keyHex}`;
|
||||
|
||||
// Store for decryption
|
||||
document.getElementById('decrypt-key').value = keyHex;
|
||||
|
||||
// Encrypt the message
|
||||
const message = document.getElementById('encrypt-message').value;
|
||||
const messageBytes = new TextEncoder().encode(message);
|
||||
|
||||
try {
|
||||
// New API: encrypt_symmetric only takes key and message
|
||||
const ciphertext = encrypt_symmetric(key, messageBytes);
|
||||
const ciphertextHex = bufferToHex(ciphertext);
|
||||
document.getElementById('encrypt-result').textContent = `Ciphertext: ${ciphertextHex}`;
|
||||
|
||||
// Store for decryption
|
||||
document.getElementById('decrypt-ciphertext').value = ciphertextHex;
|
||||
} catch (e) {
|
||||
document.getElementById('encrypt-result').textContent = `Error encrypting: ${e}`;
|
||||
}
|
||||
} catch (e) {
|
||||
document.getElementById('encrypt-result').textContent = `Error: ${e}`;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up the symmetric decryption example
|
||||
document.getElementById('decrypt-button').addEventListener('click', () => {
|
||||
try {
|
||||
const keyHex = document.getElementById('decrypt-key').value;
|
||||
const ciphertextHex = document.getElementById('decrypt-ciphertext').value;
|
||||
|
||||
const key = hexToBuffer(keyHex);
|
||||
const ciphertext = hexToBuffer(ciphertextHex);
|
||||
|
||||
try {
|
||||
// New API: decrypt_symmetric only takes key and ciphertext
|
||||
const plaintext = decrypt_symmetric(key, ciphertext);
|
||||
const decodedText = new TextDecoder().decode(plaintext);
|
||||
document.getElementById('decrypt-result').textContent = `Decrypted: ${decodedText}`;
|
||||
} catch (e) {
|
||||
document.getElementById('decrypt-result').textContent = `Error decrypting: ${e}`;
|
||||
}
|
||||
} catch (e) {
|
||||
document.getElementById('decrypt-result').textContent = `Error: ${e}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
82
www/server.js
Normal file
82
www/server.js
Normal file
@@ -0,0 +1,82 @@
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = 8080;
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html',
|
||||
'.js': 'text/javascript',
|
||||
'.css': 'text/css',
|
||||
'.json': 'application/json',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpg',
|
||||
'.gif': 'image/gif',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.txt': 'text/plain',
|
||||
};
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
console.log(`${req.method} ${req.url}`);
|
||||
|
||||
// Handle CORS preflight requests
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.writeHead(204, {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type',
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize URL path
|
||||
let filePath = req.url;
|
||||
if (filePath === '/' || filePath === '') {
|
||||
filePath = '/index.html';
|
||||
}
|
||||
|
||||
// Determine the file path
|
||||
const resolvedPath = path.resolve(
|
||||
__dirname,
|
||||
filePath.startsWith('/pkg/')
|
||||
? `..${filePath}` // For files in the pkg directory (one level up)
|
||||
: `.${filePath}` // For files in the www directory
|
||||
);
|
||||
|
||||
// Get the file extension
|
||||
const extname = path.extname(resolvedPath);
|
||||
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
|
||||
|
||||
// Read and serve the file
|
||||
fs.readFile(resolvedPath, (err, data) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
console.error(`File not found: ${resolvedPath}`);
|
||||
res.writeHead(404);
|
||||
res.end('File not found');
|
||||
} else {
|
||||
console.error(`Server error: ${err}`);
|
||||
res.writeHead(500);
|
||||
res.end(`Server Error: ${err.code}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Set CORS headers for all responses
|
||||
res.writeHead(200, {
|
||||
'Content-Type': contentType,
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cross-Origin-Embedder-Policy': 'require-corp',
|
||||
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||
});
|
||||
res.end(data);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Server running at http://localhost:${PORT}/`);
|
||||
console.log(`Press Ctrl+C to stop the server`);
|
||||
});
|
Reference in New Issue
Block a user