-
-
Save byBretema/2b36b5df6fde62194579323651833ac4 to your computer and use it in GitHub Desktop.
GoLang Encrypt string to base64 and vice versa using AES encryption.
This file contains 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" | |
"log" | |
) | |
func main() { | |
// original text | |
oText := "TEST TEXT TO TEST" | |
fmt.Printf("Orig text:\t%v\n", oText) | |
// key (only for test :)) | |
key := []byte("SuperDuperKey_16") | |
// encrypt string to base64 | |
cText := encrypt(key, oText) | |
fmt.Printf("Crypt text:\t%v\n", cText) | |
// decrypt base64 to string | |
dText := decrypt(key, cText) | |
fmt.Printf("DeCrypt text:\t%v\n", dText) | |
} | |
/// | |
/// encrypt string to base64 crypto using AES | |
/// | |
func encrypt(key []byte, text string) string { | |
// Cast plain string to a slice of bytes | |
plaintext := []byte(text) | |
// Cipher obj that uses passed key as... key | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
log.Print(err) | |
} | |
// Prepare to store cipher text | |
ciphertext := make([]byte, aes.BlockSize+len(plaintext)) | |
// Fill with random numbers, using rand pkg, not math pkg | |
iv := ciphertext[:aes.BlockSize] | |
if _, err := io.ReadFull(rand.Reader, iv); err != nil { | |
log.Print(err) | |
} | |
// ENCRYPTION | |
stream := cipher.NewCFBEncrypter(block, iv) | |
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) | |
// Return as base64 | |
return base64.URLEncoding.EncodeToString(ciphertext) | |
} | |
/// | |
/// decrypt from base64 to decrypted string | |
/// | |
func decrypt(key []byte, cryptoText string) string { | |
// Interpret the Base64 encode of a gived string as []byte | |
ciphertext, err := base64.URLEncoding.DecodeString(cryptoText) | |
if err != nil { | |
log.Print(err) | |
} | |
if len(ciphertext) < aes.BlockSize { | |
log.Print("Ciphertext is too short!") | |
} | |
// Cipher obj that uses passed key as... key | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
log.Print(err) | |
} | |
// Prepare slices for decryption process, notice the colons | |
iv := ciphertext[:aes.BlockSize] //< Must be first, unmodified Rside | |
ciphertext = ciphertext[aes.BlockSize:] //< Must be second, modify Lside | |
// DECRYPTION | |
stream := cipher.NewCFBDecrypter(block, iv) | |
stream.XORKeyStream(ciphertext, ciphertext) | |
// Return as string | |
return fmt.Sprintf("%s", ciphertext) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment