Unbewohnte
4 years ago
9 changed files with 212 additions and 46 deletions
@ -0,0 +1,30 @@
|
||||
package encryption |
||||
|
||||
import ( |
||||
"crypto/aes" |
||||
"crypto/cipher" |
||||
"fmt" |
||||
) |
||||
|
||||
// Decrypts encrypted aes data with given key.
|
||||
// https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/ - very grateful to the author, THANK YOU.
|
||||
func Decrypt(key, dataToDecrypt []byte) ([]byte, error) { |
||||
block, err := aes.NewCipher(key) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not create new AES cipher: %s", err) |
||||
} |
||||
|
||||
aesGCM, err := cipher.NewGCM(block) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not create new GCM: %s", err) |
||||
} |
||||
|
||||
nonce, encryptedBytes := dataToDecrypt[:aesGCM.NonceSize()], dataToDecrypt[aesGCM.NonceSize():] |
||||
|
||||
decryptedData, err := aesGCM.Open(nil, nonce, encryptedBytes, nil) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not decrypt given data: %s", err) |
||||
} |
||||
|
||||
return decryptedData, nil |
||||
} |
@ -0,0 +1,24 @@
|
||||
package encryption |
||||
|
||||
import ( |
||||
"crypto/aes" |
||||
"crypto/cipher" |
||||
"fmt" |
||||
) |
||||
|
||||
// Encrypts given data using aes encryption.
|
||||
// https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/ - very grateful to the author, THANK YOU.
|
||||
func Encrypt(key, dataToEncrypt []byte) ([]byte, error) { |
||||
block, err := aes.NewCipher(key) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not create new AES cipher: %s", err) |
||||
} |
||||
aesGCM, err := cipher.NewGCM(block) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not create new GCM: %s", err) |
||||
} |
||||
nonce := make([]byte, aesGCM.NonceSize()) |
||||
encryptedData := aesGCM.Seal(nonce, nonce, dataToEncrypt, nil) |
||||
|
||||
return encryptedData, nil |
||||
} |
@ -0,0 +1,27 @@
|
||||
package encryption |
||||
|
||||
import ( |
||||
"math/rand" |
||||
"time" |
||||
) |
||||
|
||||
// using aes256, so 32 bytes-long key
|
||||
const KEYLEN uint = 32 |
||||
const CHARS string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" |
||||
|
||||
// Generates 32 pseudo-random bytes to use as a key
|
||||
func Generate32AESkey() []byte { |
||||
var generatedKey []byte |
||||
|
||||
rand.Seed(time.Now().UTC().UnixNano()) |
||||
// choosing "random" 32 bytes from CHARS
|
||||
for { |
||||
if len(generatedKey) == int(KEYLEN) { |
||||
break |
||||
} |
||||
randomIndex := rand.Intn(len(CHARS)) |
||||
generatedKey = append(generatedKey, CHARS[randomIndex]) |
||||
} |
||||
|
||||
return generatedKey |
||||
} |
Loading…
Reference in new issue