在Golang中使用UTF-8加密字符串以放入PostgreSQL中。

huangapple go评论80阅读模式
英文:

Encrypt String in Golang in UTF-8 to put in postgres

问题

我正在使用Go语言中的加密功能,通过密码和口令对密码进行加密,然后将其以字符串形式存储在PostgreSQL数据库中。加密本身没有问题,但是当我尝试将其添加到数据库时,出现了一个错误,似乎是由于从[]byte类型转换为string类型导致加密的密码出错。

当我运行这段代码并尝试在数据库中添加行时,出现以下错误:

ERROR #22021 invalid byte sequence for encoding "UTF8"

我只是想在Go语言中找到一种简单的方法来加密字符串密码,并将加密后的字符串保存到PostgreSQL的表中。表中的列类型为VARCHAR,但如果有必要,我也可以更改该类型。谢谢!

英文:

I am using crypto in go to take a password and use a passphrase to encrypt the password and then store it as a string in a postgres sql database. The encryption works fine but when I try to add it to my database I get an error that seems to indicate that going from a []byte to a string type messes up the encrypted password.

func Encrypt(password string, passphrase string) string {
	data := []byte(password)
	block, _ := aes.NewCipher([]byte(createHash(passphrase)))
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}
	nonce := make([]byte, gcm.NonceSize())
	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
		panic(err.Error())
	}
	ciphertext := gcm.Seal(nonce, nonce, data, nil)
	return string(ciphertext)
}

func createHash(key string) string {
	hasher := md5.New()
	hasher.Write([]byte(key))
	return hex.EncodeToString(hasher.Sum(nil))
}

When I run this code and try to add the row in the database I get the error

ERROR #22021 invalid byte sequence for encoding "UTF8"

I am just looking for an easy way in go to encrypt a string password and save the encrypted string into a table in postgres. The column in the table is of type VARCHAR but I am willing to change that as well if that is for some reason the issue. Thanks for your time!

答案1

得分: 6

将其进行Base64编码:

return base64.StdEncoding.EncodeToString(ciphertext)

尽管字符串是一个字节数组,但并不是所有的字节序列都是有效的UTF-8字符串。Base64编码通常用于将二进制数据存储为文本。

英文:

Base64 encode it:

return base64.StdEncoding.EncodeToString(ciphertext)

Even though a string is a byte array, not all sequences of bytes are a valid UTF-8 string. Base64 encoding is commonly used to store binary data as text.

huangapple
  • 本文由 发表于 2021年6月19日 05:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/68041548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定