首页 > 解决方案 > Go lang 3DES 部分解密了加密字符串

问题描述

使用3des解密时给定的加密文本没有完全解密,不知道哪里出错了,帮我完成解密错误

该代码可在Go Playground for Insection 获得并运行

package main

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

func main() {

    // Mimimum Key Size of Length 24
    key := "mysecretPasswordkeySiz24"
    plainText := "https://8gwifi.org"
    ct := EncryptTripleDES([]byte(key),plainText)
    fmt.Printf("Original Text:  %s\n",plainText)
    fmt.Printf("3DES Encrypted Text:  %s\n", ct)
    DecryptTripleDES([]byte(key),ct)

}

func EncryptTripleDES(key []byte, plaintext string) string {
        c,err := des.NewTripleDESCipher(key)
    if err != nil {
        fmt.Errorf("NewTripleDESCipher(%d bytes) = %s", len(key), err)
        panic(err)
    }

    out := make([]byte, len(plaintext))
    c.Encrypt(out, []byte(plaintext))
    return hex.EncodeToString(out)

    }


func DecryptTripleDES(key []byte, ct string) {

        ciphertext, _ := hex.DecodeString(ct)
        c, err := des.NewTripleDESCipher([]byte(key))
        if err != nil {
            fmt.Errorf("NewTripleDESCipher(%d bytes) = %s", len(key), err)
            panic(err)
        }
        plain := make([]byte, len(ciphertext))
        c.Decrypt(plain, ciphertext)
        s := string(plain[:])
        fmt.Printf("3DES Decrypyed Text:  %s\n", s)
}

输出

Original Text:  https://8gwifi.org
3DES Encrypted Text:  a6e5215154bf86d000000000000000000000
3DES Decrypyed Text:  https://

标签: goencryptiondes3des

解决方案


给定的加密文本未完全解密

您提供的加密文本已完全解密。问题不是(还)解密,而是你的加密。如记录des.NewTripleDESCipher的返回 acipher.Blockcipher.Block.Encrypt仅加密输入数据的第一个块。鉴于 DES 的块大小为 8 字节,只有输入数据的前 8 个字节被加密,即https://.

这意味着为了加密所有数据,您必须加密所有块。类似地,您需要在解密时解密所有块 - 但cipher.Block.Decrypt也只解密一个块。

除了 DES 坏了,所以不要将它用于严重的事情。


推荐阅读