Exemple #1
0
func (this *PrePackModule) Init(global_conf *context.GlobalContext) (err error) {
	this.click_head = global_conf.Prepack.ClickHeader
	this.win_head = global_conf.Prepack.WinHeader
	this.common_head = global_conf.Prepack.CommonHeader
	utils.DebugLog.Write("Prepack.ClickHeader [%s]", this.click_head)
	utils.DebugLog.Write("Prepack.WinHeader [%s]", this.win_head)
	base64_code := [64]string{"0Ge5Q6wnuBML3Wg-8s7kAjOr2xohRHif1CczEXDKq_VaUPJdYpy9TSNvIFmbZ4tl", "1RPspa70TiZum_6tKNIFOVJ4o3gBGkdLlvhCnQHWDxEA5cq8fYzj2XU9MwrS-ybe", "2txfHr4BFaqSOTVn_CuYozeygvbcL1RNKs8MkWUPG0JpmXd5l6hDIAjw7i9E-Q3Z", "3c5gtSlVFoEXsehLaMJwI0Rv6U7xmWuzCYABP_TDp-QfdKniNrq2Ob419jHkGZy8", "456tTGIcm3EK7_RQpBA2uezWXjqnHPsi9bV-Zx8vSgkwaMlCoJ1DyfLFr0UYNhdO", "5zDkOUe_q7a2TN-Y3fvrnsCHZxhBIdcESPj8GuWXLgib4QwJo6yVtMF0Kp1mA9Rl", "6bgkOJjx8mPI9Y_hWANypSoFtnDadivQ31crfR0uC-K2qzE4UslMXGBTL5Vw7HeZ", "7zXOg9UZp0sa2vWGJP3TCBYR-6eIfHVnmdKwMrbuSlo8LFNthAkqcDy4QxE5ji1_", "8iMsWOQuApUEhoITJfjbYdLqrcF3m17XwNa_B4lVSC-Deny0KPtG6z2k5gx9vZHR", "9gdocC-fpejPiYnHF7l0XrWUAaS3OI_Nm2uDkyZbVGRJq5vt1QzhM6xTLw4BsK8E", "aJEr4IWdD3Zxw8ClmNzGPHFL9usbKTvXU-2eAkiV16ScBOy7pqgQnR0_j5MYftho", "bZqml65BeDJETLrNpMAC-tIOhVXsnf1w9_Szv7gP2xaWKR0cQ4F3Uuo8YHGdjiky", "cIJjl64KtC_doMuUeEq0fv831F2kDnNshAbzVaZTprYHB-mWXwygQ7RGxi9PL5SO", "dZgpqwv-321tRL5ITib0X8Uy64kKjoQuOsrGENxMBfY9WDea7HcmJnAC_PzSlFVh", "eUOghPNMEVoxkiG7YQL0Zmjc_IWsdl2FtRufySH4DvATBwbXCK9z5-par8J61nq3", "fP1pUQ3_moNy-7FXHAGT8uKL4wszIVMjaRdhi25E9O0kWntrBvScl6DZgqbxYJCe", "g43jISvAuK6UND0qYma2QXxRPyBib1l_zCtke5VpsEJOMf7LdZHGcFnw-hW9o8Tr", "humQGil2xCkHY391US7DvZVEbe_PR4NXWqKgrFfJApd60Bt8yno5IMawsj-OLzcT", "i2MxZ56X0LWSQGzpONHwPje_lA1nftYIvRTr-9UJs4DkydcgoVqBCu3bE7Kh8mFa", "jk9A_YBn6aqWt1yfm38SLJ7z-c42erUEHxhb5dROGgNoIusvKCDXQMTp0lZiPwVF", "kCBHjyTZmhSEwfY8JPdX9MpoKWuL61FQDtOnzab-s3INrc4qi0e7lA_gxUV5R2Gv", "lToWfMpEHAcir_JLRdBDSkaU5hPnmOCqVZ2KXNzI4uwGx01Ys379egtQ8yF-vbj6", "m36NTQ82RhD4E-tMfxjs0CPoLbirI_WBZHgnFcypezvkadXSGwO95lAKYJ7Uu1qV", "niOyHQ6oFbWzeM1qmu4tV9grTkldhGj20NELD3pRU8ZSAa7-wxKJsYcPBI5_vCXf", "odnysI_h-FGKmJQ2NvUwgVLcaOHCbSDAqlxp85Zurjzi4Mft793RYPe6TE01XkWB", "p0tGYHmhNTfdFkMQbUc1axCq4y5viXD89suS3BAIPL67VKrWolOgzwRZ_eE2jJ-n", "qrw0jSf_3pxth-LZnPoBITkGAvl7gQKdF69CVyWaD5izE4mN8ecMRHYOu2UJs1Xb", "rjUafJvNocE3D8TiQYVAHLp7WbSnzemqugBy5lIFk10_2CdM-Gh69Ksx4XRZtOwP", "sPWiyNlL3rGBI8gtfxpDbAoUe_5uhzMjZd09cTCamEwYJF6k14QvnVK7Oq-R2HXS", "tHir6_aKGnqf1RQABh3IzSwYysp4kWdU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nYd7zPQo1M8KxyIjBugESqTGZtmleifcVkCX9v5-aO4", "-6mTYvy7KRxCr2elEiWbL5qMoc9G1_3untsdpjwDAzFVhZSgBN0aIOU4QkH8fJXP"}
	for i := 0; i < len(base64_code); i++ {
		this.coder[i] = base64.NewEncoding(base64_code[i])
	}
	code_char := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
	this.basecoder = base64.NewEncoding(code_char)
	this.texttpl, err = template.ParseFiles(global_conf.Template.Texttpl)
	utils.DebugLog.Write("get texttpl [%s]", global_conf.Template.Texttpl)
	if err != nil || this.texttpl == nil {
		utils.FatalLog.Write("load texttpl fail, err[%s]", err.Error())
		return
	}
	this.imgtpl, err = template.ParseFiles(global_conf.Template.Imagetpl)
	utils.DebugLog.Write("get imagetpl [%s]", global_conf.Template.Imagetpl)
	if err != nil || this.imgtpl == nil {
		utils.FatalLog.Write("load imagetpl fail, err[%s]", err.Error())
		return
	}
	this.icontexttpl, err = template.ParseFiles(global_conf.Template.Icontexttpl)
	utils.DebugLog.Write("get icontpl [%s]", global_conf.Template.Icontexttpl)
	if err != nil || this.icontexttpl == nil {
		utils.FatalLog.Write("load icontexttpl fail, err[%s]", err.Error())
		return
	}
	this.texttpl_rec, err = template.ParseFiles(global_conf.Template.Texttplrec)
	utils.DebugLog.Write("get texttpl_rec [%s]", global_conf.Template.Texttplrec)
	if err != nil || this.texttpl_rec == nil {
		utils.FatalLog.Write("load txttpl_rec fail . err[%s]", err.Error())
		return
	}
	this.imgtpl_rec, err = template.ParseFiles(global_conf.Template.Imagetplrec)
	utils.DebugLog.Write("get texttpl_rec [%s]", global_conf.Template.Imagetplrec)
	if err != nil || this.imgtpl_rec == nil {
		utils.FatalLog.Write("load imagetpl_rec fail . err[%s]", err.Error())
		return
	}
	this.icontpl_rec, err = template.ParseFiles(global_conf.Template.Icontplrec)
	utils.DebugLog.Write("get icontpl_rec [%s]", global_conf.Template.Icontplrec)
	if err != nil || this.icontpl_rec == nil {
		utils.FatalLog.Write("load icontpl_rec fail . err[%s]", err.Error())
		return
	}
	/*	this.recommendtpl, err = template.ParseFiles(global_conf.Template.Recommendtpl)
		if err != nil || this.imgtpl == nil {
			return
		}*/
	return
}
Exemple #2
0
//for a websocket connection this function funcs as handshaking
//apply websocket protocal to establish a connection
func HandshakeOfWS(conn net.Conn) error {
	b := make([]byte, 1024)

	a := make([]byte, 1024)
	n, err := conn.Read(a)
	b = append(b, a[:n]...)
	if err != nil {
		if err == io.EOF {
		} else {
			return errors.New("error happen when read from connection!")
		}
	}

	re, err := regexp.Compile("Sec-WebSocket-Key: (.*)\r\n")
	if checkErr(err) {
		return errors.New("regexp error!")
	}
	result := re.FindStringSubmatch(string(b))
	if result == nil {
		return errors.New("not right format!")
	}
	key_tmp := append([]byte(result[1]), []byte(mask)...)
	key_tmp_tmp := sha1.Sum(key_tmp)
	encoder := base64.NewEncoding(base64Table)
	dst := make([]byte, 1024)
	encoder.Encode(dst, key_tmp_tmp[:])
	reply := "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + string(dst) + "\r\n\r\n"
	conn.Write([]byte(reply))
	return nil
}
Exemple #3
0
func SendToEvernote(from, to, subject, body string) error {

	hp := strings.Split(EmailSrv, ":")
	auth := smtp.PlainAuth("", EmailUsr, EmailPwd, hp[0])

	subject = erasebractket(subject)
	tmpsubject := subject

	subidx := 0
	for len(tmpsubject) > 0 {
		_, size := utf8.DecodeRuneInString(tmpsubject)
		if subidx+size > 70 {
			break
		}
		subidx += size
		tmpsubject = tmpsubject[size:]
	}

	subject = subject[:subidx]

	subject = strings.Replace(subject, "@", "", -1)
	subject += " @股市"

	log.Println("SendToEvernote", from, subject, to)

	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	msg := []byte("To: " + to + "\r\nFrom: " + "xhbot" + "<" + EmailUsr + ">\r\nSubject: " + encodeRFC2047(subject) + "\r\n" + "MIME-Version: 1.0\r\n" + "Content-Type: text/html; charset=UTF-8 \r\nContent-Transfer-Encoding: base64\r\n\r\n" + b64.EncodeToString([]byte(body)))
	send_to := strings.Split(to, "|")
	err := smtp.SendMail(EmailSrv, auth, EmailUsr, send_to, msg)
	return err
}
Exemple #4
0
// SignPolicy return the proper signature and other parameters needed to
// generate a valid Cloudfront Signed URL.
// For canned policies this is: Expires, Signature, Key-Pair-Id
// For custom policies this is: Policy, Signature, Key-Pair-Id
//
// More information:
//   http://goo.gl/pvA97e
// Command line equivalent:
//   cat policy | openssl sha1 -sign cloudfront-keypair.pem | openssl base64 | tr '+=/' '-_~'
func SignPolicy(privateKey PrivateKey, policy PolicySigner, keyPairID string) (string, error) {
	signature, err := policy.signWithPrivateKey(privateKey)
	if err != nil {
		return "", fmt.Errorf("Cannot sign policy: %v", err)
	}

	encoding := base64.NewEncoding(encodeCloudFront)
	paddingMap := func(r rune) rune {
		switch r {
		case '=':
			return '_'
		default:
			return r
		}
	}

	switch policy.(type) {
	case CannedPolicy:
		return fmt.Sprintf("Expires=%d&Signature=%s&Key-Pair-Id=%s",
			policy.(CannedPolicy).ExpiresAt.Unix(),
			strings.Map(paddingMap, encoding.EncodeToString(signature)),
			keyPairID,
		), nil
	case CustomPolicy:
		return fmt.Sprintf("Policy=%s&Signature=%s&Key-Pair-Id=%s",
			strings.Map(paddingMap, encoding.EncodeToString([]byte(policy.String()))),
			strings.Map(paddingMap, encoding.EncodeToString(signature)),
			keyPairID,
		), nil
	}
	return "", nil
}
Exemple #5
0
func encodeBytes(b []byte) (s string) {
	// Note that this encoding is not decodable, as we are using '0' for two different bytes.
	// This is much safer for using these as parts of file names.
	enc := base64.NewEncoding("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz0")
	s = enc.EncodeToString(b)
	return
}
Exemple #6
0
func main() {
	host := "192.168.0.243:25"

	from := mail.Address{"发件人", "*****@*****.**"}
	to := mail.Address{"收件人", "*****@*****.**"}
	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte("标题测试")))
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/html; charset=UTF-8"
	header["Content-Transfer-Encoding"] = "base64"

	body := "邮件正文"

	message := ""

	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + b64.EncodeToString([]byte(body))
	//auth := smtp.PlainAuth("", "", "", host)
	err := smtp.SendMail(host, nil, "*****@*****.**", []string{to.Address}, []byte(message))
	fmt.Println(err)
}
func (ca *ConnectionAcceptor) HandleConnection(conn net.Conn) {
	err := conn.(*tls.Conn).Handshake()
	if err != nil {
		log.Print("New connection failed during Handshake")
		log.Print(err)
	} else {
		state := conn.(*tls.Conn).ConnectionState()
		if len(state.PeerCertificates) == 0 {
			log.Print("New connection failed: no certificate present")
			conn.Close()
			return
		}
		hash := sha1.New()
		hash.Write(state.PeerCertificates[0].Raw)
		sha1hash := hash.Sum(nil)
		encoder := base64.NewEncoding("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/")
		hashstring := encoder.EncodeToString(sha1hash)
		if hashstring == ca.Myhash {
			log.Print("New admin connection")
			ca.out <- NewEvent("NewAdminConnection", conn)
		} else {
			ci := &UnauthConnectionInfo{conn, hashstring}
			event := NewEvent("NewUnauthenticatedConnection", ci)
			//log.Print("New unauthenticated connection")
			ca.out <- event
		}
	}
}
func Base64Encode(values []byte) string {
	if base64Encoding == nil {
		base64Encoding = base64.NewEncoding(base64CodeTbl)
	}

	return base64Encoding.EncodeToString(values)
}
Exemple #9
0
func genPw(master, siteName, alphabet string) (string, error) {
	if m, _ := regexp.MatchString("[^uns]+", alphabet); m {
		return "", errors.New(fmt.Sprintf("Alphabet string %s makes no sense", alphabet))
	}
	encodeString := ""

	if strings.Contains(alphabet, "u") {
		encodeString += "QWERTYUIOPASDFGHJKLZXCVBNM"
	}
	if strings.Contains(alphabet, "n") {
		encodeString += "1234567890"
	}
	if strings.Contains(alphabet, "s") {
		encodeString += "!@#$%^&*()~`{}[];:<>,.?/"
	}
	encodeString += genLowers(64 - len(encodeString))

	encoder := base64.NewEncoding(encodeString)

	c1 := sha256.Sum256([]byte(master + siteName))

	s1 := encoder.EncodeToString(c1[:12])

	return s1, nil
}
Exemple #10
0
func Base64Decode(fileContent string) (string, error) {
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	decodeBytes, err := b64.DecodeString(fileContent)
	if err != nil {
		return "", err
	}
	return string(decodeBytes), nil
}
Exemple #11
0
func randString(l int) string {
	encoding := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AB"
	b := make([]byte, l)
	rand.Read(b)
	enc := base64.NewEncoding(encoding)
	d := make([]byte, enc.EncodedLen(len(b)))
	enc.Encode(d, b)
	d = d[:l]
	return string(d)
}
Exemple #12
0
func base64Decode(data string) ([]byte, error) {
	base := base64.NewEncoding(validEncoding)
	if len(data)%4 == 1 && data[len(data)-1] == 'A' {
		return base.DecodeString(string(data[:len(data)-1]))
	}
	if len(data)%4 != 0 {
		data = data + strings.Repeat("=", (4-(len(data)%4)))
	}
	return base.DecodeString(data)
}
Exemple #13
0
func generate(secretpassword, sitename string) string {
	input := []byte(secretpassword + ":" + sitename)
	pwd := &bytes.Buffer{}
	encoder := base64.NewEncoder(base64.NewEncoding("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789?!#@&$"), pwd)
	h := sha1.New()
	h.Write(input)
	s := h.Sum(nil)
	encoder.Write(s)
	encoder.Close()
	return ensurenumberandletter(pwd.String()[:10])
}
Exemple #14
0
func main() {
	s := "Love is but a song to sing Fear's the way we die You can make the mountains ring Or make the angels cry Though the bird is on the wing And you may not know why Come on people now Smile on your brother Everybody get together Try to love one another Right now"

	encodeStd := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	s64 := base64.NewEncoding(encodeStd).EncodeToString([]byte(s))

	fmt.Println(len(s))
	fmt.Println(len(s64))
	fmt.Println(s)
	fmt.Println(s64)
}
Exemple #15
0
// Configure initializes this formatter with values from a plugin config.
func (format *Base64Decode) Configure(conf core.PluginConfig) error {
	dict := conf.GetString("Dictionary", "")
	if dict == "" {
		format.dictionary = base64.StdEncoding
	} else {
		if len(dict) != 64 {
			return fmt.Errorf("Base64 dictionary must contain 64 characters.")
		}
		format.dictionary = base64.NewEncoding(dict)
	}
	return nil
}
Exemple #16
0
func init() {
	gob.Register((*peony.Session)(nil))

	peony.OnServerInit(func(s *peony.Server) {
		sec := s.App.Security
		encoding = base64.NewEncoding(sec)
		s.RegisterSessionManager(&SimpleSessionManager{})
		CookieHttpOnly = s.App.GetBoolConfig("CookieHttpOnly", false)
		CookieSecure = s.App.GetBoolConfig("CookieSecure", false)
		SessionTimeout = s.App.GetIntConfig("SessionTimeout", 30)
	})
}
Exemple #17
0
func base64Encode(data []byte) (string, error) {
	if len(data) < 1 {
		return "", errors.New("Zero Length String")
	}
	base := base64.NewEncoding(validEncoding)
	encodedString := base.EncodeToString(data)
	if !strings.Contains(encodedString, "=") {
		encodedString += "A"
	} else {
		encodedString = strings.TrimRight(encodedString, "=")
	}
	return encodedString, nil
}
Exemple #18
0
func (this *Smtp) SendMail(from, tos, subject, body string, contentType ...string) error {
	if this.Address == "" {
		return fmt.Errorf("address is necessary")
	}

	hp := strings.Split(this.Address, ":")
	if len(hp) != 2 {
		return fmt.Errorf("address format error")
	}

	arr := strings.Split(tos, ";")
	count := len(arr)
	safeArr := make([]string, 0, count)
	for i := 0; i < count; i++ {
		if arr[i] == "" {
			continue
		}
		safeArr = append(safeArr, arr[i])
	}

	if len(safeArr) == 0 {
		return fmt.Errorf("tos invalid")
	}

	tos = strings.Join(safeArr, ";")

	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	header := make(map[string]string)
	header["From"] = from
	header["To"] = tos
	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
	header["MIME-Version"] = "1.0"

	ct := "text/plain; charset=UTF-8"
	if len(contentType) > 0 && contentType[0] == "html" {
		ct = "text/html; charset=UTF-8"
	}

	header["Content-Type"] = ct
	header["Content-Transfer-Encoding"] = "base64"

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + b64.EncodeToString([]byte(body))

	auth := smtp.PlainAuth("", this.Username, this.Password, hp[0])
	return smtp.SendMail(this.Address, auth, from, strings.Split(tos, ";"), []byte(message))
}
/**
 * getAuthHeader generates a base64 encoded auth-header value
 * which can be used in a http request to access restricted urls.
 */
