Table of Contents
Common error: Incorrect length of initialization vector (IV)
Correct initialization method
Things to note
Summarize
Home Backend Development Golang Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream

Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream

Sep 16, 2025 pm 12:30 PM

Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream

This article aims to help developers understand and solve nil pointer exceptions caused by XORKeyStream function that may be encountered when using the CFB (Cipher Feedback) mode of Go language for AES encryption. Ensure the encryption process goes smoothly by analyzing common causes of errors and providing the correct code examples. The focus is on the correct use of initialization vectors (IVs) and the importance of understanding the AES block size.

When using the Go language crypto/cipher package for CFB mode encryption, developers may encounter the XORKeyStream function throwing a runtime error: invalid memory address or nil pointer dereference exception. This usually indicates that the cipher stream sEnc is nil, which is often caused by errors in the initialization process.

Common error: Incorrect length of initialization vector (IV)

The cipher.NewCFBEncrypter function document clearly states that the length of the initialization vector (IV) must be consistent with the block size of the underlying block. For the AES algorithm, its block size is fixed to 128 bits, that is, 16 bytes. If the provided IV length is incorrect, the NewCFBEncryptter function may return nil or cause the program to crash in subsequent XORKeyStream calls.

Correct initialization method

The following code shows how to correctly generate AES keys and IVs and encrypt them using CFB mode:

 package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "fmt"
    "io"
    "log"
)

func main() {
    // plaintext to be encrypted := "This is a secret message."

    // Generate random AES key (256 bits)
    key := make([]byte, 32)
    if _, err := io.ReadFull(rand.Reader, key); err != nil {
        log.Fatal(err)
    }

    // Create AES cipher block block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }

    // Generate a random IV, the length must be equal to the block size iv := make([]byte, aes.BlockSize)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        log.Fatal(err)
    }

    // Create CFB encryptor stream := cipher.NewCFBEncryptter(block, iv)

    // Encryption ciphertext := make([]byte, len(plaintext))
    stream.XORKeyStream(ciphertext, []byte(plaintext))

    fmt.Printf("Plaintext: %s\n", plaintext)
    fmt.Printf("Ciphertext: %x\n", ciphertext)

    // Decrypt (example, need to create a decryptor)
    decryptedtext := make([]byte, len(ciphertext))
    streamDecrypter := cipher.NewCFBDecrypter(block, iv)
    streamDecrypter.XORKeyStream(decryptedtext, ciphertext)

    fmt.Printf("Decryptedtext: %s\n", decryptedtext)
}

Code explanation:

  1. Generate key: Use the crypto/rand package to generate a 256-bit random key.
  2. Create a cipher block: Use the aes.NewCipher(key) function to create an AES cipher block based on the key.
  3. Generate IV: Use the crypto/rand package to generate a random IV with a length equal to aes.BlockSize. aes.BlockSize constant defines the block size of the AES algorithm, i.e. 16 bytes.
  4. Create a CFB Encryptor: Use the cipher.NewCFBEncrypter(block, iv) function to create a CFB Encryptor based on the cipher block and IV.
  5. Encryption: Use the stream.XORKeyStream(ciphertext, []byte(plaintext)) function to encrypt the plaintext, and the result is stored in the ciphertext.
  6. Decryption: For demonstration, the corresponding decryption code is added here, using cipher.NewCFBDecrypter to create the decryptor, and then using XORKeyStream to decrypt the cipher text.

Things to note

  • Key security: In practical applications, keys must be stored and managed securely. For the sake of demonstration convenience, the sample code generates and uses keys directly in memory, which is not desirable in production environments.
  • Uniqueness of IV: For each encryption operation, the IV must be unique. Reusing the same IV can cause security issues. IVs are usually generated using random numbers.
  • Error handling: The sample code contains basic error handling. In practical applications, various possible error situations should be handled more thoroughly.
  • Features of CFB mode: CFB mode is a stream cipher mode that converts block passwords to stream ciphers. This means it can encrypt data of any length without having to fill it. However, the security of CFB mode depends on the security of the underlying block password and the correct use of IVs.

