// Copyright (c) 2019 Alexander Medvednikov. All rights reserved. // Use of this source code is governed by an MIT license // that can be found in the LICENSE file. // Package sha256 implements the SHA224 and SHA256 hash algorithms as defined // in FIPS 180-4. // Adaped from https://github.com/golang/go/tree/master/src/crypto/sha256 module sha256 import math import encoding.binary const ( // The size of a SHA256 checksum in bytes. Size = 32 // The size of a SHA224 checksum in bytes. Size224 = 28 // The blocksize of SHA256 and SHA224 in bytes. BlockSize = 64 ) const ( Chunk = 64 Init0 = 0x6A09E667 Init1 = 0xBB67AE85 Init2 = 0x3C6EF372 Init3 = 0xA54FF53A Init4 = 0x510E527F Init5 = 0x9B05688C Init6 = 0x1F83D9AB Init7 = 0x5BE0CD19 Init0_224 = 0xC1059ED8 Init1_224 = 0x367CD507 Init2_224 = 0x3070DD17 Init3_224 = 0xF70E5939 Init4_224 = 0xFFC00B31 Init5_224 = 0x68581511 Init6_224 = 0x64F98FA7 Init7_224 = 0xBEFA4FA4 ) // digest represents the partial evaluation of a checksum. struct Digest { mut: h []u32 x []byte nx int len u64 is224 bool // mark if this digest is SHA-224 } fn (d &Digest) reset() { d.h = [u32(0); 8] d.x = [byte(0); Chunk] if !d.is224 { d.h[0] = u32(Init0) d.h[1] = u32(Init1) d.h[2] = u32(Init2) d.h[3] = u32(Init3) d.h[4] = u32(Init4) d.h[5] = u32(Init5) d.h[6] = u32(Init6) d.h[7] = u32(Init7) } else { d.h[0] = u32(Init0_224) d.h[1] = u32(Init1_224) d.h[2] = u32(Init2_224) d.h[3] = u32(Init3_224) d.h[4] = u32(Init4_224) d.h[5] = u32(Init5_224) d.h[6] = u32(Init6_224) d.h[7] = u32(Init7_224) } d.nx = 0 d.len = u64(0) } // new returns a new Digest (implementing hash.Hash) computing the SHA256 checksum. pub fn new() *Digest { mut d := &Digest{} d.reset() return d } // new224 returns a new Digest (implementing hash.Hash) computing the SHA224 checksum. pub fn new224() *Digest { mut d := &Digest{} d.is224 = true d.reset() return d } fn (d mut Digest) write(p []byte) ?int { nn := p.len d.len += u64(nn) if d.nx > 0 { n := int(math.min(f64(d.x.len), f64(p.len))) for i:=0; i= p.len { p = []byte } else { p = p.right(n) } } if p.len >= Chunk { n := p.len &~ (Chunk - 1) block(d, p.left(n)) if n >= p.len { p = []byte } else { p = p.right(n) } } if p.len > 0 { d.nx = int(math.min(f64(d.x.len), f64(p.len))) for i:=0; i