func (m *clientHelloMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

	length := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods)
	x := make([]byte, 4+length)
	x[0] = typeClientHello
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)
	x[4] = m.major
	x[5] = m.minor
	bytes.Copy(x[6:38], m.random)
	x[38] = uint8(len(m.sessionId))
	bytes.Copy(x[39:39+len(m.sessionId)], m.sessionId)
	y := x[39+len(m.sessionId) : len(x)]
	y[0] = uint8(len(m.cipherSuites) >> 7)
	y[1] = uint8(len(m.cipherSuites) << 1)
	for i, suite := range m.cipherSuites {
		y[2+i*2] = uint8(suite >> 8)
		y[3+i*2] = uint8(suite)
	}
	z := y[2+len(m.cipherSuites)*2 : len(y)]
	z[0] = uint8(len(m.compressionMethods))
	bytes.Copy(z[1:len(z)], m.compressionMethods)
	m.raw = x

	return x
}
Esempio n. 2
0
func main() {
	in = bufio.NewReader(os.Stdin)
	buf := make([]byte, 100*1024)
	top := 0
	for {
		line, err := in.ReadSlice('\n')
		if err != nil {
			break
		}
		if line[0] == '>' {
			if top > 0 {
				output(buf[0:top])
				top = 0
			}
			os.Stdout.Write(line)
			continue
		}
		line = line[0 : len(line)-1] // drop newline
		if top+len(line) > len(buf) {
			nbuf := make([]byte, 2*len(buf)+1024*(100+len(line)))
			bytes.Copy(nbuf, buf[0:top])
			buf = nbuf
		}
		bytes.Copy(buf[top:len(buf)], line)
		top += len(line)
	}
	output(buf[0:top])
}
Esempio n. 3
0
File: rsa.go Progetto: 8l/go-learn
// EncryptOAEP encrypts the given message with RSA-OAEP.
// The message must be no longer than the length of the public modulus less
// twice the hash length plus 2.
func EncryptOAEP(hash hash.Hash, rand io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) {
	hash.Reset()
	k := (pub.N.Len() + 7) / 8
	if len(msg) > k-2*hash.Size()-2 {
		err = MessageTooLongError{}
		return
	}

	hash.Write(label)
	lHash := hash.Sum()
	hash.Reset()

	em := make([]byte, k)
	seed := em[1 : 1+hash.Size()]
	db := em[1+hash.Size() : len(em)]

	bytes.Copy(db[0:hash.Size()], lHash)
	db[len(db)-len(msg)-1] = 1
	bytes.Copy(db[len(db)-len(msg):len(db)], msg)

	_, err = io.ReadFull(rand, seed)
	if err != nil {
		return
	}

	mgf1XOR(db, hash, seed)
	mgf1XOR(seed, hash, db)

	m := new(big.Int)
	m.SetBytes(em)
	c := encrypt(new(big.Int), pub, m)
	out = c.Bytes()
	return
}
Esempio n. 4
0
// finishedSum calculates the contents of the verify_data member of a Finished
// message given the MD5 and SHA1 hashes of a set of handshake messages.
func finishedSum(md5, sha1, label, masterSecret []byte) []byte {
	seed := make([]byte, len(md5)+len(sha1))
	bytes.Copy(seed, md5)
	bytes.Copy(seed[len(md5):len(seed)], sha1)
	out := make([]byte, finishedVerifyLength)
	pRF11(out, masterSecret, label, seed)
	return out
}
Esempio n. 5
0
// WriteHeader writes hdr and prepares to accept the file's contents.
// WriteHeader calls Flush if it is not the first header.
func (tw *Writer) WriteHeader(hdr *Header) os.Error {
	if tw.err == nil {
		tw.Flush()
	}
	if tw.err != nil {
		return tw.err
	}

	tw.nb = int64(hdr.Size)
	tw.pad = -tw.nb & (blockSize - 1) // blockSize is a power of two

	header := make([]byte, blockSize)
	s := slicer(header)

	// TODO(dsymonds): handle names longer than 100 chars
	bytes.Copy(s.next(100), strings.Bytes(hdr.Name))

	tw.octal(s.next(8), hdr.Mode)                       // 100:108
	tw.numeric(s.next(8), hdr.Uid)                      // 108:116
	tw.numeric(s.next(8), hdr.Gid)                      // 116:124
	tw.numeric(s.next(12), hdr.Size)                    // 124:136
	tw.numeric(s.next(12), hdr.Mtime)                   // 136:148
	s.next(8)                                           // chksum (148:156)
	s.next(1)[0] = hdr.Typeflag                         // 156:157
	s.next(100)                                         // linkname (157:257)
	bytes.Copy(s.next(8), strings.Bytes("ustar\x0000")) // 257:265
	tw.cString(s.next(32), hdr.Uname)                   // 265:297
	tw.cString(s.next(32), hdr.Gname)                   // 297:329
	tw.numeric(s.next(8), hdr.Devmajor)                 // 329:337
	tw.numeric(s.next(8), hdr.Devminor)                 // 337:345

	// Use the GNU magic instead of POSIX magic if we used any GNU extensions.
	if tw.usedBinary {
		bytes.Copy(header[257:265], strings.Bytes("ustar  \x00"))
	}

	// The chksum field is terminated by a NUL and a space.
	// This is different from the other octal fields.
	chksum, _ := checksum(header)
	tw.octal(header[148:155], chksum)
	header[155] = ' '

	if tw.err != nil {
		// problem with header; probably integer too big for a field.
		return tw.err
	}

	_, tw.err = tw.w.Write(header)

	return tw.err
}
func (p *recordProcessor) processHandshakeRecord(data []byte) {
	if p.handshakeBuf == nil {
		p.handshakeBuf = data
	} else {
		if len(p.handshakeBuf) > maxHandshakeMsg {
			p.error(alertInternalError)
			return
		}
		newBuf := make([]byte, len(p.handshakeBuf)+len(data))
		bytes.Copy(newBuf, p.handshakeBuf)
		bytes.Copy(newBuf[len(p.handshakeBuf):len(newBuf)], data)
		p.handshakeBuf = newBuf
	}

	for len(p.handshakeBuf) >= 4 {
		handshakeLen := int(p.handshakeBuf[1])<<16 |
			int(p.handshakeBuf[2])<<8 |
			int(p.handshakeBuf[3])
		if handshakeLen+4 > len(p.handshakeBuf) {
			break
		}

		bytes := p.handshakeBuf[0 : handshakeLen+4]
		p.handshakeBuf = p.handshakeBuf[handshakeLen+4 : len(p.handshakeBuf)]
		if bytes[0] == typeFinished {
			// Special case because Finished is synchronous: the
			// handshake handler has to tell us if it's ok to start
			// forwarding application data.
			m := new(finishedMsg)
			if !m.unmarshal(bytes) {
				p.error(alertUnexpectedMessage)
			}
			p.handshakeChan <- m
			var ok bool
			p.connState, ok = (<-p.controlChan).(ConnectionState)
			if !ok || p.connState.Error != 0 {
				p.shutdown = true
				return
			}
		} else {
			msg, ok := parseHandshakeMsg(bytes)
			if !ok {
				p.error(alertUnexpectedMessage)
				return
			}
			p.handshakeChan <- msg
		}
	}
}
Esempio n. 7
0
File: fasta.go Progetto: 8l/go-learn
// RepeatFasta prints the characters of the byte slice s. When it
// reaches the end of the slice, it goes back to the beginning.
// It stops after generating count characters.
// After each WIDTH characters it prints a newline.
// It assumes that WIDTH <= len(s) + 1.
func RepeatFasta(s []byte, count int) {
	pos := 0;
	s2 := make([]byte, len(s) + WIDTH);
	bytes.Copy(s2, s);
	bytes.Copy(s2[len(s):len(s2)], s);
	for count > 0 {
		line := min(WIDTH, count);
		out.Write(s2[pos:pos+line]);
		out.WriteByte('\n');
		pos += line;
		if pos >= len(s) {
			pos -= len(s);
		}
		count -= line;
	}
}
Esempio n. 8
0
func (tls *Conn) Read(p []byte) (int, os.Error) {
	if len(tls.readBuf) == 0 {
		if tls.eof {
			return 0, os.EOF
		}

		var timeoutChan chan bool
		if tls.readTimeout > 0 {
			timeoutChan = make(chan bool)
			go timeout(timeoutChan, tls.readTimeout)
		}

		select {
		case b := <-tls.readChan:
			tls.readBuf = b
		case <-timeoutChan:
			return 0, os.EAGAIN
		}

		// TLS distinguishes between orderly closes and truncations. An
		// orderly close is represented by a zero length slice.
		if closed(tls.readChan) {
			return 0, io.ErrUnexpectedEOF
		}
		if len(tls.readBuf) == 0 {
			tls.eof = true
			return 0, os.EOF
		}
	}

	n := bytes.Copy(p, tls.readBuf)
	tls.readBuf = tls.readBuf[n:len(tls.readBuf)]
	return n, nil
}
Esempio n. 9
0
func (r *msgReceiver) recv() (*msg, os.Error) {
	// Init pointers to buffers where syscall recvmsg can write.
	r.iov.base = &r.data[0]
	r.iov.len = int32(len(r.data))
	r.hdr.iov = &r.iov
	r.hdr.niov = 1
	r.hdr.desc = &r.desc[0]
	r.hdr.ndesc = int32(len(r.desc))
	n, _, e := syscall.Syscall(syscall.SYS_IMC_RECVMSG, uintptr(r.fd), uintptr(unsafe.Pointer(&r.hdr)), 0)
	if e != 0 {
		return nil, os.NewSyscallError("imc_recvmsg", int(e))
	}

	// Make a copy of the data so that the next recvmsg doesn't
	// smash it.  The system call did not update r.iov.len.  Instead it
	// returned the total byte count as n.
	m := new(msg)
	m.rdata = make([]byte, n)
	bytes.Copy(m.rdata, &r.data)

	// Make a copy of the desc too.
	// The system call *did* update r.hdr.ndesc.
	if r.hdr.ndesc > 0 {
		m.rdesc = make([]int32, r.hdr.ndesc)
		for i := range m.rdesc {
			m.rdesc[i] = r.desc[i]
		}
	}

	return m, nil
}
Esempio n. 10
0
func (d *deflater) fillWindow(index int) (int, os.Error) {
	wSize := d.windowMask + 1
	if index >= wSize+wSize-(minMatchLength+maxMatchLength) {
		// shift the window by wSize
		bytes.Copy(d.window, d.window[wSize:2*wSize])
		index -= wSize
		d.windowEnd -= wSize
		if d.blockStart >= wSize {
			d.blockStart -= wSize
		} else {
			d.blockStart = math.MaxInt32
		}
		for i, h := range d.hashHead {
			d.hashHead[i] = max(h-wSize, -1)
		}
		for i, h := range d.hashPrev {
			d.hashPrev[i] = max(h-wSize, -1)
		}
	}
	var count int
	var err os.Error
	count, err = io.ReadAtLeast(d.r, d.window[d.windowEnd:len(d.window)], 1)
	d.windowEnd += count
	if err == os.EOF {
		return index, nil
	}
	return index, err
}
func (m *certificateMsg) marshal() (x []byte) {
	if m.raw != nil {
		return m.raw
	}

	var i int
	for _, slice := range m.certificates {
		i += len(slice)
	}

	length := 3 + 3*len(m.certificates) + i
	x = make([]byte, 4+length)
	x[0] = typeCertificate
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)

	certificateOctets := length - 3
	x[4] = uint8(certificateOctets >> 16)
	x[5] = uint8(certificateOctets >> 8)
	x[6] = uint8(certificateOctets)

	y := x[7:len(x)]
	for _, slice := range m.certificates {
		y[0] = uint8(len(slice) >> 16)
		y[1] = uint8(len(slice) >> 8)
		y[2] = uint8(len(slice))
		bytes.Copy(y[3:len(y)], slice)
		y = y[3+len(slice) : len(y)]
	}

	m.raw = x
	return
}
Esempio n. 12
0
func (d *decoder) Read(p []byte) (n int, err os.Error) {
	if d.err != nil {
		return 0, d.err
	}

	// Use leftover decoded output from last read.
	if len(d.out) > 0 {
		n = bytes.Copy(p, d.out)
		d.out = d.out[n:len(d.out)]
		return n, nil
	}

	// Read a chunk.
	nn := len(p) / 3 * 4
	if nn < 4 {
		nn = 4
	}
	if nn > len(d.buf) {
		nn = len(d.buf)
	}
	nn, d.err = io.ReadAtLeast(d.r, d.buf[d.nbuf:nn], 4-d.nbuf)
	d.nbuf += nn
	if d.nbuf < 4 {
		return 0, d.err
	}

	// Decode chunk into p, or d.out and then p if p is too small.
	nr := d.nbuf / 4 * 4
	nw := d.nbuf / 4 * 3
	if nw > len(p) {
		nw, d.end, d.err = d.enc.decode(&d.outbuf, d.buf[0:nr])
		d.out = d.outbuf[0:nw]
		n = bytes.Copy(p, d.out)
		d.out = d.out[n:len(d.out)]
	} else {
		n, d.end, d.err = d.enc.decode(p, d.buf[0:nr])
	}
	d.nbuf -= nr
	for i := 0; i < d.nbuf; i++ {
		d.buf[i] = d.buf[i+nr]
	}

	if d.err == nil {
		d.err = err
	}
	return n, d.err
}
Esempio n. 13
0
// pRF11 implements the TLS 1.1 pseudo-random function, as defined in RFC 4346, section 5.
func pRF11(result, secret, label, seed []byte) {
	hashSHA1 := sha1.New()
	hashMD5 := md5.New()

	labelAndSeed := make([]byte, len(label)+len(seed))
	bytes.Copy(labelAndSeed, label)
	bytes.Copy(labelAndSeed[len(label):len(labelAndSeed)], seed)

	s1, s2 := splitPreMasterSecret(secret)
	pHash(result, s1, labelAndSeed, hashMD5)
	result2 := make([]byte, len(result))
	pHash(result2, s2, labelAndSeed, hashSHA1)

	for i, b := range result2 {
		result[i] ^= b
	}
}
Esempio n. 14
0
func (r *reader) Read(p []byte) (n int, err os.Error) {
	b := *r;
	if len(b) == 0 && len(p) > 0 {
		return 0, os.EOF
	}
	n = bytes.Copy(p, b);
	*r = b[n:len(b)];
	return;
}
Esempio n. 15
0
File: rsa.go Progetto: 8l/go-learn
// leftPad returns a new slice of length size. The contents of input are right
// aligned in the new slice.
func leftPad(input []byte, size int) (out []byte) {
	n := len(input)
	if n > size {
		n = size
	}
	out = make([]byte, size)
	bytes.Copy(out[len(out)-n:len(out)], input)
	return
}
Esempio n. 16
0
// keysFromPreMasterSecret generates the connection keys from the pre master
// secret, given the lengths of the MAC and cipher keys, as defined in RFC
// 4346, section 6.3.
func keysFromPreMasterSecret11(preMasterSecret, clientRandom, serverRandom []byte, macLen, keyLen int) (masterSecret, clientMAC, serverMAC, clientKey, serverKey []byte) {
	var seed [tlsRandomLength * 2]byte
	bytes.Copy(seed[0:len(clientRandom)], clientRandom)
	bytes.Copy(seed[len(clientRandom):len(seed)], serverRandom)
	masterSecret = make([]byte, masterSecretLength)
	pRF11(masterSecret, preMasterSecret, masterSecretLabel, seed[0:len(seed)])

	bytes.Copy(seed[0:len(clientRandom)], serverRandom)
	bytes.Copy(seed[len(serverRandom):len(seed)], clientRandom)

	n := 2*macLen + 2*keyLen
	keyMaterial := make([]byte, n)
	pRF11(keyMaterial, masterSecret, keyExpansionLabel, seed[0:len(seed)])
	clientMAC = keyMaterial[0:macLen]
	serverMAC = keyMaterial[macLen : macLen*2]
	clientKey = keyMaterial[macLen*2 : macLen*2+keyLen]
	serverKey = keyMaterial[macLen*2+keyLen : len(keyMaterial)]
	return
}
Esempio n. 17
0
// Writing to msg.wdata.
func (m *msg) grow(n int) []byte {
	i := len(m.wdata)
	if i+n > cap(m.wdata) {
		a := make([]byte, i, (i+n)*2)
		bytes.Copy(a, m.wdata)
		m.wdata = a
	}
	m.wdata = m.wdata[0 : i+n]
	return m.wdata[i : i+n]
}
Esempio n. 18
0
func (d *decoder) Read(p []byte) (n int, err os.Error) {
	if len(p) == 0 {
		return 0, nil
	}
	if d.err != nil {
		return 0, d.err
	}

	for {
		// Copy leftover output from last decode.
		if len(d.out) > 0 {
			n = bytes.Copy(p, d.out)
			d.out = d.out[n:len(d.out)]
			return
		}

		// Decode leftover input from last read.
		var nn, nsrc, ndst int
		if d.nbuf > 0 {
			ndst, nsrc, d.err = Decode(&d.outbuf, d.buf[0:d.nbuf], d.readErr != nil)
			if ndst > 0 {
				d.out = d.outbuf[0:ndst]
				d.nbuf = bytes.Copy(&d.buf, d.buf[nsrc:d.nbuf])
				continue // copy out and return
			}
		}

		// Out of input, out of decoded output.  Check errors.
		if d.err != nil {
			return 0, d.err
		}
		if d.readErr != nil {
			d.err = d.readErr
			return 0, d.err
		}

		// Read more data.
		nn, d.readErr = d.r.Read(d.buf[d.nbuf:len(d.buf)])
		d.nbuf += nn
	}
	panic("unreachable")
}
Esempio n. 19
0
func (d *decoder) Read(p []byte) (n int, err os.Error) {
	if len(p) == 0 {
		return 0, nil
	}

	for {
		// Copy leftover output from last decode.
		if len(d.out) > 0 {
			n = bytes.Copy(p, d.out)
			d.out = d.out[n:len(d.out)]
			return
		}

		// Out of decoded output.  Check errors.
		if d.err != nil {
			return 0, d.err
		}
		if d.readErr != nil {
			d.err = d.readErr
			return 0, d.err
		}

		// Read and decode more input.
		var nn int
		nn, d.readErr = d.r.Read(d.buf[d.nbuf:len(d.buf)])
		d.nbuf += nn

		// Send complete lines to Decode.
		nl := bytes.LastIndex(d.buf[0:d.nbuf], newline)
		if nl < 0 {
			continue
		}
		nn, d.err = Decode(&d.outbuf, d.buf[0:nl+1])
		if e, ok := d.err.(CorruptInputError); ok {
			d.err = CorruptInputError(int64(e) + d.off)
		}
		d.out = d.outbuf[0:nn]
		d.nbuf = bytes.Copy(&d.buf, d.buf[nl+1:d.nbuf])
		d.off += int64(nl + 1)
	}
	panic("unreacahable")
}
Esempio n. 20
0
func copy(v int, x, y []byte) []byte {
	if len(x) > len(y) {
		x = x[0:len(y)]
	} else {
		y = y[0:len(x)]
	}
	if v == 1 {
		bytes.Copy(x, y)
	}
	return x
}
Esempio n. 21
0
func videoPollEvent(ev []byte) (err os.Error) {
	if srpcEnabled {
		r := bridge.share.eq.ri
		if r == bridge.share.eq.wi {
			return noEvents
		}
		bytes.Copy(ev, &bridge.share.eq.event[r])
		bridge.share.eq.ri = (r + 1) % eqsize
		return nil
	}
	return os.NewSyscallError("video_poll_event", syscall.VideoPollEvent(&ev[0]))
}
func (m *finishedMsg) marshal() (x []byte) {
	if m.raw != nil {
		return m.raw
	}

	x = make([]byte, 16)
	x[0] = typeFinished
	x[3] = 12
	bytes.Copy(x[4:len(x)], m.verifyData)
	m.raw = x
	return
}
Esempio n. 23
0
func TrSymbol_new(vm *RubyVM, str *string) RubyObject {
	id := TrSymbol_lookup(vm, str);
  
	if (!id) {
		s := Symbol{type: TR_T_Symbol, class: vm.classes[TR_T_Symbol], ivars: make(map[string] RubyObject), len: strlen(str), ptr: make([]byte, s.len + 1), interned: true};
		bytes.Copy(s.ptr, str[0:s.len - 1]);
		s.ptr[s.len] = '\0';
		id := s;
		TrSymbol_add(vm, s.ptr, id);
	}
	return id;
}
Esempio n. 24
0
func (a *decimal) String() string {
	n := 10 + a.nd
	if a.dp > 0 {
		n += a.dp
	}
	if a.dp < 0 {
		n += -a.dp
	}

	buf := make([]byte, n)
	w := 0
	switch {
	case a.nd == 0:
		return "0"

	case a.dp <= 0:
		// zeros fill space between decimal point and digits
		buf[w] = '0'
		w++
		buf[w] = '.'
		w++
		w += digitZero(buf[w : w+-a.dp])
		w += bytes.Copy(buf[w:w+a.nd], a.d[0:a.nd])

	case a.dp < a.nd:
		// decimal point in middle of digits
		w += bytes.Copy(buf[w:w+a.dp], a.d[0:a.dp])
		buf[w] = '.'
		w++
		w += bytes.Copy(buf[w:w+a.nd-a.dp], a.d[a.dp:a.nd])

	default:
		// zeros fill space between digits and decimal point
		w += bytes.Copy(buf[w:w+a.nd], a.d[0:a.nd])
		w += digitZero(buf[w : w+a.dp-a.nd])
	}
	return string(buf[0:w])
}
func (m *serverHelloMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

	length := 38 + len(m.sessionId)
	x := make([]byte, 4+length)
	x[0] = typeServerHello
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)
	x[4] = m.major
	x[5] = m.minor
	bytes.Copy(x[6:38], m.random)
	x[38] = uint8(len(m.sessionId))
	bytes.Copy(x[39:39+len(m.sessionId)], m.sessionId)
	z := x[39+len(m.sessionId) : len(x)]
	z[0] = uint8(m.cipherSuite >> 8)
	z[1] = uint8(m.cipherSuite)
	z[2] = uint8(m.compressionMethod)
	m.raw = x

	return x
}
Esempio n. 26
0
func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
	// loop because first call needs two reads:
	// one to get data and a second to look for an error.
	for {
		if len(r.unread) == 0 {
			n1, err1 := r.r.Read(r.data)
			r.unread = r.data[0:n1]
			err = err1
		}
		if n > 0 {
			break
		}
		n = bytes.Copy(p, r.unread)
		r.unread = r.unread[n:len(r.unread)]
	}
	return
}
func (m *clientKeyExchangeMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}
	length := len(m.ciphertext) + 2
	x := make([]byte, length+4)
	x[0] = typeClientKeyExchange
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)
	x[4] = uint8(len(m.ciphertext) >> 8)
	x[5] = uint8(len(m.ciphertext))
	bytes.Copy(x[6:len(x)], m.ciphertext)

	m.raw = x
	return x
}
Esempio n. 28
0
// EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS#1 v1.5.
// The message must be no longer than the length of the public modulus minus 11 bytes.
// WARNING: use of this function to encrypt plaintexts other than session keys
// is dangerous. Use RSA OAEP in new protocols.
func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.Error) {
	k := (pub.N.Len() + 7) / 8
	if len(msg) > k-11 {
		err = MessageTooLongError{}
		return
	}

	// EM = 0x02 || PS || 0x00 || M
	em := make([]byte, k-1)
	em[0] = 2
	ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):len(em)]
	err = nonZeroRandomBytes(ps, rand)
	if err != nil {
		return
	}
	em[len(em)-len(msg)-1] = 0
	bytes.Copy(mm, msg)

	m := new(big.Int).SetBytes(em)
	c := encrypt(new(big.Int), pub, m)
	out = c.Bytes()
	return
}
Esempio n. 29
0
// pHash implements the P_hash function, as defined in RFC 4346, section 5.
func pHash(result, secret, seed []byte, hash hash.Hash) {
	h := hmac.New(hash, secret)
	h.Write(seed)
	a := h.Sum()

	j := 0
	for j < len(result) {
		h.Reset()
		h.Write(a)
		h.Write(seed)
		b := h.Sum()
		todo := len(b)
		if j+todo > len(result) {
			todo = len(result) - j
		}
		bytes.Copy(result[j:j+todo], b)
		j += todo

		h.Reset()
		h.Write(a)
		a = h.Sum()
	}
}
Esempio n. 30
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [options] file\nOptions:\n", os.Args[0])
		flag.PrintDefaults()
	}

	async := flag.Bool("async", false, "transparently execute instructions concurrently")
	coords := flag.Bool("coords", false, "print current instruction and coordinates to stderr")
	debug := flag.Bool("debug", false, "synonym for -coords -pause -stack -trace")
	help := flag.Bool("help", false, "show usage information")
	pause := flag.Bool("pause", false, "pause for return keypress between instructions")
	stack := flag.Bool("stack", false, "print stack contents to stderr ")
	trace := flag.Bool("trace", false, "print instruction pointer superimposed over code to stderr")
	flag.Parse()

	if *help {
		flag.Usage()
		return
	}

	if *debug {
		*coords = true
		*pause = true
		*stack = true
		*trace = true
	}

	path := flag.Arg(0)
	if len(path) == 0 {
		fmt.Fprintln(os.Stderr, "No input file specified.")
		flag.Usage()
		return
	}

	raw, err := ReadFile(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "File error:", err.String())
	}

	code := bytes.Split(raw, []byte{'\n'}, len(raw))

	space := make([][]byte, 25)
	for i, _ := range space {
		space[i] = make([]byte, 80)
		rowLen := 0
		if i < len(code) {
			rowLen = len(code[i])
			bytes.Copy(space[i], code[i])
		}

		for j := 0; j < len(space[i])-rowLen; j++ {
			space[i][rowLen+j] = ' '
		}
	}

	if *async {
		befunge := gofunge93.NewAsyncGofunge93(space)
		debugger := gofunge93.NewAsyncGofunge93Debugger(befunge)
		debugger.SetPause(*pause)
		debugger.SetPrintCoords(*coords)
		debugger.SetPrintStack(*stack)
		debugger.SetPrintTrace(*trace)
		gofunge93.StartDebug(debugger, gofunge93.NewIP2d(0, 0, [2]int8{1, 0}, 80, 25))
	} else {
		befunge := gofunge93.NewGofunge93(space)
		debugger := gofunge93.NewGofunge93Debugger(befunge)
		debugger.SetPause(*pause)
		debugger.SetPrintCoords(*coords)
		debugger.SetPrintStack(*stack)
		debugger.SetPrintTrace(*trace)
		gofunge93.StartDebug(debugger, gofunge93.NewIP2d(0, 0, [2]int8{1, 0}, 80, 25))
	}
}