func getAuthHeader(client *Client) string {
	// base64 encode the username and password
	var encoding = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	//log.Stdout(client.Username+":"+client.Password);
	var src []byte = strings.Bytes(client.Username + ":" + client.Password)
	var encodedLen int = encoding.EncodedLen(len(src))
	var dest = make([]byte, encodedLen)
	encoding.Encode(dest, src)
	var destSlice = dest[0:encodedLen]

	// convert bytes to string
	var destStr = "Basic " + bytes.NewBuffer(destSlice).String()
	return destStr
}
Exemple #20
0
func tNewEncoding() {
	base64Table := "123QRSTUabcdVWXYZHijKLAWDCABDstEFGuvwxyzGHIJklmnopqr234560178912"
	// P(len(base64Table))
	coder := base64.NewEncoding(base64Table)
	output := coder.EncodeToString(input)
	stoutput := base64.StdEncoding.EncodeToString(input)
	P(output)
	P(stoutput)

	input2, _ := coder.DecodeString(output)
	input2Std, _ := base64.StdEncoding.DecodeString(stoutput)
	P(string(input2))
	P(string(input2Std))

}
Exemple #21
0
// 发送邮件
func SendMail(conf *MailT) error {
	var (
		contentType string
		vs          string
		message     string
		toaddr      mail.Address
	)
	encode := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	host := strings.Split(conf.Addr, ":")
	auth := smtp.PlainAuth("", conf.User, conf.Pass, host[0])
	if conf.Type == "html" {
		contentType = "text/html; charset=UTF-8"
	} else {
		contentType = "text/plain; charset=UTF-8"
	}
	from := mail.Address{"CmsTop Monitor", conf.From}
	tolist := strings.Split(conf.To, ",")
	to := make([]string, 0)
	for i, addr := range tolist {
		addr = strings.TrimSpace(addr)
		tolist[i] = addr
		toaddr = mail.Address{"", tolist[i]}
		to = append(to, toaddr.String())
	}

	header := make(mail.Header)
	header["From"] = []string{from.String()}
	header["To"] = to
	header["Subject"] = []string{conf.Title}
	header["MIME-Version"] = []string{"1.0"}
	header["Content-Type"] = []string{contentType}
	header["Content-Transfer-Encoding"] = []string{"base64"}

	for k, v := range header {
		vs = strings.Join(v, ", ")
		message += fmt.Sprintf("%s: %s\r\n", k, vs)
	}
	message += "\r\n" + encode.EncodeToString([]byte(conf.Body))

	err := smtp.SendMail(
		conf.Addr,
		auth,
		from.Address,
		tolist,
		[]byte(message),
	)
	return err
}
Exemple #22
0
//发送邮件
func SendToMail(toEmail, name string) error {
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	email, _ := conf.Cfg.GetValue("email", "email")
	password, _ := conf.Cfg.GetValue("email", "passwd")
	host, _ := conf.Cfg.GetValue("email", "host")
	subject, _ := conf.Cfg.GetValue("email", "subject")
	sendName, _ := conf.Cfg.GetValue("email", "sendName")

	from := mail.Address{sendName, email}
	to := mail.Address{name, toEmail}

	hp := strings.Split(host, ":")
	auth := smtp.PlainAuth("", email, password, hp[0])

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/html; charset=UTF-8"
	header["Content-Transfer-Encoding"] = "base64"

	//获取用户信息
	userInfo, _, _ := models.GetUserInfo(name)
	EmailMd5 := GetMd5String(toEmail + name + userInfo.Passwd)
	newUser := new(models.User)
	newUser.Email_change = EmailMd5
	err := models.UpdateUser(userInfo.Id, newUser)
	if CheckError("数据库读取失败", err) {
		return err
	}
	body := `<strong>修改密码</strong>
	<p>访问以下网址:<a href="http://` + conf.HttpWeb + `/login/changePasswd?emailCode=` + EmailMd5 + `">http://` + conf.HttpWeb + `/login/changePasswd?emailCode=` + EmailMd5 + `<a><p>
	<p>如果以上链接无法访问,请将该网址复制并粘贴至新的浏览器窗口中。</p>`

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + b64.EncodeToString([]byte(body))

	send_to := strings.Split(toEmail, ";")
	err = smtp.SendMail(host, auth, email, send_to, []byte(message))
	return err
}
Exemple #23
0
// Configure initializes this formatter with values from a plugin config.
func (format *Base64Decode) Configure(conf core.PluginConfig) error {
	plugin, err := core.NewPluginWithType(conf.GetString("Base64Formatter", "format.Forward"), conf)
	if err != nil {
		return err
	}
	format.base = plugin.(core.Formatter)

	dict := conf.GetString("Base64Dictionary", "")
	if dict == "" {
		format.dictionary = base64.StdEncoding
	} else {
		if len(dict) != 64 {
			return fmt.Errorf("Base64 dictionary must contain 64 characters.")
		}
		format.dictionary = base64.NewEncoding(dict)
	}
	return nil
}
Exemple #24
0
//图片代理
func getPic(w http.ResponseWriter, req *http.Request) {
	var cacheContent *[]byte
	var err error

	req.ParseForm()
	picUrlcoded := req.Form.Get("url")
	if picUrlcoded == "" {
		w.Write([]byte("param error"))
		return
	}
	coding := base64.NewEncoding("VPQRXAZabBCDNkYcWMIist5EFLvlmnGHu34wxyz0hSTJKOdefgU6j12opqr978-_")
	picUrldecoded, err := coding.DecodeString(picUrlcoded)
	if err != nil {
		log.Println("param decode error, param coded:", picUrlcoded)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	picUrl := string(picUrldecoded)
	picUrl = strings.TrimRight(picUrl, string(0x0)) //rtrim tailing zero
	picId := getCacheId(picUrl)
	log.Println("requesting pic id:", picId)

	if !cacheExist(picId) {
		log.Println("cache miss, id:", picId)

		if err := makeCache(picUrl); err != nil {
			log.Println("make cache error, id:", picId, "error:", err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
	} else {
		log.Println("cache hit, pic id:", picId)
	}

	//读取缓存
	cacheContent, err = cacheRead(picId)
	if err != nil {
		log.Println("cache read error, id:", picId, "error:", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(*cacheContent)
	log.Println("serve pic done, id:", picId)
}
func (ca *LocalConnectAuthenticator) AuthenticateClient(payload *ConnectLocalPayload) {
	conn := payload.Conn
	port := payload.Port
	ret := make(chan *tls.Config)
	ca.Out <- NewEvent("GetTlsConfig", ret)
	conf := <-ret
	authed := tls.Server(conn, conf)
	err := authed.Handshake()
	if err != nil {
		log.Print("LocalAuth failed during Handshake")
		return
	}
	hash := sha1.New()
	hash.Write(authed.ConnectionState().PeerCertificates[0].Raw)
	sha1hash := hash.Sum(nil)
	encoder := base64.NewEncoding("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/")
	hashstring := encoder.EncodeToString(sha1hash)
	log.Print("Got new authenticated connection from " + hashstring)
	ca.Out <- NewEvent("AuthenticatedLocalClient", &AuthenticatedLocalClientPayload{authed, port, hashstring})
}
Exemple #26
0
func main() {

	flag.Parse()
	if *paramHost == "" {
		flag.PrintDefaults()
		return
	}
	defaultFrom = mail.Address{*paramFromName, *paramFromEmail}
	msgChan = make(chan *Msg, 5000)
	timeOutChan = make(chan bool)
	b64 = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	go sendMail()
	go sendMail()
	go sendMail()
	go sendMail()
	go sendMail()
	go timeOut()

	beego.RegisterController("/", &SendMailController{})
	beego.Run()
}
Exemple #27
0
// Decrypts a byte slice and returns the unencrypted byte slice.
func Decrypt(data []byte, keys string) (decrypted []byte, err error) {
	var (
		tempdec = make([]byte, blockSize)
		block   cipher.Block
		iv      []byte
		key     []byte
	)
	if err != nil {
		return decrypted, err
	}

	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")

	iv = make([]byte, blockSize)
	b64.Encode(iv, []byte("wombatwombat"))
	fmt.Println("iv", string(iv))

	key = make([]byte, base64.StdEncoding.EncodedLen(len(keys)))
	b64.Encode(key, []byte(keys))
	fmt.Println("key", string(key))

	block, err = aes.NewCipher(key)
	if err != nil {
		return decrypted, err
	}

	mode := cipher.NewCBCDecrypter(block, []byte(iv))

	fmt.Println(data)

	for i := 0; i < len(data)/blockSize; i++ {
		mode.CryptBlocks(tempdec, data[i*blockSize:i*blockSize+blockSize])
		fmt.Println(tempdec)
		decrypted = append(decrypted, tempdec...)
	}
	fmt.Println(decrypted)
	unpadded, err := padding.Unpad(decrypted, blockSize)
	return unpadded, err
}
func NewConnectionAcceptor(capacity int) *ConnectionAcceptor {
	ca := new(ConnectionAcceptor)
	ca.in = make(chan *Event, capacity)
	ca.out = make(chan *Event, capacity)
	err := ca.LoadKeys()
	if err != nil {
		return nil
	}

	go func() {
		ret := make(chan int)
		ca.out <- NewEvent("GetPort", ret)
		port := <-ret
		listener, err := tls.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port), &ca.Tlsconfig)
		port = listener.Addr().(*net.TCPAddr).Port
		log.Print("ConnectionAcceptor is up and running on port " + strconv.Itoa(port))
		if err != nil {
			log.Print("ConnectionAcceptor failed to start... is the port busy?")
			return
		}
		go ca.ServeEventRequests()
		hash := sha1.New()
		hash.Write(ca.Tlsconfig.Certificates[0].Certificate[0])
		sha1hash := hash.Sum(nil)
		encoder := base64.NewEncoding("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/")
		ca.Myhash = encoder.EncodeToString(sha1hash)
		log.Print("Our certhash is " + ca.Myhash)
		for {
			conn, err := listener.Accept()
			if err != nil {
				log.Print("ConnectionAcceptor failed to accept...")
				break
			}
			//log.Print("Accepted new socket")
			go ca.HandleConnection(conn)
		}
	}()
	return ca
}
Exemple #29
0
func (s *_SmtpSender) sendMail(c client, subject string, mail_body *template.Template, receivers []mail.Address, args map[string]interface{}) (err error) {
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	var standard_header_template *template.Template

	if standard_header_template, err = template.New("standard_header").Parse(StandardHeader); err == nil {
		if err = c.Auth(smtpoverttl.PlainAuth("", *s.User, *s.Pwd, *s.Server)); err == nil {
			for _, receiver := range receivers {
				if err = c.Mail(*s.User); err == nil {
					if err = c.Rcpt(receiver.Address); err == nil {
						// Send the email body.
						var wc io.WriteCloser
						if wc, err = c.Data(); err == nil {
							defer wc.Close()

							from := mail.Address{*s.UserName, *s.User}

							body_writer := new(bytes.Buffer)
							if err = mail_body.Execute(body_writer, args); err != nil {
								return
							}

							if err = standard_header_template.Execute(wc, map[string]string{
								"Receiver": receiver.String(),
								"Sender":   from.String(),
								"Body":     b64.EncodeToString(body_writer.Bytes()),
								"Subject":  fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject))),
							}); err != nil {
								return
							}
						}
					}
				}
			}
		}
	}
	return
}
Exemple #30
0
func dns(username string, password string, domain string, ip string) string {
	//base64
	Authorization := username + ":" + password
	encodeStd := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	var en *base64.Encoding = base64.NewEncoding(encodeStd)
	var buf *bytes.Buffer = bytes.NewBufferString(Authorization)
	enS := en.EncodeToString(buf.Bytes())

	//http request and header
	url := fmt.Sprintf("http://ddns.oray.com/ph/update?hostname=%s&myip=%s", domain, ip)
	requ, _ := http.NewRequest("GET", url, nil)
	requ.Header.Add("Authorization", "Basic "+enS)
	requ.Header.Add("User-Agent", "FUCKALL")

	client := new(http.Client)
	resp, _ := client.Do(requ)
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	buf = bytes.NewBuffer(body)
	bufS := buf.String()
	return bufS
}