initial commit
This commit is contained in:
39
internal/protectString/decrypt.go
Normal file
39
internal/protectString/decrypt.go
Normal file
@ -0,0 +1,39 @@
|
||||
package protectString
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func Decrypt(encryptedString string, keyString string) (decryptedString string) {
|
||||
key, _ := hex.DecodeString(keyString)
|
||||
enc, _ := hex.DecodeString(encryptedString)
|
||||
|
||||
//Create a new Cipher Block from the key
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
//Create a new GCM
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
//Get the nonce size
|
||||
nonceSize := aesGCM.NonceSize()
|
||||
|
||||
//Extract the nonce from the encrypted data
|
||||
nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
|
||||
|
||||
//Decrypt the data
|
||||
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s", plaintext)
|
||||
}
|
37
internal/protectString/encrypt.go
Normal file
37
internal/protectString/encrypt.go
Normal file
@ -0,0 +1,37 @@
|
||||
package protectString
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
func Encrypt(stringToEncrypt string, keyString string) (encryptedString string) {
|
||||
key, _ := hex.DecodeString(keyString)
|
||||
plaintext := []byte(stringToEncrypt)
|
||||
|
||||
//Create a new Cipher Block from the key
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
//Create a new GCM
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
//Create a nonce. Nonce should be from GCM
|
||||
nonce := make([]byte, aesGCM.NonceSize())
|
||||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
//Encrypt the data using aesGCM.Seal
|
||||
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
|
||||
return fmt.Sprintf("%x", ciphertext)
|
||||
}
|
Reference in New Issue
Block a user