在 Golang 中解密在 Python AES CFB 中加密的内容

Seb*_*ian 6 python cryptography aes go

基于关于CFB 解密Golang 文档,我编写了一个最小的工作示例来解密使用 AES CFB 加密的字符串,然后在 python3 中进行 base 64 编码。

当消息在 Golang 中加密时,golang 解密工作正常(使用来自 Golang doc 示例的加密函数)。但是,当我使用 python 加密包在 python 脚本中加密消息时,我无法在 golang 脚本中成功解密它。我没有得到正确的字节。

$ python3 stack.py 
Going to encrypt and base64 "This is not encrypted" result:
b'jf9A5LCxKWPuNb1XiH+G3APAgR//'

Now going to call the Golang script:
b'Hello from Golang, going to decrypt: jf9A5LCxKWPuNb1XiH+G3APAgR//
Result:  Tl!\xca/\xf1\xc0\xb2\xd01Y\x02V\xec\xdf\xecy\xd38&\xd9\n'
Run Code Online (Sandbox Code Playgroud)

两种 AES 实现的块大小默认为 16。

所以问题是:出了什么问题?

高朗脚本:

$ python3 stack.py 
Going to encrypt and base64 "This is not encrypted" result:
b'jf9A5LCxKWPuNb1XiH+G3APAgR//'

Now going to call the Golang script:
b'Hello from Golang, going to decrypt: jf9A5LCxKWPuNb1XiH+G3APAgR//
Result:  Tl!\xca/\xf1\xc0\xb2\xd01Y\x02V\xec\xdf\xecy\xd38&\xd9\n'
Run Code Online (Sandbox Code Playgroud)

蟒蛇脚本:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "os"

)

func main() {
    key := []byte("TfvY7I358yospfWKcoviZizOShpm5hyH")
    iv := []byte("mb13KcoviZizvYhp")
    payload_python := os.Args[1]

    fmt.Println("Hello from Golang, going to decrypt: "+payload_python+" Result: "+string(decrypt(key, payload_python, iv)))
}


func decrypt(key []byte, cryptoText string, iv []byte) []byte {
    ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)    //decode base64 coding

    //prepare decryption based on key and iv
    block, _ := aes.NewCipher(key)
    stream := cipher.NewCFBDecrypter(block, iv)

    //decrypt
    stream.XORKeyStream(ciphertext, ciphertext)

    return ciphertext
}
Run Code Online (Sandbox Code Playgroud)

eug*_*ioy 5

尝试像这样从 Python 加密。

然后可以成功地从 Go 解密结果。

 #!/usr/bin/env python3
import base64
from Crypto.Cipher import AES

MODE = AES.MODE_CFB
BLOCK_SIZE = 16
SEGMENT_SIZE = 128

def _pad_string(value):
    length = len(value)
    pad_size = BLOCK_SIZE - (length % BLOCK_SIZE)
    return value.ljust(length + pad_size, '\x00')

def encrypt(key, iv, plaintext):
    aes = AES.new(key, MODE, iv, segment_size=SEGMENT_SIZE)
    plaintext = _pad_string(plaintext)
    encrypted_text = aes.encrypt(plaintext)
    return encrypted_text

key = 'TfvY7I358yospfWKcoviZizOShpm5hyH'
iv = 'mb13KcoviZizvYhp'
original_message = 'This is not encrypted'

encryptedpayload = base64.b64encode(encrypt(key, iv, original_message))

print('Going to encrypt and base64 "{}" result:\n{}\n'.format(original_message,encryptedpayload))
Run Code Online (Sandbox Code Playgroud)

来源:http : //chase-seibert.github.io/blog/2016/01/29/cryptojs-pycrypto-ios-aes256.html