aes.NewCipher返回一个有效的块,但调用block.BlockSize()时出现错误

问题描述:

I'm trying to get AES encryption and decryption working in my go API, I create a new block using aes.NewCipher(mykey) and the block seems to be valid, but then when I call cipher.NewCBCDecrypter(block, iv) the function causes a "invalid memory address or nil pointer dereference" error at line 26 in cbc.go when it tries to call b.BlockSize().

So I tried calling block.BlockSize() from my own code and I also get an exception, but when I check the block var it's not nil.

func Decrypt(data []byte) (result []byte, err error) {
    logger := logrus.New()

    logger.Infof("Starting decryption for string: %s
", string(data[:]))

    var block cipher.Block

    if block, err := aes.NewCipher([]byte(app.Config.AESKey)); (err != nil) || (block == nil) {
        logger.Infof("Failed to create block
")
        return nil, err
    }

    if len(data) < aes.BlockSize {
        logger.Infof("Input too short
")
        return nil, nil
    }

    cbc := cipher.NewCBCDecrypter(block, []byte(app.Config.AESIV))
    cbc.CryptBlocks(data, data)

    return data, nil
}

I would expect the function to work properly since aes.NewCipher doesn't return an error.

Remove this line

var block cipher.Block

As you are initializing block in the next line.

Essentially, you are creating 2 block variables.

I see my issue now, I'm not that familiar with go, so I was basically creating 2 block variables, one that was accessible function wide and one only accessible form inside the if statement.