Skip to content

Instantly share code, notes, and snippets.

@Dank-del
Last active December 6, 2022 10:48
Show Gist options
  • Select an option

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

Select an option

Save Dank-del/2b7cc3877127b7d5639dd78ad9673dbb to your computer and use it in GitHub Desktop.
Encrypt and Decrypt Strings :) no byte return/input types involved
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"log"
)
func main() {
// Encrypt string
secretKey := "mysecretkey12345"
str := "I love go"
encryptedStr := encrypt(secretKey, str)
fmt.Printf("Encrypted string: %s\n", encryptedStr)
// Decrypt encrypted string
decryptedStr := decrypt(secretKey, encryptedStr)
fmt.Printf("Decrypted string: %s\n", decryptedStr)
}
func encrypt(key, text string) string {
plaintext := []byte(text)
block, err := aes.NewCipher([]byte(key))
keyBytes := []byte(key)
if len(key) < block.BlockSize() {
keyBytes = append(keyBytes, make([]byte, block.BlockSize()-len(key))...)
} else if len(key) > block.BlockSize() {
keyBytes = keyBytes[:block.BlockSize()]
} // Once the key has the correct length, the aes.NewCipher function should be able to initialize the AES cipher without returning an error.
key = string(keyBytes)
if err != nil {
log.Println(err)
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
log.Println(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// Encode encrypted value to base64
// (note: this is not secure, but is used for simplicity in this example)
return base64.StdEncoding.EncodeToString(ciphertext)
}
func decrypt(key, encrypted string) string {
// Decode encrypted value from base64
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
panic(err)
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
panic(err)
}
if len(ciphertext) < aes.BlockSize {
panic("encrypted string too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
return string(ciphertext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment