Golang: How do I encrypt plain text that is 5 characters long with DES and CBC?

二次信任 提交于 2019-12-09 14:17:32

问题


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:


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)]
  }


来源:https://stackoverflow.com/questions/41490851/golang-how-do-i-encrypt-plain-text-that-is-5-characters-long-with-des-and-cbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!