Example #1
0
File: tcp.go Project: cirias/myvpn
func (conn *TCPConn) Write(b []byte) (n int, err error) {
	defer func() {
		if r := recover(); r != nil {
			glog.Warningln(r)
			err = r.(error)
		}
	}()
	iv, err := cipher.NewIV()
	if err != nil {
		glog.V(3).Infoln("fail to create iv", err)
		return 0, err
	}

	enc := cipher.NewEncrypter(conn.cipher, iv)
	encrypted := make([]byte, len(iv)+len(b))
	copy(encrypted, iv)
	enc.Encrypt(encrypted[len(iv):], b)

	if _, err := conn.Conn.Write(encrypted); err != nil {
		glog.V(3).Infoln("fail to write data through connection", err)
		return 0, err
	}

	glog.V(3).Infoln("data writed", encrypted)
	return len(encrypted), nil
}
Example #2
0
File: tcp.go Project: cirias/myvpn
func send(cph *cipher.Cipher, tcpConn net.Conn, data interface{}) error {
	iv, err := cipher.NewIV()
	if err != nil {
		glog.V(3).Infoln("fail to create iv", err)
		return err
	}

	enc := cipher.NewEncrypter(cph, iv)
	buf := &bytes.Buffer{}
	if err := binary.Write(buf, binary.BigEndian, data); err != nil {
		glog.V(3).Infoln("fail to marshal data", err)
		return err
	}
	unencypted := buf.Bytes()

	packet := make([]byte, len(iv)+len(unencypted))
	copy(packet, iv)
	enc.Encrypt(packet[len(iv):], unencypted)

	if _, err := tcpConn.Write(packet); err != nil {
		glog.V(3).Infoln("fail to write data through connection", err)
		return err
	}

	glog.V(3).Infoln("data send", data)
	return nil
}