纯JavaScript实现字母数字哈希:加密与可恢复非加密哈希需求
Got it, let's tackle your requirements with practical, client-side JavaScript implementations. Below are two solutions that fit exactly what you're asking for:
1. Cryptographic Hash Implementation
For a secure cryptographic hash, we'll use the browser's native Web Crypto API (widely supported in modern browsers). This produces a fixed-length, irreversible hash perfect for verifying data integrity.
async function generateCryptoHash(inputString) { // Convert input string to a binary buffer const encoder = new TextEncoder(); const data = encoder.encode(inputString); // Generate SHA-256 hash (a trusted cryptographic standard) const hashBuffer = await crypto.subtle.digest('SHA-256', data); // Convert buffer to an alphanumeric string (using base64url to avoid special characters) const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashBase64 = btoa(String.fromCharCode(...hashArray)) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); // Return a trimmed alphanumeric segment (adjust length as needed) return hashBase64.slice(0, 16); } // Usage example generateCryptoHash('YourSecretString') .then(hash => console.log('Cryptographic Hash:', hash)) .catch(err => console.error('Hash generation failed:', err));
Quick Notes:
- Uses SHA-256, a widely accepted secure hash function.
- Output is strictly alphanumeric (we stripped padding and replaced special base64 chars).
- Irreversible: You can't convert this hash back to the original string—this is intentional for security.
2. Reversible Non-Cryptographic Alphanumeric Hash (~10 characters)
This implementation skips the Crypto API and Promises entirely, produces a short (≈10 char) alphanumeric string, and can be reversed to recover the original input. Great for non-security use cases like obfuscated identifiers.
// Define our alphanumeric character set (62 unique characters) const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const CHARSET_LENGTH = CHARSET.length; // Encode string to a short alphanumeric hash function encodeReversibleHash(inputString) { let encoded = ''; // Convert each character to its Unicode code point, then map to two chars from our set for (const char of inputString) { const code = char.charCodeAt(0); // Split code into two indices (62² = 3844, covers most common Unicode characters) const firstIndex = Math.floor(code / CHARSET_LENGTH); const secondIndex = code % CHARSET_LENGTH; encoded += CHARSET[firstIndex] + CHARSET[secondIndex]; } // Trim to ~10 characters (perfect for input strings up to 5 characters) return encoded.slice(0, 10); } // Decode hash back to the original string function decodeReversibleHash(encodedHash) { let decoded = ''; // Process two characters at a time to reconstruct the original Unicode code points for (let i = 0; i < encodedHash.length; i += 2) { const firstChar = encodedHash[i]; const secondChar = encodedHash[i + 1]; if (!secondChar) break; // Handle odd-length hashes gracefully const firstIndex = CHARSET.indexOf(firstChar); const secondIndex = CHARSET.indexOf(secondChar); if (firstIndex === -1 || secondIndex === -1) { throw new Error('Invalid character in hash'); } const originalCode = (firstIndex * CHARSET_LENGTH) + secondIndex; decoded += String.fromCharCode(originalCode); } return decoded; } // Usage example const originalText = 'Hello123'; const hash = encodeReversibleHash(originalText); const restoredText = decodeReversibleHash(hash); console.log('Original:', originalText); console.log('Reversible Hash:', hash); // 10 characters for 5-char input console.log('Restored:', restoredText); // Matches original
Quick Notes:
- No dependencies: Pure vanilla JavaScript, works in all browsers.
- Fully reversible: The decode function recovers the exact original string (as long as the hash wasn't truncated beyond what's needed for the input).
- Length control: For input strings up to 5 characters, the hash is exactly 10 characters. Adjust the slice length if you need longer/shorter outputs.
- Non-cryptographic: Not secure for sensitive data—use only for obfuscation or non-security identifiers.
内容的提问来源于stack exchange,提问作者Yash Sampat
相关产品推荐
相关产品推荐

