douchou8935 2017-01-10 22:10
浏览 1311
已采纳

Golang:如何使用DES,CBC和PKCS7解密?

Currently trying to figure out why my decryption method is not working. I used DES, CBC, and PKCS7Padding to encrypt my string. My current code outputs panic: crypto/cipher: input not full blocks during decryption.

  • 写回答

1条回答 默认 最新

  • dsfdfd1211 2017-01-11 16:13
    关注

    Buddy it's work completely fine.

    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))
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 如何批量获取json的url
  • ¥15 对法兰连接元件所承受的表面载荷等效转化为法兰开孔接触面上的等效表面载荷?
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