Golang:如何使用DES和CBC加密长度为5个字符的纯文本? [英] Golang: How do I encrypt plain text that is 5 characters long with DES and CBC?
本文介绍了Golang:如何使用DES和CBC加密长度为5个字符的纯文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前试图将长度为5个字符的明文加密成12个字符的加密字符串。我希望能够指定一个独特的IV(不是随机生成的),一个唯一的密钥,并使用DES。我目前的代码要求明文长度为8个字符(5个字符的名称加上3个空格)。
解决方案
我已经遇到了这个问题。这是因为填充问题。您需要的代码是
包主
导入(
crypto / cipher
crypto / des
encoding / base64
fmt
字节
)
func main(){
originalText:=yolan
fmt.Println(originalText)
key:= [] byte {0xBC,0xBC,0xBC,0xBC,0xBC ,0xBC,0xBC,0xBC}
//将值加密到base64
cryptoText:= encrypt(key,originalText)
fmt.Println(cryptoText)
$ // b使用des
将字符串加密到base64密码func encrypt(key [] byte,text string)string {
明文:= [] byte(text)
block,err:= des.NewCipher(key)
if err!= nil {
panic(err)
}
iv:= []字节{0xBC,0xBC,0xBC,0xBC,0xBC,0xBC,0xBC,0xBC}
blockSize:= block.BlockSize()
origData:= PKCS5Padding(plaintext,blockSize)
lockMode:= 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])$ b $ b return src [:( length - unpadding)]
}
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).
解决方案
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)]
}
这篇关于Golang:如何使用DES和CBC加密长度为5个字符的纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文