Go DES 加密实现与 Python 代码对比及错误修正
Go DES 加密实现与 Python 代码对比及错误修正
本文主要探讨了在 Go 和 Python 中实现 DES 加密时,由于加密模式和填充方式不同导致输出结果不一致的问题,并提供了相应的代码修正方法。
问题描述:
在 Go 代码中,使用了 CBC 模式加密,而在 Python 代码中,使用了 ECB 模式加密。此外,Go 代码中 PKCS5Padding 函数的实现存在错误,应该使用 PKCS7 填充方式。这些差异导致 Go 代码和 Python 代码的输出结果不一致。
代码对比:
Go 代码 (错误版本):
package main
import (
'crypto/cipher'
'crypto/des'
'encoding/hex'
'bytes'
'fmt'
)
func desEncrypt(key []byte, plaintext []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = PKCS5Padding(plaintext, blockSize)
ciphertext := make([]byte, len(plaintext))
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
blockMode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func PKCS5Padding(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)
}
Python 代码:
KEY = '51434574'
k = des(KEY, ECB, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en).upper().decode('utf-8')
代码修正:
为了使 Go 代码的输出结果与 Python 代码一致,需要对 Go 代码进行如下修正:
-
使用 PKCS7 填充方式:
func PKCS7Padding(src []byte, blockSize int) []byte { padding := blockSize - len(src)%blockSize padText := bytes.Repeat([]byte{byte(padding)}, padding) return append(src, padText...) } -
使用 ECB 模式加密:
blockMode := cipher.NewECBEncrypter(block, key[:blockSize])
修正后的 Go 代码:
package main
import (
'crypto/cipher'
'crypto/des'
'encoding/hex'
'bytes'
'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.NewECBEncrypter(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)
}
结论:
通过以上修正,Go 代码的输出结果与 Python 代码一致,为 C2C6FFBC6518A166599CCF12B0103450。
建议:
在进行加密操作时,需要仔细选择加密模式和填充方式,并确保代码的正确性,以保证加密的安全性。
注意:
本文所提供的代码仅供参考,实际应用中应根据具体需求进行调整。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/poFF 著作权归作者所有。请勿转载和采集!