Mackenzie Quigley
Mackenzie Quigley

Reputation: 75

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

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!

Upvotes: 2

Views: 2549

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51467

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.

Upvotes: 7

Related Questions