没有IV的AES128

标签 go

我正在尝试解密一些没有 IV 的 AES128 数据。 Go 提供了使用 IV 解密的简单方法,但我不知道如何不使用 IV。到目前为止,这是我所拥有的:

block, err := aes.NewCipher(key)

if err != nil {
    panic(err)
}

if len(data)%aes.BlockSize != 0 {
    panic("ciphertext is not a multiple of the block size")
}

fmt.Printf("Decyphered:\n%s\n", data)

所以我正在努力弄清楚如何使用该 block 进行解密。

谢谢...

最佳答案

我假设您在这里使用的是 CBC,但 CFB 模式的工作原理应该相同。

请注意,由于 IV 不被认为是 secret 的,因此为了方便起见,它通常被添加到密文本身的前面。

由于这些模式处理 IV 的方式,如果您使用不正确的 IV,您只会丢失第一个明文 block 。如果实际的 IV 在那里,您最终会在明文输出的开头解密随机数据,因此简单地尝试用空 IV 解密它并没有什么坏处。但是,如果没有原始 IV,您将无法取回第一个 block (除非使用蛮力)。

Example

key := []byte("YELLOW SUBMARINE")
plaintext := []byte("exampleplaintext that is longer than a single block and some pad")

if len(plaintext)%aes.BlockSize != 0 {
    panic("plaintext not multiple of block size")
}

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 := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    panic(err)
}

mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
fmt.Printf("%x\n", ciphertext)

// Now Decrypt with wrong IV
iv = make([]byte, 16)

// If you wanted the correct IV, in thise case we could pull it from the ciphertext
//iv = ciphertext[:aes.BlockSize]
//ciphertext = ciphertext[aes.BlockSize:]

if len(ciphertext)%aes.BlockSize != 0 {
    panic("ciphertext is not a multiple of the block size")
}

mode = cipher.NewCBCDecrypter(block, iv)
newPlaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(newPlaintext, ciphertext)

fmt.Printf("%s\n", newPlaintext)

关于没有IV的AES128,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25290596/

相关文章:

json - 在 golang 版本之间使用自定义解码器解析 json 的差异

go - 同一项目中的多个模块

shell - 流式 exec.Command StdoutPipe

go - 是什么让 http.server 使用 HTTP/2?

go - 如何在 Go 中重用原始的 strings.Reader?

Go - 运算符重载

go 不能在模板执行的参数中使用输出(字符串类型)作为 io.Writer 类型

xml - 如何从 xml(包括标签)中提取完整的 html?

mysql - Golang 将映射键设置为其值的变量

algorithm - 实时显示一段时间内最常见/重复的元素