问题
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