Skip to content

Instantly share code, notes, and snippets.

@karl-gustav
Created September 25, 2022 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karl-gustav/a686eac5585a08ecc55a00960902e338 to your computer and use it in GitHub Desktop.
Save karl-gustav/a686eac5585a08ecc55a00960902e338 to your computer and use it in GitHub Desktop.
AES encryption and decryption with password
// based on https://github.com/isfonzar/filecrypt/blob/master/filecrypt.go
func encryptAES(password, plaintext string) (string, error) {
key := []byte(password)
nonce := make([]byte, 12)
// Randomizing the nonce
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("io.ReadFull(...): %w)", err)
}
dk := pbkdf2.Key(key, nonce, 4096, 32, sha1.New)
block, err := aes.NewCipher(dk)
if err != nil {
return "", fmt.Errorf("encrypt aes.NewCipher(dk): %w", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("encrypt cipher.NewGCM(block): %w", err)
}
cipherText := aesGCM.Seal(nil, nonce, []byte(plaintext), nil)
// Append the nonce to the end of file
cipherText = append(cipherText, nonce...)
return base64.StdEncoding.EncodeToString(cipherText), nil
}
func decryptAES(password, encryptedText string) (string, error) {
cipherText, err := base64.StdEncoding.DecodeString(encryptedText)
if err != nil {
return "", fmt.Errorf("base64.StdEncoding.DecodeString(...): %w", err)
}
key := []byte(password)
salt := cipherText[len(cipherText)-12:]
str := hex.EncodeToString(salt)
nonce, err := hex.DecodeString(str)
if err != nil {
return "", fmt.Errorf("hex.DecodeString(str): %w", err)
}
dk := pbkdf2.Key(key, nonce, 4096, 32, sha1.New)
block, err := aes.NewCipher(dk)
if err != nil {
return "", fmt.Errorf("decrypt aes.NewCipher(dk): %w", err)
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("decrypt cipher.NewGCM(block): %w", err)
}
plaintext, err := aesGCM.Open(nil, nonce, cipherText[:len(cipherText)-12], nil)
if err != nil {
return "", fmt.Errorf("aesgcm.Open(...): %w", err)
}
return string(plaintext), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment