Go: how to encrypt and decrypt a string

Go: how to encrypt and decrypt a string

Go is a programming language that offers a very powerful standard library to handle the encryption and decryption of strings securely. In this article, we'll explore how to do these things using Go.

String encryption and decryption are crucial operations for ensuring the security of sensitive information. Go is a programming language that offers a very powerful standard library to handle the encryption and decryption of strings securely. In this article, we'll explore how to do these things using Go.

To start encrypting and decrypting a string in Go, we need to import the crypto package which provides numerous encryption functions and algorithms. Let's make sure to import the necessary package into our program:


import (
     "crypto/aes"
     "crypto/cipher"
     "crypto/rand"
     "errors"
     "I"
)

To encrypt a string in Go, we will use the AES (Advanced Encryption Standard) encryption algorithm with a secret key. Here's how to encrypt a string:


func EncryptString(key []byte, plaintext string) (string, error) {
     block, err := aes.NewCipher(key)
     if err != nil {
         return "", err
     }

     plaintextBytes := []byte(plaintext)
     ciphertext := make([]byte, aes.BlockSize+len(plaintextBytes))

     iv := ciphertext[:aes.BlockSize]
     if _, err := io.ReadFull(rand.Reader, iv); err != nil {
         return "", err
     }

     stream := cipher.NewCFBEncrypter(block, iv)
     stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintextBytes)

     return string(ciphertext), nil
}

In the above code, we generate a random initialization vector (IV) to improve security. The IV is then used to initialize the AES cipher. The resulting encrypted string is returned as a base64 string for ease of storage and transmission.

To decrypt an encrypted string in Go, you need to have the secret key used for encryption. Here's how to decipher a string:


func DecryptString(key []byte, ciphertext string) (string, error) {
     block, err := aes.NewCipher(key)
     if err != nil {
         return "", err
     }

     ciphertextBytes := []byte(ciphertext)
     if len(ciphertextBytes) < aes.BlockSize {
         return "", errors.New("ciphertext is too short")
     }

     iv := ciphertextBytes[:aes.BlockSize]
     ciphertextBytes = ciphertextBytes[aes.BlockSize:]

     stream := cipher.NewCFBDecrypter(block, iv)
     stream.XORKeyStream(ciphertextBytes, ciphertextBytes)

     return string(ciphertextBytes), nil
}

In this case, we provide the secret key used for encryption and the encrypted string. After extracting the IV, we decrypt the encrypted string using the same AES algorithm with the cipher.NewCFBDecrypter method.

Here is a complete example of how to encrypt and decrypt a string in Go:


package main

import (
     "fmt"
     "crypto/aes"
     "crypto/cipher"
     "crypto/rand"
     "encoding/base64"
     "errors"
     "I"
)

func EncryptString(key []byte, plaintext string) (string, error) {
     block, err := aes.NewCipher(key)
     if err != nil {
         return "", err
     }

     plaintextBytes := []byte(plaintext)
     ciphertext := make([]byte, aes.BlockSize+len(plaintextBytes))

     iv := ciphertext[:aes.BlockSize]
     if _, err := io.ReadFull(rand.Reader, iv); err != nil {
         return "", err
     }

     stream := cipher.NewCFBEncrypter(block, iv)
     stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintextBytes)

     return base64.URLEncoding.EncodeToString(ciphertext), nil
}

func DecryptString(key []byte, ciphertext string) (string, error) {
     block, err := aes.NewCipher(key)
     if err != nil {
         return "", err
     }

     ciphertextBytes, err := base64.URLEncoding.DecodeString(ciphertext)
     if err != nil {
         return "", err
     }

     if len(ciphertextBytes) < aes.BlockSize {
         return "", errors.New("ciphertext is too short")
     }

     iv := ciphertextBytes[:aes.BlockSize]
     ciphertextBytes = ciphertextBytes[aes.BlockSize:]

     stream := cipher.NewCFBDecrypter(block, iv)
     stream.XORKeyStream(ciphertextBytes, ciphertextBytes)

     return string(ciphertextBytes), nil
}

func main() {
     key := []byte("thisisakey123456") // Secret key of 16, 24 or 32 bytes
     plaintext := "Hello, world!"

     encrypted, err := EncryptString(key, plaintext)
     if err != nil {
         fmt.Println("Error during encryption:", err)
         return
     }

     fmt.Println("Ciphertext:", encrypted)

     decrypted, err := DecryptString(key, encrypted)
     if err != nil {
         fmt.Println("Error while decrypting:", err)
         return
     }

     fmt.Println("Decrypted text:", decrypted)
}

In this example, we define a 16-byte secret key, encrypt a text string, and then successfully decrypt it using the EncryptString and DecryptStr functions. Be sure to replace the key with a strong secret key for real security purposes.

Encrypting and decrypting strings in Go may seem complex, but by using the standard crypto library, you can handle these operations securely and efficiently. Cryptography is a key part of information security, and Go offers the resources you need to effectively implement it in your projects.