// decrypt msg from reader, then write into writer func PipeDecrypt(r net.Conn, w net.Conn, key string) error { laes := new(pcrypto.Pcrypto) if err := laes.Init([]byte(key)); err != nil { log.Error("Pcrypto Init error: %v", err) return fmt.Errorf("Pcrypto Init error: %v", err) } nreader := bufio.NewReader(r) for { buf, err := nreader.ReadBytes('\n') if err != nil { return err } res, err := laes.Decrypt(buf) if err != nil { log.Error("Decrypt [%s] error, %v", string(buf), err) return fmt.Errorf("Decrypt [%s] error: %v", string(buf), err) } _, err = w.Write(res) if err != nil { return err } } return nil }
// decrypt msg from reader, then write into writer func pipeDecrypt(r net.Conn, w net.Conn, conf config.BaseConf) (err error) { laes := new(pcrypto.Pcrypto) key := conf.AuthToken if conf.PrivilegeMode { key = conf.PrivilegeToken } if err := laes.Init([]byte(key)); err != nil { log.Warn("ProxyName [%s], Pcrypto Init error: %v", conf.Name, err) return fmt.Errorf("Pcrypto Init error: %v", err) } buf := make([]byte, 5*1024+4) var left, res []byte var cnt int nreader := bufio.NewReader(r) for { // there may be more than 1 package in variable // and we read more bytes if unpkgMsg returns an error var newBuf []byte if cnt < 0 { n, err := nreader.Read(buf) if err != nil { return err } newBuf = append(left, buf[0:n]...) } else { newBuf = left } cnt, res, left = unpkgMsg(newBuf) if cnt < 0 { continue } // aes if conf.UseEncryption { res, err = laes.Decrypt(res) if err != nil { log.Warn("ProxyName [%s], decrypt error, %v", conf.Name, err) return fmt.Errorf("Decrypt error: %v", err) } } // gzip if conf.UseGzip { res, err = laes.Decompression(res) if err != nil { log.Warn("ProxyName [%s], decompression error, %v", conf.Name, err) return fmt.Errorf("Decompression error: %v", err) } } _, err = w.Write(res) if err != nil { return err } } return nil }