Ejemplo n.º 1
0
func main() {
	binding := flag.String("b", "post", "Binding. Values are post, redirect, or nourl.")
	flag.Parse()

	input, e := ioutil.ReadAll(os.Stdin)
	if e != nil {
		log.Fatal(e)
	}

	if *binding == "redirect" {
		deflated := deflate(input)

		buf := bytes.Buffer{}
		encoder := base64.NewEncoder(base64.StdEncoding, &buf)
		encoder.Write(deflated)
		encoder.Close()

		fmt.Print(percentURLEncode(buf.String()))

	} else if *binding == "nourl" {
		deflated := deflate(input)

		encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
		encoder.Write(deflated)
		encoder.Close()

	} else if *binding == "post" {
		encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
		encoder.Write(input)
		encoder.Close()
	} else {
		log.Fatal("Invalid Binding.")
	}

}
Ejemplo n.º 2
0
Archivo: smtpc.go Proyecto: xoba/goutil
// only allows single content
func SendMulti(auth Auth, email MultipartEmail) error {
	if len(email.Content) != 1 {
		panic("only 1 content supported")
	}
	a := smtp.PlainAuth("", auth.User, auth.Password, auth.Host)
	buf := new(bytes.Buffer)
	boundary := randomBoundary()
	header := make(textproto.MIMEHeader)
	header.Set("Subject", email.Subject)
	header.Set("From", email.From)
	header.Set("To", strings.Join(email.To, ", "))
	if len(email.Cc) > 0 {
		header.Set("Cc", strings.Join(email.Cc, ", "))
	}
	header.Set("MIME-Version", "1.0")
	header.Set("Content-Type", "multipart/mixed; boundary="+boundary)
	for k, v := range header {
		for _, s := range v {
			fmt.Fprintf(buf, "%s: %s%s", k, textproto.TrimString(s), crlf)
		}
	}
	fmt.Fprint(buf, crlf)
	mm := multipart.NewWriter(buf)
	mm.SetBoundary(boundary)
	{
		content := email.Content[0]
		header := make(textproto.MIMEHeader)
		header.Set("Content-Type", content.Type)
		header.Set("Content-Transfer-Encoding", "base64")
		part, err := mm.CreatePart(header)
		if err != nil {
			return err
		}
		lw := &lineWriter{Writer: part, Length: 75}
		e := base64.NewEncoder(base64.StdEncoding, lw)
		e.Write(content.Data)
		e.Close()
	}
	for _, a := range email.Attachments {
		header := make(textproto.MIMEHeader)
		header.Set("Content-Type", fmt.Sprintf(`%s; name="%s"`, a.Type, a.Filename))
		if len(a.ContentID) > 0 {
			header.Set("Content-ID", fmt.Sprintf(`<%s>`, a.ContentID))
		}
		header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, a.Filename))
		header.Set("Content-Transfer-Encoding", "base64")
		part, err := mm.CreatePart(header)
		if err != nil {
			return err
		}
		lw := &lineWriter{Writer: part, Length: 75}
		e := base64.NewEncoder(base64.StdEncoding, lw)
		e.Write(a.Data)
		e.Close()
	}
	mm.Close()
	addr := fmt.Sprintf("%s:%d", auth.Host, auth.Port)
	return smtp.SendMail(addr, a, email.From, email.To, buf.Bytes())

}
Ejemplo n.º 3
0
func base64encode(src []byte) string {
	var buf bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
	encoder.Write(src)
	encoder.Close()
	return buf.String()
}
Ejemplo n.º 4
0
func encodedAuth(user, pwd string) string {
	var buf bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
	encoder.Write([]byte(user + ":" + pwd))
	encoder.Close()
	return buf.String()
}
// signV2 sign the request before Do() (AWS Signature Version 2).
func signV2(req http.Request, accessKeyID, secretAccessKey string) *http.Request {
	// Signature calculation is not needed for anonymous credentials.
	if accessKeyID == "" || secretAccessKey == "" {
		return &req
	}

	// Initial time.
	d := time.Now().UTC()

	// Add date if not present.
	if date := req.Header.Get("Date"); date == "" {
		req.Header.Set("Date", d.Format(http.TimeFormat))
	}

	// Calculate HMAC for secretAccessKey.
	stringToSign := getStringToSignV2(req)
	hm := hmac.New(sha1.New, []byte(secretAccessKey))
	hm.Write([]byte(stringToSign))

	// Prepare auth header.
	authHeader := new(bytes.Buffer)
	authHeader.WriteString(fmt.Sprintf("%s %s:", signV2Algorithm, accessKeyID))
	encoder := base64.NewEncoder(base64.StdEncoding, authHeader)
	encoder.Write(hm.Sum(nil))
	encoder.Close()

	// Set Authorization header.
	req.Header.Set("Authorization", authHeader.String())

	return &req
}
Ejemplo n.º 6
0
func handlePodSign(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	token := mux.Vars(r)["token"]

	uuid, err := pods.getUUID(token)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintln(w, err)
		return
	}

	content := r.FormValue("content")
	if content == "" {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "content form value not found")
		return
	}

	// HMAC(UID:content)
	h := hmac.New(sha512.New, hmacKey[:])
	h.Write((*uuid)[:])
	h.Write([]byte(content))

	// Send back HMAC as the signature
	w.Header().Add("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	enc := base64.NewEncoder(base64.StdEncoding, w)
	enc.Write(h.Sum(nil))
	enc.Close()
}
Ejemplo n.º 7
0
func (c *Client) PutObject(name, bucket string, md5 hash.Hash, size int64, body io.Reader) error {
	req := newReq("http://" + bucket + ".s3.amazonaws.com/" + name)
	req.Method = "PUT"
	req.ContentLength = size
	if md5 != nil {
		b64 := new(bytes.Buffer)
		encoder := base64.NewEncoder(base64.StdEncoding, b64)
		encoder.Write(md5.Sum(nil))
		encoder.Close()
		req.Header.Set("Content-MD5", b64.String())
	}
	c.Auth.SignRequest(req)
	req.Body = ioutil.NopCloser(body)

	res, err := c.httpClient().Do(req)
	if res != nil && res.Body != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return err
	}
	if res.StatusCode != 200 {
		res.Write(os.Stderr)
		return fmt.Errorf("Got response code %d from s3", res.StatusCode)
	}
	return nil
}
Ejemplo n.º 8
0
func Base64Encoding(s string) string {
	var buf bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
	defer encoder.Close()
	encoder.Write([]byte(s))
	return buf.String()
}
Ejemplo n.º 9
0
func CalcBase64(data string) string {
	var buf bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
	encoder.Write([]byte(data))
	encoder.Close()
	return buf.String()
}
Ejemplo n.º 10
0
// Encode encodes the transport as a single string for the purpose of letting a
// user paste it into his application configuraion.
func (t *Connection) Encode() (string, error) {
	resultWriter := new(bytes.Buffer)

	// Write version number first and verify that it wrote exactly two characters
	n, _ := resultWriter.WriteString(ShareableTansportConnectionVersion)
	if n != 2 {
		panic("invalid version lentgh")
	}

	data := struct {
		Transport string `json:"t"`
		Secret    string `json:"s"`
		Addr      string `json:"a"`
	}{
		Transport: t.Transport,
		Secret:    t.Secret,
		Addr:      t.Addr,
	}
	// JSON encode the data struct
	jsonBytes, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}

	// Base64 encode the JSON data
	encoder := base64.NewEncoder(base64.URLEncoding, resultWriter)
	encoder.Write(jsonBytes)
	encoder.Close()

	return string(resultWriter.Bytes()[:]), nil
}
Ejemplo n.º 11
0
Archivo: sx.go Proyecto: hlandau/sx
func writeBase64String(s string, b *bufio.Writer, f *Format) {
  b.WriteRune('|')
  w := base64.NewEncoder(base64.StdEncoding, b)
  w.Write([]byte(s))
  w.Close()
  b.WriteRune('|')
}
Ejemplo n.º 12
0
func (c *Client) PutObject(name, bucket string, md5 hash.Hash, size int64, body io.Reader) error {
	req := newReq("http://" + bucket + "." + c.hostname() + "/" + name)
	req.Method = "PUT"
	req.ContentLength = size
	if md5 != nil {
		b64 := new(bytes.Buffer)
		encoder := base64.NewEncoder(base64.StdEncoding, b64)
		encoder.Write(md5.Sum(nil))
		encoder.Close()
		req.Header.Set("Content-MD5", b64.String())
	}
	if c.DefaultACL != "" {
		req.Header.Set("x-amz-acl", c.DefaultACL)
	}
	contentType := mime.TypeByExtension(path.Ext(name))
	if contentType == "" {
		contentType = "application/octet-stream"
	}
	req.Header.Set("Content-Type", contentType)
	c.Auth.SignRequest(req)
	req.Body = ioutil.NopCloser(body)

	res, err := c.httpClient().Do(req)
	if res != nil && res.Body != nil {
		defer httputil.CloseBody(res.Body)
	}
	if err != nil {
		return err
	}
	if res.StatusCode != http.StatusOK {
		res.Write(os.Stderr)
		return fmt.Errorf("Got response code %d from s3", res.StatusCode)
	}
	return nil
}
Ejemplo n.º 13
0
func encode64(value string) (result string) {
	buffer := &bytes.Buffer{}
	encoder := base64.NewEncoder(base64.StdEncoding, buffer)
	encoder.Write([]byte(value))
	encoder.Close()
	return buffer.String()
}
Ejemplo n.º 14
0
// Encode encodes data to a base64 encoded using the secconf codec.
// data is encrypted with all public keys found in the supplied keyring.
func Encode(data []byte, keyring io.Reader) ([]byte, error) {
	entityList, err := openpgp.ReadArmoredKeyRing(keyring)
	if err != nil {
		return nil, err
	}
	buffer := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, buffer)
	pgpWriter, err := openpgp.Encrypt(encoder, entityList, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	gzWriter := gzip.NewWriter(pgpWriter)
	if _, err := gzWriter.Write(data); err != nil {
		return nil, err
	}
	if err := gzWriter.Close(); err != nil {
		return nil, err
	}
	if err := pgpWriter.Close(); err != nil {
		return nil, err
	}
	if err := encoder.Close(); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}
