package encry import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "fmt" "io" "log" "golang.org/x/crypto/pbkdf2" ) func Encrypting(jsonData []byte) (encryptedData string) { encryptedData, err := EncryptAES256(jsonData, secretKey) if err != nil { log.Fatalf("failed to encrypt data: %v", err) } return encryptedData } var secretKey = []byte("icomsys1234") func pkcs7Padding(data []byte, blockSize int) []byte { padding := blockSize - len(data)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(data, padtext...) } func pkcs7Unpadding(data []byte) ([]byte, error) { length := len(data) if length == 0 { return nil, fmt.Errorf("invalid padding size") } padding := int(data[length-1]) if padding > length { return nil, fmt.Errorf("invalid padding size") } return data[:length-padding], nil } func EncryptAES256(plaintext []byte, passphrase []byte) (string, error) { key := pbkdf2.Key(passphrase, []byte("salt"), 4096, 32, sha256.New) block, err := aes.NewCipher(key) if err != nil { return "", err } plaintext = pkcs7Padding(plaintext, aes.BlockSize) ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", err } stream := cipher.NewCBCEncrypter(block, iv) stream.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) return base64.URLEncoding.EncodeToString(ciphertext), nil } func DecryptAES256(ciphertext string, passphrase []byte) ([]byte, error) { key := pbkdf2.Key(passphrase, []byte("salt"), 4096, 32, sha256.New) decoded, err := base64.URLEncoding.DecodeString(ciphertext) if err != nil { return nil, err } block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(decoded) < aes.BlockSize { return nil, fmt.Errorf("ciphertext too short") } iv := decoded[:aes.BlockSize] decoded = decoded[aes.BlockSize:] stream := cipher.NewCBCDecrypter(block, iv) stream.CryptBlocks(decoded, decoded) decoded, err = pkcs7Unpadding(decoded) if err != nil { return nil, err } return decoded, nil }