哈希加密伪代码

// 定义 SHA256 压缩函数
function sha256_compress(data_block) {
    for (let i=16; i<64; i++) {
        w[i]=(ROTR(17,w[i-2])^ROTR(19,w[i-2])^(w[i-2]>>>10))+w[i-7]+(ROTR(7,w[i-15])^ROTR(18,w[i-15])^(w[i-15]>>>3))+w[i-16];
    }
    let [a,b,c,d,e,f,g,h]=STATE;
    for (let i=0; i<64; i++) {
        const S1=ROTR(6, e)^ROTR(11, e)^ROTR(25, e);
        const ch=(e&f)^((~e)&g);
        const temp1=h+S1+ch+K[i]+w[i];
        const S0=ROTR(2, a)^ROTR(13, a)^ROTR(22, a);
        const maj=(a&b)^(a&c)^(b&c);
        const temp2=S0+maj;
        h=g; g=f; f=e; e=d+temp1; d=c; c=b; b=a; a=temp1+temp2;
    }
    STATE[0]+=a; STATE[1]+=b; STATE[2]+=c; STATE[3]+=d;
    STATE[4]+=e; STATE[5]+=f; STATE[6]+=g; STATE[7]+=h;
}

// 定义 SHA256 哈希函数
function sha256(input_data) {
    let padded_data=pad(input_data), data_blocks=split_to_blocks(padded_data, 512);
    let STATE=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];
    for (let i=0; i<data_blocks.length; i++) sha256_compress(data_blocks[i]);
    return STATE.map(e=>('00000000'+(e>>>0).toString(16)).slice(-8)).join('');
}
posted @ 2023-04-19 18:28  斯文小扬  阅读(40)  评论(0编辑  收藏  举报