doubianyan9749 2017-03-13 19:49
浏览 39

Golang加密密文开头以As填充

I'm trying to use a custom IV for encryption but it results in a ciphertext with padding of As in the beginning like

AAAAAAAAAAAAAAAAAAAAACbglBtdgH3ajX1jgkOaVAsFYyDxRRI=

I followed the sample implementation at https://gist.github.com/manishtpatel/8222606 with a few changes. The go playground to run and test https://play.golang.org/p/2rS6zBwbnF

My code is at
https://play.golang.org/p/qlx_cU0VPQ

Here is the encrypt function for references as well

func Encrypt(key []byte, text string) string {
    // key := []byte(keyText)
    plaintext := []byte(text)

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // The IV needs to be unique, but not secure. Therefore it's common to
    // include it at the beginning of the ciphertext.
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := commonIV

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

    // convert to base64
    return base64.URLEncoding.EncodeToString(ciphertext)
}
  • 写回答

1条回答 默认 最新

  • douqujin2767 2017-03-13 20:02
    关注

    See this example for golang aes encryption, if you don't need to use AES CFB specifically you could just swap out your encrypt function and use GCM instead. TL;DR- Copy & paste your crypto code from this link instead of Stack Overflow.

    https://github.com/gtank/cryptopasta/blob/master/encrypt.go

    If you're just learning watch the associated talk and read the code linked, if you're actually encrypting with this, use the linked code.

    PS I'm no expert but your iv should be random each time shouldn't it? To fix your code above you need to copy the iv/nonce in with something like:

    copy(ciphertext[:aes.BlockSize], iv[:])

    the idea is the unique random nonce is at the start of ciphertext, and used to decrypt (so commonIV shouldn't exist) this stops it producing the same output for the same cleartext. Note how your code when fixed produces the same output each time - that's bad.

    But please, don't use advice from people on stack overflow for crypto, and certainly not from me, see the links here instead, and heed the instructions. This stuff is too hard to work out by trial and error.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大