Skip to content

Instantly share code, notes, and snippets.

@Dank-del
Created December 5, 2022 18:14
Show Gist options
  • Select an option

  • Save Dank-del/adcc8b1432dad25695150faf44d7aec1 to your computer and use it in GitHub Desktop.

Select an option

Save Dank-del/adcc8b1432dad25695150faf44d7aec1 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
// Generate a random key
key := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
}
// Encrypt a string
ciphertext, err := encrypt("hello", key)
if err != nil {
panic(err)
}
// Print the encrypted string
fmt.Printf("Encrypted string: %x\n", ciphertext)
// Decrypt the encrypted string
original, err := decrypt(ciphertext, key)
if err != nil {
panic(err)
}
// Print the original string
fmt.Printf("Original string: %s\n", original)
}
func encrypt(plaintext string, key []byte) ([]byte, error) {
// Create a new block cipher
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Pad the plaintext to a multiple of the block size
padLen := aes.BlockSize - len(plaintext)%aes.BlockSize
padText := plaintext + string(make([]byte, padLen))
// Encrypt the padded plaintext
ciphertext := make([]byte, len(padText))
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, []byte(padText))
// Return the encrypted string
return append(iv, ciphertext...), nil
}
func decrypt(ciphertext []byte, key []byte) (string, error) {
// Create a new block cipher
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// Decrypt the ciphertext
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// Remove the padding from the plaintext
padLen := int(ciphertext[len(ciphertext)-1])
plaintext := ciphertext[:len(ciphertext)-padLen]
// Return the original string
return string(plaintext), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment