This repository has been archived on 2024-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
m3tam3re.com/content/posts/password-encrypt-go.en.md
2023-10-12 14:01:05 +02:00

34 lines
1.1 KiB
Markdown

---
title: "Encrypt passwords with Go"
date: 2020-02-26
draft: false
tags: ["programming","golang","go","crypt","snippets"]
---
Go already has many helpful packages from the start. One of them is the bcrypt package with which e.g. will encrypt passwords securely.
```go
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
pw := "SecretPassword"
bs, err := bcrypt.GenerateFromPassword([]byte(pw), 2)
//let's look at the encrypted password
fmt.Printf("encryption result: %s\n", string(bs))
err = bcrypt.CompareHashAndPassword(bs, []byte(pw))
if err != nil {
fmt.Println("Wrong! Wrong! Wrong!")
}
}
```
[Try it out](https://play.golang.org/p/jxoTHhAPQ5G)
We pass our password to the function GenerateFromPassword([]byte(pw), 2) as a slice of byte. The second argument is the cost for the encryption as an integer. The higher the costs the longer the encryption will take. The encryption will also be more secure if calculated with a higher cost value. If we pass a 0 bcrypt will use a standard value for the cost.
Pretty easy so far 😊