donglou1866 2016-10-30 05:13
浏览 99
已采纳

在Go和OpenSSL中解密文件时结果不同

I have written the following code to decrypt a file:

data, err := ioutil.ReadFile("file.encrypted")
if err != nil {
    log.Fatal(err)
}

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

mode := cipher.NewCBCDecrypter(block, iv)

mode.CryptBlocks(data, data)

err = ioutil.WriteFile("file.decrypted", data, 0644)
if err != nil {
    log.Fatal(err)
}

I have also decrypted the file using OpenSSL:

openssl aes-128-cbc -d -in file.encrypted -out file.decrypted -iv $IV -K $KEY

Output file from Go program is 8 bytes larger than output file from from OpenSSL.

Tail of hexdump from file generated by OpenSSL:

ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
ff ff ff ff ff ff ff ff                           |........|

Tail of hexdump from file generated by Go program:

ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
ff ff ff ff ff ff ff ff  08 08 08 08 08 08 08 08  |................|

Why is 08 08 08 08 08 08 08 08 appended to file output from Go program?

EDIT:

As BJ Black explains, the reason for extra bytes in output from my Go program is PKCS padding.

The file is encrypted with AES in CBC mode and therefore the plain text input shall be a multiple of block size, padding is added to fulfill this requirement. AES has a block size of 16 bytes so the total number of padding bytes will always be between 1 and 16 bytes. Each padding byte has a value equal to the total number of padding bytes which in my case is 0x08.

So, to find out the amount of padding added to the file, one just have to read the last byte of decrypted file and convert that number to int:

paddingBytes := int(data[len(data)-1])

The WriteFile function can then be modified like this:

err = ioutil.WriteFile("file.decrypted", data[:len(data)-paddingBytes], 0644)

Now output from my Go program is identical to the output from OpenSSL.

  • 写回答

1条回答 默认 最新

  • doubingguan3425 2016-10-30 05:38
    关注

    What you're seeing is PKCS padding, which OSSL is removing for you and Go isn't by default. See the relevant Reddit post here.

    Basically, follow the example and you're good to go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题