dsgwoh7038 2017-01-05 17:11
浏览 145
已采纳

Golang:如何使用DES和CBC加密5个字符长的纯文本?

Currently trying to encrypt plaintext that is 5 characters long into a 12 character encrypted string. I want to be able to specify a unique IV (not randomly generated), a unique key, and use DES. My current code requires the plaintext to be 8 characters long (5 character name plus 3 spaces).

  • 写回答

1条回答 默认 最新

  • doujiaoang69440 2017-01-06 05:43
    关注

    I have already faced this problem. This is because of padding issue. The code you wanted is a

    Code link You Can test it at go playground.

      package main
    
      import (
        "crypto/cipher"
        "crypto/des"
        "encoding/base64"
        "fmt"
        "bytes"
      )
    
      func main() {
        originalText := "yolan"
        fmt.Println(originalText)
    
        key := []byte{0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC}
    
        // encrypt value to base64
        cryptoText := encrypt(key, originalText)
        fmt.Println(cryptoText)
    
      }
    
      // encrypt string to base64 crypto using des
      func encrypt(key []byte, text string) string {
        plaintext := []byte(text)
    
        block, err := des.NewCipher(key)
        if err != nil {
            panic(err)
        }
    
        iv := []byte{0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC}
    
        blockSize := block.BlockSize()
        origData := PKCS5Padding(plaintext, blockSize)
        blockMode := cipher.NewCBCEncrypter(block, iv)
        cryted := make([]byte, len(origData))
        blockMode.CryptBlocks(cryted, origData)
    
        return base64.URLEncoding.EncodeToString(cryted)
      }
    
      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)]
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用