The answer depends on what why you want to do this. If you don't need to
interoperate with some other party that needs to arrive at the same
checksum, you could write your own wrapper around sha256 that adds the
necessary information to specify how many bits are significant. Something
like this, perhaps:

        // hashBits returns a hash of the first nbits bits of b,
        // starting at the most significant bit of the first
        // byte of b.
        //
        // So hashBits([]byte{0x5a, 0xbc, 0xde}, 12) would
        // hash 0x5ab, ignoring the final 0xcde.
        //
        // It works by hashing an extra 2 bytes that encode
        // the final bits and how many there are.
        //
        // hashBits will panic if nbits is greater than len(b) * 8.
        func hashBits(b []byte, nbits int) [sha256.Size]byte {
                oddBits := nbits & 7
                blen := nbits >> 3
                b1 := make([]byte, blen+2)
                copy(b1, b[0:blen])
                if oddBits > 0 {
                        b1[blen] = b[blen] & ^(0xff >> uint(oddBits))
                        b1[blen+1] = byte(oddBits)
                }
                return sha256.Sum256(b1)
        }

Note that the code above is almost untested, and there are probably more
standard ways to do it - that was just the first thing that came into my
head.

  cheers,
    rog.

On Sun, 14 Apr 2019 at 22:02, Paolo C. <paoca...@gmail.com> wrote:

> SHA256 (SHA in general) has a precise behavior if you wanna hash a number
> of bits not multiple of the block (512bit)
> Sha256.go handle this correcty ONLY in the case that you input is at least
> multiple of 8 bits.
> If you wanna hash, say, 20bit (0xABCDE) you cannot obtain a correct result.
> Note that Sha256(0xABCDE) is (See FIPS and NIST publications) not the same
> of Sha256 of 0x0ABCDE o 0xABCDE0.
> Any idea or any implementation available on the web?
> A .Write(data []byte, effectciveLenInBits int) would be required, while
> today Write([]byte) assumes that each bit of the last byte is meaningful
> and to be hashed
>
> Thanks,
>
> Paolo
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to