Ejemplo n.º 15
0
// wrap64 writes a byte payload as wrapped base64 to an io.writer
func wrap64(writer io.Writer, b []byte, wrap int) {
	breaker := NewLineBreaker(writer, wrap)
	b64 := base64.NewEncoder(base64.StdEncoding, breaker)
	b64.Write(b)
	b64.Close()
	breaker.Close()
}
Ejemplo n.º 16
0
func tcp_checksum(b []byte) uint16 {
	if len(b)%2 != 0 {
		panic(fmt.Sprintf("tcp checksum bad length: %d", len(b)))
	}

	buf := bytes.NewBuffer(make([]byte, 0))
	enc := base64.NewEncoder(base64.StdEncoding, buf)
	enc.Write(b)
	//	b64, _ := ioutil.ReadAll(buf)

	//	Trace("To Checksum: %v", string(b64))

	var sum uint32 = 0
	var tmp uint16

	for c := 0; c < len(b); c = c + 2 {
		tmp = uint16(b[c]) | uint16(b[c+1])<<8
		sum += uint32(tmp)
	}

	sum = (sum >> 16) + (sum & 0xffff)
	sum += (sum >> 16)
	Trace("tcp checksum: %d", uint16(^sum))
	return uint16(^sum)
}
Ejemplo n.º 17
0
// WriteTo writes the LogplexLineFormatter to the provided writer
// in Kinesis' PutRecordsFormat. Conforms to the WriterTo interface.
func (r KinesisRecord) WriteTo(w io.Writer) (n int64, err error) {
	var t int
	var t64 int64
	var b string

	// Add an integer in the PartitionKey to enable distribution
	// over multiple shards in the Kinesis stream.
	b = partitionKeyHeader + r.partitionKey() + partitionKeyFooter
	t, err = w.Write([]byte(b))
	n += int64(t)
	if err != nil {
		return
	}

	e := base64.NewEncoder(base64.StdEncoding, w)

	t64, err = io.Copy(e, r.llf)
	n += encodedLen(t64)
	if err != nil {
		return
	}

	if err = e.Close(); err != nil {
		return
	}

	t, err = w.Write([]byte(`"}`))
	n += int64(t)
	return
}
Ejemplo n.º 18
0
func (c *Client) PutObject(key, bucket string, md5 hash.Hash, size int64, body io.Reader) error {
	req := newReq(c.keyURL(bucket, key))
	req.Method = "PUT"
	req.ContentLength = size
	if md5 != nil {
		b64 := new(bytes.Buffer)
		encoder := base64.NewEncoder(base64.StdEncoding, b64)
		encoder.Write(md5.Sum(nil))
		encoder.Close()
		req.Header.Set("Content-MD5", b64.String())
	}
	c.Auth.SignRequest(req)
	req.Body = ioutil.NopCloser(body)

	res, err := c.transport().RoundTrip(req)
	if res != nil && res.Body != nil {
		defer httputil.CloseBody(res.Body)
	}
	if err != nil {
		return err
	}
	if res.StatusCode != http.StatusOK {
		// res.Write(os.Stderr)
		return fmt.Errorf("Got response code %d from s3", res.StatusCode)
	}
	return nil
}
Ejemplo n.º 19
0
func encodedUsernameAndPassword(user, pwd string) string {
	bb := &bytes.Buffer{}
	encoder := base64.NewEncoder(base64.StdEncoding, bb)
	encoder.Write([]byte(user + ":" + pwd))
	encoder.Close()
	return bb.String()
}
Ejemplo n.º 20
0
func encode(r io.Reader) error {
	p := new(bytes.Buffer)
	defer flush(p)

	e := base64.NewEncoder(base64.StdEncoding, p)
	defer e.Close()

	var b [8192]byte
	for {
		n, err := r.Read(b[:])
		if n > 0 {
			e.Write(b[:n])
		}
		write(p)

		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
	}

	return nil
}
Ejemplo n.º 21
0
func (md *NeteaseMusicDetail) MakeUrl() string {
	strDfsID := strconv.Itoa(md.DfsID)
	// load eid from cache first
	eidKey := gCacheKeyPrefix + gNeteaseEIDCacheKeyPrefix + strDfsID
	eid := GetCache(eidKey, false)
	if nil == eid {
		// build encrypted dfsId, see https://github.com/yanunon/NeteaseCloudMusic/wiki/网易云音乐API分析#歌曲id加密代码
		byte1 := []byte("3go8&$8*3*3h0k(2)2")
		byte2 := []byte(strDfsID)
		byte1Len := len(byte1)
		for i := range byte2 {
			byte2[i] = byte2[i] ^ byte1[i%byte1Len]
		}
		sum := md5.Sum(byte2)
		var buff bytes.Buffer
		enc := base64.NewEncoder(base64.StdEncoding, &buff)
		_, err := enc.Write(sum[:])
		if nil != err {
			log.Printf("error encoding(base64) netease dfsId %s:%s", strDfsID, err)
			return ""
		}
		enc.Close()
		eid = []byte(gNeteaseEIDReplacer.Replace(buff.String()))
	}
	// update cache, no expiration, no compression
	SetCache(eidKey, eid, 0, false)
	return fmt.Sprintf(gNeteaseMusicCDNUrlF, eid, strDfsID)
}
Ejemplo n.º 22
0
func encode(data []byte) *bytes.Buffer {
	bb := &bytes.Buffer{}
	encoder := base64.NewEncoder(base64.StdEncoding, bb)
	encoder.Write([]byte(data))
	encoder.Close()
	return bb
}
Ejemplo n.º 23
0
func signContent(content []byte, privKey *packet.PrivateKey) ([]byte, error) {
	sig := new(packet.Signature)
	sig.PubKeyAlgo = privKey.PubKeyAlgo
	sig.Hash = openpgpConfig.Hash()
	sig.CreationTime = time.Now()
	sig.IssuerKeyId = &privKey.KeyId

	h := openpgpConfig.Hash().New()
	h.Write(content)

	err := sig.Sign(h, privKey, openpgpConfig)
	if err != nil {
		return nil, err
	}

	buf := bytes.NewBufferString("openpgp ")
	// TODO: split the base64 blob over many lines for readability of the resulting file
	enc := base64.NewEncoder(base64.StdEncoding, buf)
	err = sig.Serialize(enc)
	if err != nil {
		return nil, err
	}
	enc.Close()

	return buf.Bytes(), nil
}
Ejemplo n.º 24
0
// inlinesvg returns a byte slice that is utf8 compliant or base64
// encoded
func inlineSVG(w io.Writer, r io.Reader, encode bool) {
	if encode {
		bw := base64.NewEncoder(base64.StdEncoding, w)
		w.Write([]byte(`url("data:image/svg+xml;base64,`))
		io.Copy(bw, r)
		w.Write([]byte(`")`))
		return
	}

	w.Write([]byte(`url("data:image/svg+xml;utf8,`))
	// Exhaust the buffer and do some sloppy regex stuff to the input
	// TODO: convert url encoding to streaming reader/writer
	var buf bytes.Buffer
	buf.ReadFrom(r)

	// Strip unnecessary newlines
	input := bytes.Replace(buf.Bytes(), []byte("\r\n"), []byte(""), -1)
	// input = bytes.Replace(input, []byte(`"`), []byte("'"), -1)
	// reg := regexp.MustCompile(`>\\s+<`)
	// input = reg.ReplaceAll(input, []byte("><"))

	// url.String() properly escapes paths
	u := &url.URL{Path: string(input)}
	io.WriteString(w, u.String())
	w.Write([]byte(`")`))
}
Ejemplo n.º 25
0
// bEncode encodes s using base64 encoding and writes it to buf.
func (e WordEncoder) bEncode(buf *bytes.Buffer, charset, s string) {
	w := base64.NewEncoder(base64.StdEncoding, buf)
	// If the charset is not UTF-8 or if the content is short, do not bother
	// splitting the encoded-word.
	if !isUTF8(charset) || base64.StdEncoding.EncodedLen(len(s)) <= maxContentLen {
		io.WriteString(w, s)
		w.Close()
		return
	}

	var currentLen, last, runeLen int
	for i := 0; i < len(s); i += runeLen {
		// Multi-byte characters must not be split accross encoded-words.
		// See RFC 2047, section 5.3.
		_, runeLen = utf8.DecodeRuneInString(s[i:])

		if currentLen+runeLen <= maxBase64Len {
			currentLen += runeLen
		} else {
			io.WriteString(w, s[last:i])
			w.Close()
			e.splitWord(buf, charset)
			last = i
			currentLen = runeLen
		}
	}
	io.WriteString(w, s[last:])
	w.Close()
}
Ejemplo n.º 26
0
func (d *Data) SetTileGrid(grid DataTileGrid) (err error) {
	var (
		buf        bytes.Buffer
		b64Encoder io.WriteCloser
		zlibWriter *zlib.Writer
		gids       []uint32
		gridTile   DataTileGridTile
	)
	d.Encoding = "base64"
	d.Compression = "zlib"
	d.RawTiles = []DataTile{}
	gids = make([]uint32, grid.Width*grid.Height)
	for y := 0; y < grid.Height; y++ {
		for x := 0; x < grid.Width; x++ {
			gridTile = grid.Tiles[x][y]
			gids[grid.Width*y+x] = encodeGid(
				gridTile.Id,
				gridTile.FlipX,
				gridTile.FlipY,
				gridTile.FlipD)
		}
	}
	b64Encoder = base64.NewEncoder(base64.StdEncoding, &buf)
	zlibWriter = zlib.NewWriter(b64Encoder)
	if err = binary.Write(zlibWriter, binary.LittleEndian, gids); err != nil {
		return
	}
	zlibWriter.Close()
	b64Encoder.Close()
	d.RawContents = buf.String()
	return
}
Ejemplo n.º 27
0
func (s String) encodeAscii(b BinWriter) {
	writebyte(b, '\'')
	encoder := base64.NewEncoder(base64.StdEncoding, b)
	encoder.Write(s.raw())
	encoder.Close()
	writebyte(b, '\'')
}
Ejemplo n.º 28
0
func (f *rawFlowID) Serialize() []byte {
	buf := bytes.NewBuffer(nil)
	enc := base64.NewEncoder(base64.RawStdEncoding, buf)

	enc.Write([]byte{
		byte(f.flags & 0xff),
		byte(f.flags >> 8),
		f.offEth,
		f.offOutterVlan,
		f.offVlan,
		f.offOutterIPv4,
		f.offIPv4,
		f.offOutterIPv6,
		f.offIPv6,
		f.offICMPv4,
		f.offICMPv6,
		f.offUDP,
		f.offTCP,
		f.offID,
		f.cntEth,
		f.cntVlan,
		f.cntIP,
	})
	enc.Write(f.flowID)
	enc.Close()

	return buf.Bytes()
}
Ejemplo n.º 29
0
// Encode returns a WriteCloser which will encode the data written to it in
// OpenPGP armor.
func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) {
	bType := []byte(blockType)
	err = writeSlices(out, armorStart, bType, armorEndOfLineOut)
	if err != nil {
		return
	}

	for k, v := range headers {
		err = writeSlices(out, []byte(k), armorHeaderSep, []byte(v), newline)
		if err != nil {
			return
		}
	}

	_, err = out.Write(newline)
	if err != nil {
		return
	}

	e := &encoding{
		out:       out,
		breaker:   newLineBreaker(out, 64),
		crc:       crc24Init,
		blockType: bType,
	}
	e.b64 = base64.NewEncoder(base64.StdEncoding, e.breaker)
	return e, nil
}
Ejemplo n.º 30
0
func encodeBytesASCII(val []byte, b BinWriter) {
	writebyte('\'', b)
	encoder := base64.NewEncoder(base64.StdEncoding, b)
	encoder.Write(val)
	encoder.Close()
	writebyte('\'', b)
}