@@ -3,12 +3,14 @@ package crypto
33import (
44 "crypto/aes"
55 "crypto/cipher"
6+ "crypto/rand"
7+ "io"
68
79 "github.com/authorizerdev/authorizer/server/constants"
810 "github.com/authorizerdev/authorizer/server/envstore"
911)
1012
11- var bytes = []byte {35 , 46 , 57 , 24 , 85 , 35 , 24 , 74 , 87 , 35 , 88 , 98 , 66 , 32 , 14 , 05 }
13+ var bytes = []byte {35 , 46 , 57 , 24 , 85 , 35 , 24 , 74 , 87 , 35 , 88 , 98 , 66 , 32 , 14 , 0o5 }
1214
1315// EncryptAES method is to encrypt or hide any classified text
1416func EncryptAES (text string ) (string , error ) {
@@ -40,3 +42,67 @@ func DecryptAES(text string) (string, error) {
4042 cfb .XORKeyStream (plainText , []byte (cipherText ))
4143 return string (plainText ), nil
4244}
45+
46+ // EncryptAESEnv encrypts data using AES algorithm
47+ // kept for the backward compatibility of env data encryption
48+ func EncryptAESEnv (text []byte ) ([]byte , error ) {
49+ key := []byte (envstore .EnvStoreObj .GetStringStoreEnvVariable (constants .EnvKeyEncryptionKey ))
50+ c , err := aes .NewCipher (key )
51+ var res []byte
52+ if err != nil {
53+ return res , err
54+ }
55+
56+ // gcm or Galois/Counter Mode, is a mode of operation
57+ // for symmetric key cryptographic block ciphers
58+ // - https://en.wikipedia.org/wiki/Galois/Counter_Mode
59+ gcm , err := cipher .NewGCM (c )
60+ if err != nil {
61+ return res , err
62+ }
63+
64+ // creates a new byte array the size of the nonce
65+ // which must be passed to Seal
66+ nonce := make ([]byte , gcm .NonceSize ())
67+ // populates our nonce with a cryptographically secure
68+ // random sequence
69+ if _ , err = io .ReadFull (rand .Reader , nonce ); err != nil {
70+ return res , err
71+ }
72+
73+ // here we encrypt our text using the Seal function
74+ // Seal encrypts and authenticates plaintext, authenticates the
75+ // additional data and appends the result to dst, returning the updated
76+ // slice. The nonce must be NonceSize() bytes long and unique for all
77+ // time, for a given key.
78+ return gcm .Seal (nonce , nonce , text , nil ), nil
79+ }
80+
81+ // DecryptAES decrypts data using AES algorithm
82+ // Kept for the backward compatibility of env data decryption
83+ func DecryptAESEnv (ciphertext []byte ) ([]byte , error ) {
84+ key := []byte (envstore .EnvStoreObj .GetStringStoreEnvVariable (constants .EnvKeyEncryptionKey ))
85+ c , err := aes .NewCipher (key )
86+ var res []byte
87+ if err != nil {
88+ return res , err
89+ }
90+
91+ gcm , err := cipher .NewGCM (c )
92+ if err != nil {
93+ return res , err
94+ }
95+
96+ nonceSize := gcm .NonceSize ()
97+ if len (ciphertext ) < nonceSize {
98+ return res , err
99+ }
100+
101+ nonce , ciphertext := ciphertext [:nonceSize ], ciphertext [nonceSize :]
102+ plaintext , err := gcm .Open (nil , nonce , ciphertext , nil )
103+ if err != nil {
104+ return res , err
105+ }
106+
107+ return plaintext , nil
108+ }
0 commit comments