Skip to content

Commit

Permalink
Merge pull request #49 from elisasre/adderror
Browse files Browse the repository at this point in the history
add error to decrypt+encrypt
  • Loading branch information
zetaab authored Apr 25, 2023
2 parents 43a9fc8 + b0c4ed2 commit 1f74029
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
18 changes: 9 additions & 9 deletions crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,36 +33,36 @@ func createHash(key string) string {

// Encrypt the secret input with passphrase
// source https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/
func Encrypt(data []byte, passphrase string) []byte {
func Encrypt(data []byte, passphrase string) ([]byte, error) {
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
return ciphertext, nil
}

// Decrypt the encrypted secret with passphrase.
func Decrypt(data []byte, passphrase string) []byte {
func Decrypt(data []byte, passphrase string) ([]byte, error) {
key := []byte(createHash(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
return nil, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
return nil, err
}
return plaintext
return plaintext, nil
}
10 changes: 6 additions & 4 deletions crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ func ExampleBase64encode() {
}

func ExampleEncrypt() {
encrypted := Encrypt([]byte("supersecret"), "testpassword")
fmt.Println(string(Decrypt(encrypted, "testpassword")))
encrypted, _ := Encrypt([]byte("supersecret"), "testpassword")
data, _ := Decrypt(encrypted, "testpassword")
fmt.Println(string(data))
// Output: supersecret
}

func ExampleDecrypt() {
encrypted := Encrypt([]byte("supersecret"), "testpassword")
fmt.Println(string(Decrypt(encrypted, "testpassword")))
encrypted, _ := Encrypt([]byte("supersecret"), "testpassword")
data, _ := Decrypt(encrypted, "testpassword")
fmt.Println(string(data))
// Output: supersecret
}

0 comments on commit 1f74029

Please sign in to comment.