请在不使用外部库的情况下使用js实现带盐MD5算法
时间: 2024-10-27 21:02:36 浏览: 9
md5加密,原生js使用md5加密
在JavaScript中,如果你不想依赖外部库来实现MD5哈希函数(通常情况下会推荐使用像`crypto-js`这样的库),你可以手动编写一个简单的MD5计算函数,虽然这可能会涉及到位操作,对于非专业人士来说可能有些复杂。下面是一个基本的JavaScript版“小端”MD5算法的实现,但请注意它并不如专业库那样完整和高效:
```javascript
function toHex(num) {
var str = num.toString(16);
return (str.length < 2) ? '0' + str : str;
}
function addPoly(a, b) {
// 这里省略了详细的位运算步骤,简化为加法运算
let sum = a + b;
if (sum > 0xffffffff) {
sum -= 0x100000000;
}
return sum;
}
function f(x, y, z) {
return (y & z) | ((~y) & x);
}
function g(x, y, z) {
return x ^ y ^ z;
}
function md5(input, salt) {
let length = input + salt.length;
let i = length << 2;
let A = 0x67452301;
let B = 0xefcdab89;
let C = 0x98badcfe;
let D = 0x10325476;
let messageWords = Array.from(new TextEncoder().encode(input)).map((b) => b).concat(salt.split('').map((ch) => ch.charCodeAt(0)));
while (i > 0) {
let offset = i >> 2;
let W = [];
for (let j = 0; j < 16; j++) {
W[j] = messageWords[offset + j];
}
let A1 = A, B1 = B, C1 = C, D1 = D;
for (let j = 0; j < 64; j++) {
let S1 = j <= 15 ? f(A1, B1, C1) : g(A1, B1, C1);
let K = 0x5a827999 + (j * 0x055a09ce);
let t = addPoly(addPoly(S1, K), W[j]);
if (j < 16) {
D1 = addPoly(t, D1);
} else if (j < 32) {
C1 = addPoly(t, C1);
} else if (j < 48) {
B1 = addPoly(t, B1);
} else {
A1 = addPoly(t, A1);
}
}
A = addPoly(A1, A);
B = addPoly(B1, B);
C = addPoly(C1, C);
D = addPoly(D1, D);
i -= 16;
}
return (
toHex(A >>> 0) +
toHex(B >>> 0) +
toHex(C >>> 0) +
toHex(D >>> 0)
);
}
// 示例用法
let input = "Hello";
let salt = "World!";
let hashed = md5(input, salt);
console.log(hashed); // 输出MD5哈希结果
阅读全文