working commit
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
package cm509
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
func EncryptAES256(b64data string, key string) (string, error) {
|
||||
var res string
|
||||
var err error
|
||||
|
||||
const aes256KeyLen = 32
|
||||
|
||||
bKey := []byte(key)
|
||||
keyLen := len(bKey)
|
||||
switch {
|
||||
case keyLen > aes256KeyLen:
|
||||
bKey = bKey[:aes256KeyLen]
|
||||
case keyLen < aes256KeyLen:
|
||||
padding := make([]byte, aes256KeyLen-keyLen)
|
||||
bKey = append(bKey, padding...)
|
||||
case keyLen == 0:
|
||||
return res, fmt.Errorf("Zero lenght key")
|
||||
}
|
||||
|
||||
data, err := base64.StdEncoding.DecodeString(b64data)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(bKey)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
nonce := make([]byte, 12)
|
||||
_, err = io.ReadFull(rand.Reader, nonce)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
ciphertext := aesgcm.Seal(nil, nonce, data, nil)
|
||||
ciphertext = append(nonce, ciphertext...)
|
||||
|
||||
res = base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
return res, err
|
||||
|
||||
}
|
||||
|
||||
func DecryptAES256(b64ciphertext string, key string) (string, error) {
|
||||
var res string
|
||||
var err error
|
||||
|
||||
const aes256KeyLen = 32
|
||||
|
||||
bKey := []byte(key)
|
||||
keyLen := len(bKey)
|
||||
switch {
|
||||
case keyLen > aes256KeyLen:
|
||||
bKey = bKey[:aes256KeyLen]
|
||||
case keyLen < aes256KeyLen:
|
||||
padding := make([]byte, aes256KeyLen-keyLen)
|
||||
bKey = append(bKey, padding...)
|
||||
case keyLen == 0:
|
||||
return res, fmt.Errorf("Zero lenght key")
|
||||
}
|
||||
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(b64ciphertext)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(bKey)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
nonceSize := aesgcm.NonceSize()
|
||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
|
||||
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
res = base64.StdEncoding.EncodeToString(plaintext)
|
||||
return res, err
|
||||
}
|
||||
Reference in New Issue
Block a user