如何为Python AES CBC模式编写golang代码?

3ks5zfa0  于 2023-03-16  发布在  Go
关注(0)|答案(1)|浏览(86)

我正在尝试写以下CCAvenue支付网关Python代码的golang代码。

def pad(data):
    length = 16 - (len(data) % 16)
    data += chr(length)*length
    return data

def encrypt(plainText, workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    plainText = pad(plainText)
    encDigest = md5.new ()
    encDigest.update(workingKey)
    enc_cipher = AES.new(encDigest.digest(), AES.MODE_CBC, iv)
    encryptedText = enc_cipher.encrypt(plainText).encode('hex')
    return encryptedText

以下是相关的golang代码

func Pad(text string) string {
    length := aes.BlockSize - (len(text) % aes.BlockSize)
    pad := string(length)
    for i := 0; i < length; i++ {
        text += pad
    }
    return text
}

func Encrypt(text, key string) string {
    iv := "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
    text = Pad(text)
    h := md5.New()
    h.Write([]byte(key))
    block, err := aes.NewCipher([]byte(fmt.Sprintf("%x", h.Sum(nil))))
    if err != nil {
        return "ollo"
    }
    ciphertext := make([]byte, len([]byte(text)))   
    mode := cipher.NewCBCEncrypter(block, []byte(iv))
    mode.CryptBlocks(ciphertext, []byte(text))
    return fmt.Sprintf("%x", ciphertext)
}

这里的ciphetext和encryptedText不匹配。问题是什么?

xeufq47z

xeufq47z1#

我已经实现了加密,并在我下面提到的golang解密。

func Encrypt(plainText string, workingKey string) (string, error) {
    iv := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    plainTextBytes := []byte(pad(plainText))

    encDigest := md5.Sum([]byte(workingKey))
    encCipher, err := aes.NewCipher(encDigest[:])
    if err != nil {
        return "", err
    }

    encMode := cipher.NewCBCEncrypter(encCipher, iv)
    encryptedTextBytes := make([]byte, len(plainTextBytes))
    encMode.CryptBlocks(encryptedTextBytes, plainTextBytes)

    return hex.EncodeToString(encryptedTextBytes), nil
}

func Decrypt(encryptedText string, workingKey string) (string, error) {
    iv := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    encryptedTextBytes, err := hex.DecodeString(encryptedText)
    if err != nil {
        return "", err
    }

    decDigest := md5.Sum([]byte(workingKey))
    decCipher, err := aes.NewCipher(decDigest[:])
    if err != nil {
        return "", err
    }

    decMode := cipher.NewCBCDecrypter(decCipher, iv)
    decryptedTextBytes := make([]byte, len(encryptedTextBytes))
    decMode.CryptBlocks(decryptedTextBytes, encryptedTextBytes)

    return strings.TrimRight(string(decryptedTextBytes), "\x00"), nil
}

func pad(text string) string {
    padding := aes.BlockSize - len(text)%aes.BlockSize
    padText := bytes.Repeat([]byte{byte(padding)}, padding)
    return string(append([]byte(text), padText...))
}

相关问题