在Go代码中,使用的是CBC模式加密,而在Python代码中,使用的是ECB模式加密。这是造成结果不一致的一个原因。

另外,Go代码中的PKCS5Padding函数实现有误。应该使用PKCS7填充方式,而不是PKCS5。以下是修正后的Go代码:

package main

import (
	"crypto/cipher"
	"crypto/des"
	"encoding/hex"
	"fmt"
)

func desEncrypt(key []byte, plaintext []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	plaintext = PKCS7Padding(plaintext, blockSize)
	ciphertext := make([]byte, len(plaintext))
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	blockMode.CryptBlocks(ciphertext, plaintext)
	return ciphertext, nil
}

func PKCS7Padding(src []byte, blockSize int) []byte {
	padding := blockSize - len(src)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padText...)
}

func main() {
	key := []byte("51434574")
	plaintext := []byte("catcatcat1206")

	ciphertext, err := desEncrypt(key, plaintext)
	if err != nil {
		panic(err)
	}

	encoded := hex.EncodeToString(ciphertext)
	fmt.Println(encoded)
}

修正后的代码输出结果为C2C6FFBC6518A166599CCF12B0103450,与Python代码的输出结果一致

package mainimport 	cryptocipher	cryptodes	encodinghex	bytes	fmtfunc desEncryptkey byte plaintext byte byte error 	block err = desNewCipherkey	if err != nil 		return nil err		blockSize = blockBlockSiz

原文地址: https://www.cveoy.top/t/topic/i0Lj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录