当前试图弄清楚为什么我的解密方法不起作用。我使用DES,CBC和PKCS7Padding来加密我的字符串。我当前的code在解密过程中输出panic: crypto/cipher: input not full blocks

最佳答案

伙计,它的工作完全正常。

package main

    import (
        "bytes"
        "crypto/des"
        "crypto/cipher"
        "fmt"
    )

    func DesEncryption(key, iv, plainText []byte) ([]byte, error) {

        block, err := des.NewCipher(key)

        if err != nil {
            return nil, err
        }

        blockSize := block.BlockSize()
        origData := PKCS5Padding(plainText, blockSize)
        blockMode := cipher.NewCBCEncrypter(block, iv)
        cryted := make([]byte, len(origData))
        blockMode.CryptBlocks(cryted, origData)
        return cryted, nil
    }

    func DesDecryption(key, iv, cipherText []byte) ([]byte, error) {

        block, err := des.NewCipher(key)

        if err != nil {
            return nil, err
        }

        blockMode := cipher.NewCBCDecrypter(block, iv)
        origData := make([]byte, len(cipherText))
        blockMode.CryptBlocks(origData, cipherText)
        origData = PKCS5UnPadding(origData)
        return origData, 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 PKCS5UnPadding(src []byte) []byte {
        length := len(src)
        unpadding := int(src[length-1])
        return src[:(length - unpadding)]
    }


    func main() {
        originalText := "sysys"
        fmt.Println(originalText)
        mytext := []byte(originalText)

        key := []byte{0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC }
        iv := []byte{0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC }


        cryptoText,_ := DesEncryption(key, iv, mytext)
        fmt.Println(string(cryptoText))
        decryptedText,_ := DesDecryption(key, iv, cryptoText)
        fmt.Println(string(decryptedText))

    }

关于go - Golang : How do I decrypt with DES, CBC和PKCS7?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41579325/

10-12 05:11