Loo*_*per 4 python encryption encoding aes go
我希望能够在 Go 中解密在 Python 中加密的内容。加密/解密函数分别在每种语言中工作,但当我在 Python 中加密并在 Go 中解密时则不然,我猜测编码有问题,因为我得到了乱码输出:
\nRx\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdd\xef\xbf\xbd\xef\xbf\xbdI\xef\xbf\xbdK|\xef\xbf\xbdap\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdk\xef\xbf\xbd\xef\xbf\xbdB%F\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdUV\xef\xbf\xbd~d3h\xef\xbf\xbd\xc3\x91\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd|\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd>\xef\xbf\xbdB\xef\xbf\xbd\xef\xbf\xbdB\xef\xbf\xbd\nRun Code Online (Sandbox Code Playgroud)\ndef encrypt(plaintext, key=config.SECRET, key_salt='', no_iv=False):\n """Encrypt shit the right way"""\n\n # sanitize inputs\n key = SHA256.new((key + key_salt).encode()).digest()\n if len(key) not in AES.key_size:\n raise Exception()\n if isinstance(plaintext, string_types):\n plaintext = plaintext.encode('utf-8')\n\n # pad plaintext using PKCS7 padding scheme\n padlen = AES.block_size - len(plaintext) % AES.block_size\n plaintext += (chr(padlen) * padlen).encode('utf-8')\n\n # generate random initialization vector using CSPRNG\n if no_iv:\n iv = ('\\0' * AES.block_size).encode()\n else:\n iv = get_random_bytes(AES.block_size)\n log.info(AES.block_size)\n # encrypt using AES in CFB mode\n ciphertext = AES.new(key, AES.MODE_CFB, iv).encrypt(plaintext)\n\n # prepend iv to ciphertext\n if not no_iv:\n ciphertext = iv + ciphertext\n # return ciphertext in hex encoding\n log.info(ciphertext)\n return ciphertext.hex()\n\n\ndef decrypt(ciphertext, key=config.SECRET, key_salt='', no_iv=False):\n """Decrypt shit the right way"""\n\n # sanitize inputs\n key = SHA256.new((key + key_salt).encode()).digest()\n if len(key) not in AES.key_size:\n raise Exception()\n if len(ciphertext) % AES.block_size:\n raise Exception()\n try:\n ciphertext = codecs.decode(ciphertext, 'hex')\n except TypeError:\n log.warning("Ciphertext wasn't given as a hexadecimal string.")\n\n # split initialization vector and ciphertext\n if no_iv:\n iv = '\\0' * AES.block_size\n else:\n iv = ciphertext[:AES.block_size]\n ciphertext = ciphertext[AES.block_size:]\n\n # decrypt ciphertext using AES in CFB mode\n plaintext = AES.new(key, AES.MODE_CFB, iv).decrypt(ciphertext).decode()\n\n # validate padding using PKCS7 padding scheme\n padlen = ord(plaintext[-1])\n if padlen < 1 or padlen > AES.block_size:\n raise Exception()\n if plaintext[-padlen:] != chr(padlen) * padlen:\n raise Exception()\n plaintext = plaintext[:-padlen]\n\n return plaintext\nRun Code Online (Sandbox Code Playgroud)\n// PKCS5Padding adds padding to the plaintext to make it a multiple of the block size\nfunc PKCS5Padding(src []byte, blockSize int) []byte {\n padding := blockSize - len(src)%blockSize\n padtext := bytes.Repeat([]byte{byte(padding)}, padding)\n return append(src, padtext...)\n}\n\n// Encrypt encrypts the plaintext,the input salt should be a random string that is appended to the plaintext\n// that gets fed into the one-way function that hashes it.\nfunc Encrypt(plaintext) string {\n h := sha256.New()\n h.Write([]byte(os.Getenv("SECRET")))\n key := h.Sum(nil)\n plaintextBytes := PKCS5Padding([]byte(plaintext), aes.BlockSize)\n block, err := aes.NewCipher(key)\n if err != nil {\n panic(err)\n }\n // The IV needs to be unique, but not secure. Therefore it's common to\n // include it at the beginning of the ciphertext.\n ciphertext := make([]byte, aes.BlockSize+len(plaintextBytes))\n iv := ciphertext[:aes.BlockSize]\n if _, err := io.ReadFull(rand.Reader, iv); err != nil {\n panic(err)\n }\n stream := cipher.NewCFBEncrypter(block, iv)\n stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintextBytes)\n // return hexadecimal representation of the ciphertext\n return hex.EncodeToString(ciphertext)\n}\nfunc PKCS5UnPadding(src []byte) []byte {\n length := len(src)\n unpadding := int(src[length-1])\n return src[:(length - unpadding)]\n}\nfunc Decrypt(ciphertext string) string {\n\n h := sha256.New()\n // have to check if the secret is hex encoded\n h.Write([]byte(os.Getenv("SECRET")))\n key := h.Sum(nil)\n ciphertext_bytes := []byte(ciphertext)\n block, err := aes.NewCipher(key)\n if err != nil {\n panic(err)\n }\n log.Print(aes.BlockSize)\n // The IV needs to be unique, but not secure. Therefore it's common to\n // include it at the beginning of the ciphertext.\n iv := ciphertext_bytes[:aes.BlockSize]\n if len(ciphertext) < aes.BlockSize {\n panic("ciphertext too short")\n }\n ciphertext_bytes = ciphertext_bytes[aes.BlockSize:]\n stream := cipher.NewCFBDecrypter(block, iv)\n stream.XORKeyStream(ciphertext_bytes, ciphertext_bytes)\n plaintext := PKCS5UnPadding(ciphertext_bytes)\n return string(plaintext)\n}\n \nRun Code Online (Sandbox Code Playgroud)\n
CFB 模式使用与每个加密步骤加密的位相对应的段大小,请参阅CFB。
Go 仅支持 128 位(CFB128)的段大小,至少没有更深入的修改(参见此处和此处)。相比之下,PyCryptodome 中的段大小是可配置的,默认为 8 位 (CFB8),s。这里。发布的Python代码使用这个默认值,因此两个代码不兼容。由于Go代码中段大小不可调整,因此必须在Python代码中将其设置为CFB128:
cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
Run Code Online (Sandbox Code Playgroud)
另外,密文在Python代码中是十六进制编码的,因此它必须在Go代码中进行十六进制解码,而这在发布的代码中还没有发生。
通过这两项更改,可以解密使用 Python 代码生成的密文。
以下 Go 代码中的密文是使用 Python 代码使用 128 位大小的段和密码创建的my passphrase,并已成功解密:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
ciphertextHex := "546ddf226c4c556c7faa386940f4fff9b09f7e3a2ccce2ed26f7424cf9c8cd743e826bc8a2854bb574df9f86a94e7b2b1e63886953a6a3eb69eaa5fa03d69ba5" // Fix 1: Apply CFB128 on the Python side
fmt.Println(Decrypt(ciphertextHex)) // The quick brown fox jumps over the lazy dog
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
func Decrypt(ciphertext string) string {
h := sha256.New()
//h.Write([]byte(os.Getenv("SECRET")))
h.Write([]byte("my passphrase")) // Apply passphrase from Python side
key := h.Sum(nil)
//ciphertext_bytes := []byte(ciphertext)
ciphertext_bytes, _ := hex.DecodeString(ciphertext) // Fix 2. Hex decode ciphertext
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
iv := ciphertext_bytes[:aes.BlockSize]
if len(ciphertext) < aes.BlockSize {
panic("ciphertext too short")
}
ciphertext_bytes = ciphertext_bytes[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext_bytes, ciphertext_bytes)
plaintext := PKCS5UnPadding(ciphertext_bytes)
return string(plaintext)
}
Run Code Online (Sandbox Code Playgroud)
安全:
salt|IV|ciphertext。no_iv=True应用静态 IV(零 IV),这是不安全的,不应使用。正确的方法用变体描述no_iv=False。