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)] }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报