Created
August 31, 2024 13:38
-
-
Save chilljello/61f0533da5c5ef5562a7101b1fae3953 to your computer and use it in GitHub Desktop.
enc and decryp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Decrypt decrypts the ciphertext using AES with the given key | |
func Decrypt(ciphertext, key string) (string, error) { | |
// Convert the key and ciphertext to byte arrays | |
keyBytes := []byte(key) | |
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext) | |
if err != nil { | |
return "", err | |
} | |
// Create a new AES cipher | |
block, err := aes.NewCipher(keyBytes) | |
if err != nil { | |
return "", err | |
} | |
// Create a GCM mode cipher | |
gcm, err := cipher.NewGCM(block) | |
if err != nil { | |
return "", err | |
} | |
// Separate nonce and ciphertext | |
nonce, ciphertextBytes := ciphertextBytes[:gcm.NonceSize()], ciphertextBytes[gcm.NonceSize():] | |
// Decrypt the ciphertext | |
decrypted, err := gcm.Open(nil, nonce, ciphertextBytes, nil) | |
if err != nil { | |
return "", err | |
} | |
// Remove padding | |
padding := decrypted[len(decrypted)-1] | |
if int(padding) > aes.BlockSize || int(padding) > len(decrypted) { | |
return "", fmt.Errorf("invalid padding") | |
} | |
decrypted = decrypted[:len(decrypted)-int(padding)] | |
return string(decrypted), nil | |
} | |
// Encrypt encrypts the plaintext using AES with the given key | |
func Encrypt(plaintext, key string) (string, error) { | |
// Convert the key to a byte array | |
keyBytes := []byte(key) | |
// Create a new AES cipher | |
block, err := aes.NewCipher(keyBytes) | |
if err != nil { | |
return "", err | |
} | |
// Ensure plaintext is a multiple of the block size | |
padding := aes.BlockSize - len(plaintext)%aes.BlockSize | |
padtext := []byte(plaintext) | |
padtext = append(padtext, bytes.Repeat([]byte{byte(padding)}, padding)...) | |
// Create a GCM mode cipher | |
gcm, err := cipher.NewGCM(block) | |
if err != nil { | |
return "", err | |
} | |
// Generate a nonce | |
nonce := make([]byte, gcm.NonceSize()) | |
// Encrypt the plaintext | |
ciphertext := gcm.Seal(nonce, nonce, padtext, nil) | |
// Return base64 encoded ciphertext | |
return base64.StdEncoding.EncodeToString(ciphertext), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment