如何找到字节字符串的4字节前缀,当在javascript中以十六进制编码时



嗨,我的一位培训师让我解决这个与哈希有关的神秘问题,这个问题非常罕见,以至于我找不到任何好的来源来解决和学习它背后的逻辑。

Given a string of bytes, which when encoded in hexadecimal notation look like this:

f064b8b61422a3456cb273a474a1fb0cabb04200a6a82a9426bd01f56c97fbf8c4ef58634fd5cf21af29e7db3406de4f886fe71408696789f853af9932a84b79

Find a 4-byte prefix so that, a SHA256 hash of the prefix combined with the original string of bytes, has two last bytes as 0xca, 0xfe.

我尝试了一次。我用的是弦乐,我相信这不是最有效的。但让我们看看它是否有效。

async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}

function hexToString(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes.map(function(byte) {
return String.fromCharCode(byte)
}).join("")
// return bytes;
}
function hex32(val) {
val &= 0xFFFFFFFF;
var hex = val.toString(16).toUpperCase();
return ("00000000" + hex).slice(-8);
}
var str = "f064b8b61422a3456cb273a474a1fb0cabb04200a6a82a9426bd01f56c97fbf8c4ef58634fd5cf21af29e7db3406de4f886fe71408696789f853af9932a84b79";

var original = hexToString(str);
var found = false;

async function search() {
for (var i = 0; i < 0xffffffff; i++) {
var prefix = hexToString(hex32(i))
await sha256(prefix + original).then(function(result) {
// console.log(result.slice(-4))
if (result.slice(-4) == 'cafe') {
console.log(`found a prefix: "${prefix}"`);
found = true;
}
});
if (found) {
break;
}
}
}
search();

相关内容

最新更新