Summarize

When using the CFB mode of Go for AES encryption, be sure to ensure that the length of the initialization vector (IV) is consistent with the AES block size (16 bytes). Proper generation and use of IVs is the key to ensuring encryption security. At the same time, pay attention to the secure storage and management of keys and complete error handling. By following these best practices, nil pointer exceptions caused by XORKeyStream functions can be avoided and a secure encryption process can be implemented.

The above is the detailed content of Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

What is the empty struct struct{} used for in Golang What is the empty struct struct{} used for in Golang Sep 18, 2025 am 05:47 AM

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

Resolve Go WebSocket EOF error: Keep the connection active Resolve Go WebSocket EOF error: Keep the connection active Sep 16, 2025 pm 12:15 PM

This article aims to resolve EOF (End-of-File) errors encountered when developing WebSocket using Go. This error usually occurs when the server receives the client message and the connection is unexpectedly closed, resulting in the subsequent messages being unable to be delivered normally. This article will analyze the causes of the problem, provide code examples, and provide corresponding solutions to help developers build stable and reliable WebSocket applications.

Start an external editor in the Go program and wait for it to complete Start an external editor in the Go program and wait for it to complete Sep 16, 2025 pm 12:21 PM

This article describes how to start an external editor (such as Vim or Nano) in a Go program and wait for the user to close the editor before the program continues to execute. By setting cmd.Stdin, cmd.Stdout, and cmd.Stderr, the editor can interact with the terminal to solve the problem of startup failure. At the same time, a complete code example is shown and precautions are provided to help developers implement this function smoothly.

How do you read and write files in Golang? How do you read and write files in Golang? Sep 21, 2025 am 01:59 AM

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

How to read configuration from files in Golang How to read configuration from files in Golang Sep 18, 2025 am 05:26 AM

Use the encoding/json package of the standard library to read the JSON configuration file; 2. Use the gopkg.in/yaml.v3 library to read the YAML format configuration; 3. Use the os.Getenv or godotenv library to overwrite the file configuration; 4. Use the Viper library to support advanced functions such as multi-format configuration, environment variables, automatic reloading; it is necessary to define the structure to ensure type safety, properly handle file and parsing errors, correctly use the structure tag mapping fields, avoid hard-coded paths, and recommend using environment variables or safe configuration storage in the production environment. It can start with simple JSON and migrate to Viper when the requirements are complex.

What are middleware in the context of Golang web servers? What are middleware in the context of Golang web servers? Sep 16, 2025 am 02:16 AM

MiddlewareinGowebserversarefunctionsthatinterceptHTTPrequestsbeforetheyreachthehandler,enablingreusablecross-cuttingfunctionality;theyworkbywrappinghandlerstoaddpre-andpost-processinglogicsuchaslogging,authentication,CORS,orerrorrecovery,andcanbechai

Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream Go language CFB mode encryption: Solve nil pointer exception of XORKeyStream Sep 16, 2025 pm 12:30 PM

This article aims to help developers understand and solve nil pointer exceptions caused by XORKeyStream function that may be encountered when using the CFB (Cipher Feedback) mode of Go language for AES encryption. Ensure the encryption process goes smoothly by analyzing common causes of errors and providing the correct code examples. The focus is on the correct use of initialization vectors (IVs) and the importance of understanding the AES block size.

How to compile Go for a different architecture (ARM) How to compile Go for a different architecture (ARM) Sep 16, 2025 am 12:27 AM

To compile Go code for ARM architecture, simply set the environment variables and use the gobuild command. 1. Set GOOS=linux and GOARCH=arm (32-bit) or arm64 (64-bit) to specify the target platform. 2. Optionally, set GOARM=7 for 32-bit ARM to specify the ARMv7 instruction set. 3. If no CGO is required, set CGO_ENABLED=0 to ensure static linking. 4. Run the command such as GOOS=linuxGOARCH=arm64CGO_ENABLED=0gobuild-omyapp-arm64 to generate a binary file. 5. Copy the generated binary file to an ARM device (such as Raspber

See all articles