Created
June 8, 2023 06:11
-
-
Save cod3smith/f0751a8b491141dcd81836c1c61c42fe to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"crypto/aes" | |
"crypto/cipher" | |
"crypto/rand" | |
"encoding/base64" | |
"fmt" | |
"io" | |
) | |
func encrypt(plainText []byte, key []byte) ([]byte, error) { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
return nil, err | |
} | |
// Generate a random IV (Initialization Vector) | |
iv := make([]byte, aes.BlockSize) | |
if _, err := io.ReadFull(rand.Reader, iv); err != nil { | |
return nil, err | |
} | |
// Create a new cipher block mode with the block and IV | |
cipherText := make([]byte, aes.BlockSize+len(plainText)) | |
copy(cipherText[:aes.BlockSize], iv) | |
cfb := cipher.NewCFBEncrypter(block, iv) | |
cfb.XORKeyStream(cipherText[aes.BlockSize:], plainText) | |
return cipherText, nil | |
} | |
func decrypt(cipherText []byte, key []byte) ([]byte, error) { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
return nil, err | |
} | |
// Extract the IV from the cipher text | |
iv := cipherText[:aes.BlockSize] | |
cipherText = cipherText[aes.BlockSize:] | |
// Create a new cipher block mode with the block and IV | |
cfb := cipher.NewCFBDecrypter(block, iv) | |
// Decrypt the cipher text | |
plainText := make([]byte, len(cipherText)) | |
cfb.XORKeyStream(plainText, cipherText) | |
return plainText, nil | |
} | |
func main() { | |
// Encryption key (must be 16, 24, or 32 bytes) | |
key := []byte("0123456789abcdef") | |
// Plain text to encrypt | |
plainText := []byte("Hello, world!") | |
// Encrypt the plain text | |
cipherText, err := encrypt(plainText, key) | |
if err != nil { | |
fmt.Println("Encryption error:", err) | |
return | |
} | |
// Convert the cipher text to a base64-encoded string | |
cipherTextBase64 := base64.StdEncoding.EncodeToString(cipherText) | |
fmt.Println("Cipher text (Base64):", cipherTextBase64) | |
// Decrypt the cipher text | |
decryptedText, err := decrypt(cipherText, key) | |
if err != nil { | |
fmt.Println("Decryption error:", err) | |
return | |
} | |
fmt.Println("Decrypted text:", string(decryptedText)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment