Esempio n. 1
0
func (sc *streamCipher) Partial(dst, src, key []byte) {

	n := ints.Max(len(dst), len(src), len(key)) // bytes to process

	// create our Stream cipher if needed
	if sc.s == nil {
		if sc.k == nil {
			sc.k = make([]byte, sc.hashLen)
		}
		sc.s = sc.newStream(sc.k[:sc.keyLen])
	}

	// squeeze cryptographic output
	ndst := ints.Min(n, len(dst))    // # bytes to write to dst
	nsrc := ints.Min(ndst, len(src)) // # src bytes available
	sc.s.XORKeyStream(dst[:nsrc], src[:nsrc])
	if n > nsrc {
		buf := make([]byte, n-nsrc)
		sc.s.XORKeyStream(buf, buf)
		copy(dst[nsrc:], buf)
	}

	// absorb cryptographic input (which may overlap with dst)
	if key != nil {
		nkey := ints.Min(n, len(key)) // # key bytes available
		sc.h.Write(key[:nkey])
		if n > nkey {
			buf := make([]byte, n-nkey)
			sc.h.Write(buf)
		}
	}
}
Esempio n. 2
0
func (sc *spongeCipher) Partial(dst, src, key []byte) {
	sp := sc.sponge
	rate := sc.rate
	buf := sc.buf
	pos := sc.pos
	rem := ints.Max(len(dst), len(src), len(key)) // bytes to process
	for rem > 0 {
		if pos == rate { // process next block if needed
			sp.Transform(buf, buf[:rate])
			pos = 0
		}
		n := ints.Min(rem, rate-pos) // bytes to process in this block

		// squeeze cryptographic output
		ndst := ints.Min(n, len(dst))    // # bytes to write to dst
		nsrc := ints.Min(ndst, len(src)) // # src bytes available
		for i := 0; i < nsrc; i++ {      // XOR-encrypt from src to dst
			dst[i] = src[i] ^ buf[pos+i]
		}
		copy(dst[nsrc:ndst], buf[pos+nsrc:]) // "XOR" with 0 bytes
		dst = dst[ndst:]
		src = src[nsrc:]

		// absorb cryptographic input (which may overlap with dst)
		nkey := ints.Min(n, len(key)) // # key bytes available
		copy(buf[pos:], key[:nkey])
		for i := nkey; i < n; i++ { // missing key bytes implicitly 0
			buf[pos+i] = 0
		}
		key = key[nkey:]

		pos += n
		rem -= n
	}

	sc.pos = pos
	//println("Decrypted",more,"\n" + hex.Dump(osrc) + "->\n" + hex.Dump(odst))
}