-
-
Save aereal/dd7093fdfe51f5c95bc0fea2bb8d5dea to your computer and use it in GitHub Desktop.
generate scram-sha256-encoded password for PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"encoding/base64" | |
"errors" | |
"fmt" | |
"io" | |
"log/slog" | |
"os" | |
"github.com/xdg-go/scram" | |
) | |
func do() error { | |
salt := make([]byte, 16) | |
if _, err := io.ReadFull(rand.Reader, salt); err != nil && !errors.Is(err, io.EOF) { | |
return fmt.Errorf("io.ReadFull: %w", err) | |
} | |
client, err := scram.SHA256.NewClient("", "password", "") | |
if err != nil { | |
return fmt.Errorf("scram.SHA256.NewClient: %w", err) | |
} | |
creds := client.GetStoredCredentials(scram.KeyFactors{Iters: 4096, Salt: string(salt)}) | |
slog.Info("generated credentials", slog.String("salt", creds.Salt), slog.String("server_key", string(creds.ServerKey)), slog.String("stored_key", string(creds.StoredKey)), slog.String("encoded_password", encodePassword(creds))) | |
return nil | |
} | |
func encodePassword(creds scram.StoredCredentials) string { | |
return fmt.Sprintf("SCRAM-SHA-256$%d:%s$%s:%s", | |
creds.Iters, | |
base64.StdEncoding.EncodeToString([]byte(creds.Salt)), | |
base64.StdEncoding.EncodeToString(creds.StoredKey), | |
base64.StdEncoding.EncodeToString(creds.ServerKey), | |
) | |
} | |
func main() { | |
os.Exit(run()) | |
} | |
func run() int { | |
if err := do(); err != nil { | |
slog.Error("failure", slog.Group("error", slog.String("message", err.Error()))) | |
status := 1 | |
if hasCode, ok := err.(interface{ ExitCode() int }); ok { | |
status = hasCode.ExitCode() | |
} | |
return status | |
} | |
return 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment