<p>I have an example program where given a padded aes-encrypted ciphertext and a key, it outputs the decrypted url. Knowing that the input is padded via Pkcs7, I assumed that I would have to unpad the output. However, the program still produces the correct output, regardless of whether I unpad it or not. </p>
<pre><code>func main() {
ciphertext := ciphertext(b64_cipher)
iv := iv(vector)
key := sha(secret)
block, _ := aes.NewCipher(key[:])
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
url := fmt.Sprintf("%s",ciphertext)
fmt.Println(url) // This works for a padded input!
}
</code></pre>
<p>Does the standard library's <a href="https://golang.org/pkg/crypto/cipher/#NewCBCDecrypter" rel="nofollow">CBC decrypter</a> automatically unpad the output? Forgive me for sounding noobish, but what is the reason behind it? Thanks</p>
<hr/>**评论:**<br/><br/>alexwhoizzle: <pre><p>No it doesn't. Looking at the example in the docs (<a href="https://golang.org/pkg/crypto/cipher/#example_NewCBCDecrypter" rel="nofollow">https://golang.org/pkg/crypto/cipher/#example_NewCBCDecrypter</a>) it says: </p>
<blockquote>
<p>If the original plaintext lengths are not a multiple of the block
size, padding would have to be added when encrypting, which would be
removed at this point. For an example, see
<a href="https://tools.ietf.org/html/rfc5246#section-6.2.3.2" rel="nofollow">https://tools.ietf.org/html/rfc5246#section-6.2.3.2</a>. However, it's
critical to note that ciphertexts must be authenticated (i.e. by
using crypto/hmac) before being decrypted in order to avoid creating
a padding oracle.</p>
</blockquote>
<p>You will need to remove the padding yourself. But also remember, you need to authenticate the ciphertext if you are not currently. </p></pre>smasher164: <pre><p>So I'm guessing the input was not properly padded then, since it isn't my own ciphertext. Anyways, thank you!</p></pre>alexwhoizzle: <pre><p>Yea I'd assume so. The byte length of the plaintext must happen to be a multiple of 16, so the CBC decryptor won't panic (see here: <a href="https://github.com/golang/go/blob/master/src/crypto/cipher/cbc.go#L113" rel="nofollow">https://github.com/golang/go/blob/master/src/crypto/cipher/cbc.go#L113</a>). Even so, it's good practice to always pad your messages even if the length of the message is a multiple of 16 so it doesn't become ambigious when decrypting. </p></pre>alexfiori: <pre><p>It won't pad or unpad, you have to do that yourself.
Here's a reference for pkcs7 pad/unpad code: <a href="https://github.com/go-web/tokenizer/blob/master/pkcs7.go" rel="nofollow">https://github.com/go-web/tokenizer/blob/master/pkcs7.go</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传